FoxARMBackend.Mod 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881
  1. MODULE FoxARMBackend; (** AUTHOR ""; PURPOSE "backend for ARM (advanced RISC machines)"; *)
  2. IMPORT
  3. Basic := FoxBasic, SyntaxTree := FoxSyntaxTree, Global := FoxGlobal, Backend := FoxBackend, Sections := FoxSections,
  4. IntermediateCode := FoxIntermediateCode, IntermediateBackend := FoxIntermediateBackend, CodeGenerators := FoxCodeGenerators, BinaryCode := FoxBinaryCode,
  5. SemanticChecker := FoxSemanticChecker, Formats := FoxFormats, Assembler := FoxARMAssembler, InstructionSet := FoxARMInstructionSet,
  6. SYSTEM, Diagnostics, Streams, Options, Strings, ObjectFile, Scanner := FoxScanner, ObjectFileFormat := FoxGenericObjectFile,
  7. D := Debugging;
  8. CONST
  9. Trace = FALSE; (* general trace *)
  10. DefaultRuntimeModuleName = "ARMRuntime";
  11. None = -1;
  12. (* parts of an ARM operand *)
  13. Low = 0; High = 1;
  14. (* mnemonics of the ARM instruction set *)
  15. opADC = InstructionSet.opADC; opADD = InstructionSet.opADD;
  16. opAND = InstructionSet.opAND; opB = InstructionSet.opB;
  17. opBIC = InstructionSet.opBIC; opBKPT = InstructionSet.opBKPT;
  18. opBL = InstructionSet.opBL; opBLX = InstructionSet.opBLX;
  19. opBX = InstructionSet.opBX; opCDP = InstructionSet.opCDP;
  20. opCDP2 = InstructionSet.opCDP2; opCLZ = InstructionSet.opCLZ;
  21. opCMN = InstructionSet.opCMN; opCMP = InstructionSet.opCMP;
  22. opEOR = InstructionSet.opEOR; opFABSD = InstructionSet.opFABSD;
  23. opFABSS = InstructionSet.opFABSS; opFADDD = InstructionSet.opFADDD;
  24. opFADDS = InstructionSet.opFADDS; opFCMPD = InstructionSet.opFCMPD;
  25. opFCMPED = InstructionSet.opFCMPED; opFCMPES = InstructionSet.opFCMPES;
  26. opFCMPEZD = InstructionSet.opFCMPEZD; opFCMPEZS = InstructionSet.opFCMPEZS;
  27. opFCMPS = InstructionSet.opFCMPS; opFCMPZD = InstructionSet.opFCMPZD;
  28. opFCMPZS = InstructionSet.opFCMPZS; opFCPYD = InstructionSet.opFCPYD;
  29. opFCPYS = InstructionSet.opFCPYS; opFCVTDS = InstructionSet.opFCVTDS;
  30. opFCVTSD = InstructionSet.opFCVTSD; opFDIVD = InstructionSet.opFDIVD;
  31. opFDIVS = InstructionSet.opFDIVS; opFLDD = InstructionSet.opFLDD;
  32. opFLDMIAD = InstructionSet.opFLDMIAD; opFLDMIAS = InstructionSet.opFLDMIAS;
  33. opFLDMIAX = InstructionSet.opFLDMIAX; opFLDMDBD = InstructionSet.opFLDMDBD;
  34. opFLDMDBS = InstructionSet.opFLDMDBS; opFLDMDBX = InstructionSet.opFLDMDBX;
  35. opFLDS = InstructionSet.opFLDS; opFMACD = InstructionSet.opFMACD;
  36. opFMACS = InstructionSet.opFMACS; opFMDHR = InstructionSet.opFMDHR;
  37. opFMDLR = InstructionSet.opFMDLR; opFMRDH = InstructionSet.opFMRDH;
  38. opFMRDL = InstructionSet.opFMRDL; opFMRS = InstructionSet.opFMRS;
  39. opFMRX = InstructionSet.opFMRX; opFMSCD = InstructionSet.opFMSCD;
  40. opFMSCS = InstructionSet.opFMSCS; opFMSR = InstructionSet.opFMSR;
  41. opFMSTAT = InstructionSet.opFMSTAT; opFMULD = InstructionSet.opFMULD;
  42. opFMULS = InstructionSet.opFMULS; opFMXR = InstructionSet.opFMXR;
  43. opFNEGD = InstructionSet.opFNEGD; opFNEGS = InstructionSet.opFNEGS;
  44. opFNMACD = InstructionSet.opFNMACD; opFNMACS = InstructionSet.opFNMACS;
  45. opFNMSCD = InstructionSet.opFNMSCD; opFNMSCS = InstructionSet.opFNMSCS;
  46. opFNMULD = InstructionSet.opFNMULD ; opFNMULS = InstructionSet.opFNMULS;
  47. opFSITOD = InstructionSet.opFSITOD; opFSITOS = InstructionSet.opFSITOS;
  48. opFSQRTD = InstructionSet.opFSQRTD; opFSQRTS = InstructionSet.opFSQRTS;
  49. opFSTD = InstructionSet.opFSTD; opFSTMIAD = InstructionSet.opFSTMIAD;
  50. opFSTMIAS = InstructionSet.opFSTMIAS; opFSTMIAX = InstructionSet.opFSTMIAX;
  51. opFSTMDBD = InstructionSet.opFSTMDBD; opFSTMDBS = InstructionSet.opFSTMDBS;
  52. opFSTMDBX = InstructionSet.opFSTMDBX; opFSTS = InstructionSet.opFSTS;
  53. opFSUBD = InstructionSet.opFSUBD; opFSUBS = InstructionSet.opFSUBS;
  54. opFTOSID = InstructionSet.opFTOSID; opFTOSIZD = InstructionSet.opFTOSIZD;
  55. opFTOSIS = InstructionSet.opFTOSIS; opFTOSIZS = InstructionSet.opFTOSIZS;
  56. opFTOUID = InstructionSet.opFTOUID; opFTOUIZD = InstructionSet.opFTOUIZD;
  57. opFTOUIS = InstructionSet.opFTOUIS; opFTOUIZS = InstructionSet.opFTOUIZS;
  58. opFUITOD = InstructionSet.opFUITOD; opFUITOS = InstructionSet.opFUITOS;
  59. opLDC = InstructionSet.opLDC; opLDC2 = InstructionSet.opLDC2;
  60. opLDM = InstructionSet.opLDM; opLDR = InstructionSet.opLDR;
  61. opLDREX = InstructionSet.opLDREX; opSTREX = InstructionSet.opSTREX;
  62. opMCR = InstructionSet.opMCR; opMCR2 = InstructionSet.opMCR2;
  63. opMCRR = InstructionSet.opMCRR; opMLA = InstructionSet.opMLA;
  64. opMOV = InstructionSet.opMOV; opMRC = InstructionSet.opMRC;
  65. opMRC2 = InstructionSet.opMRC2; opMRRC = InstructionSet.opMRRC;
  66. opMRS = InstructionSet.opMRS; opMSR = InstructionSet.opMSR;
  67. opMUL = InstructionSet.opMUL; opMVN = InstructionSet.opMVN;
  68. opORR = InstructionSet.opORR; opPLD = InstructionSet.opPLD;
  69. opQADD = InstructionSet.opQADD; opQDADD = InstructionSet.opQDADD;
  70. opQDSUB = InstructionSet.opQDSUB; opQSUB = InstructionSet.opQSUB;
  71. opRSB = InstructionSet.opRSB; opRSC = InstructionSet.opRSC;
  72. opSBC = InstructionSet.opSBC; opSMLABB = InstructionSet.opSMLABB;
  73. opSMLABT = InstructionSet.opSMLABT; opSMLAL = InstructionSet.opSMLAL;
  74. opSMLATB = InstructionSet.opSMLATB; opSMLATT = InstructionSet.opSMLATT;
  75. opSMLALBB = InstructionSet.opSMLALBB; opSMLALBT = InstructionSet.opSMLALBT;
  76. opSMLALTB = InstructionSet.opSMLALTB; opSMLALTT = InstructionSet.opSMLALTT;
  77. opSMLAWB = InstructionSet.opSMLAWB; opSMLAWT = InstructionSet.opSMLAWT;
  78. opSMULBB = InstructionSet.opSMULBB; opSMULBT = InstructionSet.opSMULBT;
  79. opSMULTB = InstructionSet.opSMULTB; opSMULTT = InstructionSet.opSMULTT;
  80. opSMULWB = InstructionSet.opSMULWB; opSMULWT = InstructionSet.opSMULWT;
  81. opSMULL = InstructionSet.opSMULL; opSTC = InstructionSet.opSTC;
  82. opSTC2 = InstructionSet.opSTC2; opSTM = InstructionSet.opSTM;
  83. opSTR = InstructionSet.opSTR; opSUB = InstructionSet.opSUB;
  84. opSWI = InstructionSet.opSWI; opSWP = InstructionSet.opSWP;
  85. opTEQ = InstructionSet.opTEQ; opTST = InstructionSet.opTST;
  86. opUMLAL = InstructionSet.opUMLAL; opUMULL = InstructionSet.opUMULL;
  87. (* builtin backend specific system instructions *)
  88. GetSP = 0; SetSP = 1;
  89. GetFP = 2; SetFP = 3;
  90. GetLNK = 4; SetLNK = 5;
  91. GetPC = 6; SetPC = 7;
  92. LDPSR = 8; STPSR = 9;
  93. LDCPR = 10; STCPR = 11;
  94. FLUSH = 12;
  95. NULL = 13; XOR = 14; MULD = 15; ADDC = 16;
  96. PACK = 17; UNPK = 18;
  97. UseFPU32Flag = "useFPU32";
  98. UseFPU64Flag = "useFPU64";
  99. TYPE
  100. Operand = InstructionSet.Operand;
  101. Ticket = CodeGenerators.Ticket;
  102. (* a citation of a symbol, i.e., an ARM instruction that requires a symbol's address *)
  103. Citation = OBJECT
  104. VAR
  105. pc: LONGINT; (* program counter of the ARM instruction *)
  106. bits: SIZE;
  107. shift: SIZE; (* fixup shift ! *)
  108. next: Citation;
  109. END Citation;
  110. (* a reference to a symbol and offset in IR units that is used by at least one instruction *)
  111. Reference = OBJECT
  112. VAR
  113. firstCitation, lastCitation: Citation; (* linked list of citations *)
  114. next: Reference;
  115. size: SIZE; (* storage size of this reference *)
  116. PROCEDURE & Init(size: SIZE);
  117. BEGIN
  118. firstCitation := NIL; lastCitation := NIL; next := NIL; SELF.size := size;
  119. END Init;
  120. PROCEDURE Emit(out: BinaryCode.Section);
  121. BEGIN
  122. HALT(100);
  123. END Emit;
  124. PROCEDURE AddCitation(pc: LONGINT; bits: SIZE; shift: SIZE);
  125. VAR
  126. citation: Citation;
  127. BEGIN
  128. NEW(citation); citation.pc := pc; citation.next := NIL; citation.bits := bits; citation.shift := shift;
  129. IF firstCitation = NIL THEN firstCitation := citation ELSE lastCitation.next := citation END;
  130. lastCitation := citation
  131. END AddCitation;
  132. END Reference;
  133. ImmediateReference = OBJECT (Reference)
  134. VAR value: LONGINT;
  135. PROCEDURE & InitImm(v: LONGINT);
  136. BEGIN
  137. Init(4);
  138. SELF.value := v;
  139. END InitImm;
  140. PROCEDURE Emit(out: BinaryCode.Section);
  141. BEGIN
  142. IF out.comments # NIL THEN
  143. out.comments.String("longint/real");
  144. out.comments.Ln; out.comments.Update
  145. END;
  146. out.PutBits(value,32);
  147. END Emit;
  148. END ImmediateReference;
  149. ImmediateHReference = OBJECT (Reference)
  150. VAR value: HUGEINT;
  151. PROCEDURE & InitImm(v: HUGEINT);
  152. BEGIN
  153. Init(8);
  154. SELF.value := v;
  155. END InitImm;
  156. PROCEDURE Emit(out: BinaryCode.Section);
  157. BEGIN
  158. IF out.comments # NIL THEN
  159. out.comments.String("hugeint/longreal");
  160. out.comments.Ln; out.comments.Update
  161. END;
  162. (* assumption: big endian *)
  163. out.PutBits(SHORT(value),32);
  164. out.PutBits(SHORT(ASH(value,-32)),32);
  165. END Emit;
  166. END ImmediateHReference;
  167. (* a reference to a symbol and offset in IR units that is used by at least one instruction *)
  168. SymbolReference = OBJECT (Reference)
  169. VAR
  170. identifier: ObjectFile.Identifier;
  171. symbolOffset: LONGINT; (* offset to the symbol in IR units *)
  172. PROCEDURE & InitSym(s: Sections.SectionName; fp: LONGINT; offs: LONGINT);
  173. BEGIN
  174. Init(4);
  175. identifier.name := s;
  176. identifier.fingerprint := fp;
  177. symbolOffset := offs;
  178. END InitSym;
  179. PROCEDURE Emit(out: BinaryCode.Section);
  180. VAR
  181. fixup: BinaryCode.Fixup;
  182. BEGIN
  183. IF out.comments # NIL THEN
  184. out.comments.String("fixup location for ");
  185. Basic.WriteSegmentedName(out.comments, identifier.name);
  186. out.comments.String(":"); out.comments.Int(symbolOffset, 0);
  187. out.comments.String(" :"); out.comments.Ln; out.comments.Update
  188. END;
  189. fixup := BinaryCode.NewFixup(BinaryCode.Absolute, out.pc, identifier, symbolOffset, 0, 0, rFixupPattern);
  190. out.fixupList.AddFixup(fixup);
  191. out.PutBits(0, 32);
  192. END Emit;
  193. END SymbolReference;
  194. ListOfReferences = OBJECT
  195. VAR
  196. firstReference, lastReference: Reference; (* linked list of all symbol references *)
  197. size: SIZE; (* length of the required fixup block *)
  198. due: SIZE; (* the PC at which the reference block has to be written (the latest) *)
  199. PROCEDURE & Init;
  200. BEGIN
  201. firstReference := NIL; lastReference := NIL;
  202. size := 0;
  203. due := MAX(SIZE);
  204. END Init;
  205. PROCEDURE UpdateDue(pc: SIZE; bits: SIZE; shift: SIZE);
  206. VAR max: SIZE;
  207. BEGIN
  208. (* bits determine the address size in words *)
  209. max := ASH(1, bits+shift) (* maximal fixup range *) + pc (* current pc *) - size (* fixup block size as of now *) - 8 (* offset *) - 64 (* 16 instructions safety *);
  210. IF max < due THEN
  211. due := max;
  212. END;
  213. END UpdateDue;
  214. PROCEDURE AddCitation(reference: Reference; pc: SIZE; bits: SIZE; shift: SIZE);
  215. BEGIN
  216. reference.AddCitation(pc, bits, shift);
  217. UpdateDue(pc, bits, shift);
  218. END AddCitation;
  219. PROCEDURE AddReference(reference: Reference): Reference;
  220. BEGIN
  221. IF firstReference = NIL THEN firstReference := reference ELSE lastReference.next := reference END;
  222. lastReference := reference;
  223. INC(size, reference.size);
  224. RETURN reference;
  225. END AddReference;
  226. PROCEDURE AddSymbol(symbol: Sections.SectionName; fingerprint: LONGINT; symbolOffset: LONGINT; pc: LONGINT; bits: LONGINT);
  227. VAR
  228. reference, foundReference: Reference; symbolReference: SymbolReference;
  229. BEGIN
  230. (* go through the list of symbol/offset-combinations and check if there already is an entry for the symbol and offset in question *)
  231. reference := firstReference;
  232. WHILE reference # NIL DO
  233. IF reference IS SymbolReference THEN
  234. WITH reference: SymbolReference DO
  235. IF (reference.identifier.name = symbol) & (reference.symbolOffset = symbolOffset) THEN
  236. foundReference := reference (* an entry already exists *)
  237. END;
  238. END;
  239. END;
  240. reference := reference.next
  241. END;
  242. IF foundReference # NIL THEN
  243. reference := foundReference
  244. ELSE
  245. (* no entry was found for the symbol/offset combination: create a new one *)
  246. NEW(symbolReference, symbol, fingerprint, symbolOffset);
  247. reference := AddReference(symbolReference);
  248. END;
  249. (* add a citation to the reference *)
  250. AddCitation(reference, pc, bits, 0);
  251. END AddSymbol;
  252. PROCEDURE AddImmediate(value: LONGINT; pc: SIZE; bits: SIZE);
  253. VAR
  254. reference, foundReference: Reference; immediateReference: ImmediateReference;
  255. BEGIN
  256. (* go through the list of symbol/offset-combinations and check if there already is an entry for the symbol and offset in question *)
  257. reference := firstReference;
  258. WHILE reference # NIL DO
  259. IF reference IS ImmediateReference THEN
  260. WITH reference: ImmediateReference DO
  261. IF (reference.value = value) THEN
  262. foundReference := reference (* an entry already exists *)
  263. END;
  264. END;
  265. END;
  266. reference := reference.next
  267. END;
  268. IF foundReference # NIL THEN
  269. reference := foundReference
  270. ELSE
  271. (* no entry was found for the symbol/offset combination: create a new one *)
  272. NEW(immediateReference, value);
  273. reference := AddReference(immediateReference);
  274. END;
  275. (* add a citation to the reference *)
  276. AddCitation(reference, pc, bits, 0);
  277. END AddImmediate;
  278. PROCEDURE AddHImmediate(value: HUGEINT; pc: LONGINT; bits: SIZE);
  279. VAR
  280. reference, foundReference: Reference; immediateHReference: ImmediateHReference;
  281. BEGIN
  282. (* go through the list of symbol/offset-combinations and check if there already is an entry for the symbol and offset in question *)
  283. reference := firstReference;
  284. WHILE reference # NIL DO
  285. IF reference IS ImmediateHReference THEN
  286. WITH reference: ImmediateHReference DO
  287. IF (reference.value = value) THEN
  288. foundReference := reference (* an entry already exists *)
  289. END;
  290. END;
  291. END;
  292. reference := reference.next
  293. END;
  294. IF foundReference # NIL THEN
  295. reference := foundReference
  296. ELSE
  297. (* no entry was found for the symbol/offset combination: create a new one *)
  298. NEW(immediateHReference, value);
  299. reference := AddReference(immediateHReference);
  300. END;
  301. (* add a citation to the reference *)
  302. AddCitation(reference, pc, bits, 2);
  303. END AddHImmediate;
  304. END ListOfReferences;
  305. PhysicalRegisters* = OBJECT(CodeGenerators.PhysicalRegisters)
  306. VAR
  307. toVirtual: ARRAY InstructionSet.NumberRegisters OF Ticket; (* registers real register -> none / reserved / split / blocked / virtual register (>0) *)
  308. reserved: ARRAY InstructionSet.NumberRegisters OF BOOLEAN;
  309. unusable: Ticket;
  310. blocked: Ticket;
  311. hint: LONGINT;
  312. useFPU32:BOOLEAN;
  313. useFPU64:BOOLEAN;
  314. PROCEDURE & InitPhysicalRegisters(supportFramePointer, useFPU32, useFPU64, cooperative: BOOLEAN);
  315. VAR
  316. i: LONGINT;
  317. unusable: Ticket;
  318. BEGIN
  319. SELF.useFPU32 := useFPU32;
  320. SELF.useFPU64 := useFPU64;
  321. FOR i := 0 TO LEN(toVirtual) - 1 DO
  322. toVirtual[i] := NIL;
  323. reserved[i] := FALSE
  324. END;
  325. NEW(unusable);
  326. NEW(blocked);
  327. (* reserve special purpose registers *)
  328. toVirtual[InstructionSet.RES] := unusable; (* low part result register *)
  329. toVirtual[InstructionSet.RESHI] := unusable; (* high part result register *)
  330. toVirtual[InstructionSet.RESFS] := unusable; (* single precision floatin point result register *)
  331. toVirtual[InstructionSet.RESFD] := unusable; (* single precision floatin point result register *)
  332. toVirtual[InstructionSet.SP] := unusable; (* stack pointer *)
  333. toVirtual[InstructionSet.FP] := unusable; (* frame pointer *)
  334. toVirtual[InstructionSet.PC] := unusable; (* program counter *)
  335. toVirtual[InstructionSet.LR] := unusable; (* link register *)
  336. toVirtual[InstructionSet.CPSR] := unusable; (* current program state register *)
  337. toVirtual[InstructionSet.SPSR] := unusable; (* saved program state register *)
  338. IF cooperative THEN
  339. toVirtual[InstructionSet.R11] := unusable; (* current activity register *)
  340. END;
  341. (* disable coprocessor registers *)
  342. FOR i := InstructionSet.CR0 TO InstructionSet.CR15 DO toVirtual[i] := unusable END;
  343. IF ~useFPU32 THEN
  344. (* disable single precision VFP registers *)
  345. FOR i := InstructionSet.SR0 TO InstructionSet.SR31 DO toVirtual[i] := unusable END
  346. END;
  347. IF ~useFPU64 THEN
  348. (* disable double precision VFP registers *)
  349. FOR i := InstructionSet.DR0 TO InstructionSet.DR31 DO toVirtual[i] := unusable END;
  350. END;
  351. END InitPhysicalRegisters;
  352. (** the number of physical registers **)
  353. PROCEDURE NumberRegisters(): LONGINT;
  354. BEGIN RETURN InstructionSet.NumberRegisters
  355. END NumberRegisters;
  356. (** allocate, i.e., map, a physical register to a ticket **)
  357. PROCEDURE Allocate(physicalRegisterNumber: LONGINT; ticket: Ticket);
  358. VAR index: LONGINT;
  359. BEGIN
  360. ASSERT(~ticket.spilled);
  361. Assert(toVirtual[physicalRegisterNumber] = NIL,"register already allocated");
  362. toVirtual[physicalRegisterNumber] := ticket;
  363. (* FP register overlap: *)
  364. IF (InstructionSet.SR0 <= physicalRegisterNumber) & (physicalRegisterNumber <= InstructionSet.SR31) THEN
  365. index := physicalRegisterNumber - InstructionSet.SR0;
  366. toVirtual[InstructionSet.DR0 + index DIV 2] := blocked;
  367. ELSIF (InstructionSet.DR0 <= physicalRegisterNumber) & (physicalRegisterNumber <= InstructionSet.DR31) THEN
  368. index := physicalRegisterNumber - InstructionSet.DR0;
  369. IF index*2 < 32 THEN
  370. toVirtual[InstructionSet.SR0 + index *2] := blocked;
  371. toVirtual[InstructionSet.SR0 + index *2 + 1] := blocked;
  372. END;
  373. END;
  374. END Allocate;
  375. (** set whether a certain physical register is reserved or not **)
  376. PROCEDURE SetReserved(physicalRegisterNumber: LONGINT; isReserved: BOOLEAN);
  377. BEGIN reserved[physicalRegisterNumber] := isReserved
  378. END SetReserved;
  379. (** whether a certain physical register is reserved **)
  380. PROCEDURE Reserved(physicalRegisterNumber: LONGINT): BOOLEAN;
  381. BEGIN RETURN (physicalRegisterNumber > 0) & reserved[physicalRegisterNumber]
  382. END Reserved;
  383. (** free a certain physical register **)
  384. PROCEDURE Free(physicalRegisterNumber: LONGINT);
  385. VAR index: LONGINT;
  386. BEGIN
  387. Assert((toVirtual[physicalRegisterNumber] # NIL), "register not reserved");
  388. toVirtual[physicalRegisterNumber] := NIL;
  389. (* FP register overlap: *)
  390. IF (InstructionSet.SR0 <= physicalRegisterNumber) & (physicalRegisterNumber <= InstructionSet.SR31) THEN
  391. index := physicalRegisterNumber - InstructionSet.SR0;
  392. IF ODD(index) & (toVirtual[InstructionSet.SR0+index-1] = NIL) OR
  393. ~ODD(index) & (toVirtual[InstructionSet.SR0+index+1] = NIL) THEN
  394. ASSERT(toVirtual[InstructionSet.DR0 + index DIV 2] = blocked);
  395. toVirtual[InstructionSet.DR0 + index DIV 2] := NIL;
  396. END;
  397. ELSIF (InstructionSet.DR0 <= physicalRegisterNumber) & (physicalRegisterNumber <= InstructionSet.DR31) THEN
  398. index := physicalRegisterNumber - InstructionSet.DR0;
  399. IF index*2 < 32 THEN
  400. ASSERT(toVirtual[InstructionSet.SR0 + index *2] = blocked);
  401. ASSERT(toVirtual[InstructionSet.SR0 + index *2+1] = blocked);
  402. toVirtual[InstructionSet.SR0 + index *2] := NIL;
  403. toVirtual[InstructionSet.SR0 + index *2 + 1] := NIL;
  404. END;
  405. END;
  406. END Free;
  407. (** get the number of the next free physical register for a certain data type
  408. - if a register hint has been set, it is respected if possible
  409. **)
  410. PROCEDURE NextFree(CONST type: IntermediateCode.Type): LONGINT;
  411. VAR
  412. result, i: LONGINT;
  413. BEGIN
  414. result := None;
  415. IF (type.form IN IntermediateCode.Integer) THEN
  416. ASSERT(type.sizeInBits <= 32); (* integers of larger size have already been split *)
  417. (* allocate a regular general purpose ARM register *)
  418. FOR i := InstructionSet.R0 TO InstructionSet.R15 DO
  419. IF (toVirtual[i] = NIL) & ((result = None) OR (i = hint)) THEN result := i END
  420. END
  421. ELSIF type.form = IntermediateCode.Float THEN
  422. IF (type.sizeInBits = 32) & useFPU32 THEN
  423. (* allocate a single precision VFP register *)
  424. FOR i := InstructionSet.SR0 TO InstructionSet.SR31 DO
  425. IF (toVirtual[i] = NIL) & ((result = None) OR (i = hint)) THEN result := i; END;
  426. END;
  427. ELSIF (type.sizeInBits = 64) & (useFPU64) THEN
  428. FOR i := InstructionSet.DR0 TO InstructionSet.DR31 DO
  429. IF (toVirtual[i] = NIL) & ((result = None) OR (i = hint)) THEN result := i END;
  430. END;
  431. ELSE
  432. (* allocate a regular general purpose ARM register *)
  433. FOR i := InstructionSet.R0 TO InstructionSet.R15 DO
  434. IF (toVirtual[i] = NIL) & ((result = None) OR (i = hint)) THEN result := i END
  435. END
  436. END
  437. ELSE
  438. HALT(100)
  439. END;
  440. IF result # None THEN ASSERT(toVirtual[result] = NIL) END;
  441. RETURN result
  442. END NextFree;
  443. (** give the register allocator a hint on what physical register to use next **)
  444. PROCEDURE AllocationHint(physicalRegisterNumber: LONGINT);
  445. BEGIN hint := physicalRegisterNumber
  446. END AllocationHint;
  447. (** get the ticket that is currently mapped to a certain physical register **)
  448. PROCEDURE Mapped(physicalRegisterNumber: LONGINT): Ticket;
  449. BEGIN RETURN toVirtual[physicalRegisterNumber]
  450. END Mapped;
  451. (** dump the current register mapping to a stream **)
  452. PROCEDURE Dump(w: Streams.Writer);
  453. VAR i: LONGINT; virtual: Ticket;
  454. BEGIN
  455. w.String("---- registers ----"); w.Ln;
  456. FOR i := 0 TO LEN(toVirtual)-1 DO
  457. virtual := toVirtual[i];
  458. IF (virtual # unusable) & (virtual # blocked) THEN
  459. w.String("reg "); w.Int(i,1); w.String(": ");
  460. IF virtual = NIL THEN w.String("free")
  461. ELSE w.String(" r"); w.Int(virtual.register,1);
  462. END;
  463. IF reserved[i] THEN w.String("reserved") END;
  464. w.Ln
  465. END
  466. END
  467. END Dump;
  468. END PhysicalRegisters;
  469. CodeGeneratorARM = OBJECT(CodeGenerators.GeneratorWithTickets)
  470. VAR
  471. runtimeModuleName: SyntaxTree.IdentifierString;
  472. backend: BackendARM;
  473. opSP, opFP, opPC, opLR, opRES, opRESHI, opRESFS, opRESFD, fpscr: InstructionSet.Operand;
  474. listOfReferences: ListOfReferences;
  475. spillStackStart, pushChainLength: LONGINT;
  476. stackSize: LONGINT; (* the size of the current stack frame *)
  477. stackSizeKnown: BOOLEAN; (* whether the size of the current stack frame is known at compile time *)
  478. inStackAllocation: BOOLEAN;
  479. PROCEDURE & InitGeneratorARM(CONST runtimeModuleName: SyntaxTree.IdentifierString; diagnostics: Diagnostics.Diagnostics; backend: BackendARM);
  480. VAR
  481. physicalRegisters: PhysicalRegisters;
  482. BEGIN
  483. SELF.runtimeModuleName := runtimeModuleName;
  484. SELF.backend := backend;
  485. IF Trace THEN IF backend.useFPU32 THEN D.String("use FPU"); D.Ln ELSE D.String("don't use FPU"); D.Ln END END;
  486. NEW(physicalRegisters, TRUE, backend.useFPU32, backend.useFPU64, backend.cooperative);
  487. InitTicketGenerator(diagnostics, backend.optimize, 2, physicalRegisters);
  488. error := FALSE;
  489. inStackAllocation := FALSE;
  490. pushChainLength := 0;
  491. opSP := InstructionSet.NewRegister(InstructionSet.SP, None, None, 0);
  492. opFP := InstructionSet.NewRegister(InstructionSet.FP, None, None, 0);
  493. opPC := InstructionSet.NewRegister(InstructionSet.PC, None, None, 0);
  494. opLR := InstructionSet.NewRegister(InstructionSet.LR, None, None, 0);
  495. opRES := InstructionSet.NewRegister(InstructionSet.RES, None, None, 0);
  496. opRESHI := InstructionSet.NewRegister(InstructionSet.RESHI, None, None, 0);
  497. opRESFS := InstructionSet.NewRegister(InstructionSet.RESFS, None, None, 0);
  498. opRESFD := InstructionSet.NewRegister(InstructionSet.RESFD, None, None, 0);
  499. fpscr := InstructionSet.NewRegister(InstructionSet.FPSCR, None, None, 0);
  500. dump := NIL;
  501. NEW(listOfReferences);
  502. END InitGeneratorARM;
  503. (*------------------- overwritten methods ----------------------*)
  504. (* TODO: revise this *)
  505. PROCEDURE Section(in: IntermediateCode.Section; out: BinaryCode.Section);
  506. VAR
  507. oldSpillStackSize: LONGINT;
  508. PROCEDURE CheckEmptySpillStack(): BOOLEAN;
  509. BEGIN
  510. IF spillStack.Size() # 0 THEN
  511. Error(inPC,"implementation error, spill stack not cleared");
  512. IF dump # NIL THEN
  513. spillStack.Dump(dump);
  514. tickets.Dump(dump)
  515. END;
  516. RETURN FALSE
  517. ELSE
  518. RETURN TRUE
  519. END
  520. END CheckEmptySpillStack;
  521. BEGIN
  522. stackSizeKnown := TRUE;
  523. stackSize := 0; (* TODO: ok? *)
  524. tickets.Init; spillStack.Init; listOfReferences.Init;
  525. Section^(in, out); (* pass 1 *)
  526. EmitFinalFixupBlock; (* force the emission of fixups for all references *)
  527. IF stackSizeKnown = FALSE THEN
  528. tickets.Init; spillStack.Init; listOfReferences.Init;
  529. out.Reset;
  530. Section^(in, out); (* pass 2 *)
  531. EmitFinalFixupBlock (* force the emission of fixups for all references *)
  532. END;
  533. IF CheckEmptySpillStack() & (spillStack.MaxSize() > 0) THEN
  534. listOfReferences.Init;
  535. oldSpillStackSize := spillStack.MaxSize();
  536. out.Reset;
  537. Section^(in, out); (* pass 3 *)
  538. EmitFinalFixupBlock; (* force the emission of fixups for all references *)
  539. ASSERT(spillStack.MaxSize() = oldSpillStackSize);
  540. END;
  541. IF CheckEmptySpillStack() THEN END
  542. END Section;
  543. (* TODO: complete this *)
  544. (** whether the code generator can generate code for a certain intermediate code intstruction
  545. if not, the location of a runtime is returned **)
  546. PROCEDURE Supported(CONST irInstruction: IntermediateCode.Instruction; VAR moduleName, procedureName: ARRAY OF CHAR): BOOLEAN;
  547. VAR
  548. result: BOOLEAN;
  549. BEGIN
  550. CASE irInstruction.opcode OF
  551. | IntermediateCode.add, IntermediateCode.sub, IntermediateCode.mul, IntermediateCode.abs, IntermediateCode.neg:
  552. IF (irInstruction.opcode = IntermediateCode.mul) & IsInteger(irInstruction.op1) & IsInteger(irInstruction.op2) & (IsComplex(irInstruction.op1) OR IsComplex(irInstruction.op2)) THEN
  553. result := FALSE;
  554. ELSE
  555. result := ~IsFloat(irInstruction.op1) OR backend.useFPU32 & IsSinglePrecisionFloat(irInstruction.op1) OR backend.useFPU64 & IsDoublePrecisionFloat(irInstruction.op1);
  556. END;
  557. | IntermediateCode.div:
  558. result := backend.useFPU32 & IsSinglePrecisionFloat(irInstruction.op1)
  559. OR backend.useFPU64 & IsDoublePrecisionFloat(irInstruction.op1)
  560. OR backend.useFPU64 & IsNonComplexInteger(irInstruction.op1);
  561. (*
  562. result := result OR IntermediateCode.IsConstantInteger(irInstruction.op3,value) & PowerOf2(value,exp)
  563. *)
  564. | IntermediateCode.conv:
  565. IF IsInteger64(irInstruction.op1) & IsFloat(irInstruction.op2) THEN (* ENTIERH: REAL/LONGREAL --> HUGEINT*)
  566. result := FALSE
  567. ELSIF IsInteger64(irInstruction.op2) & IsFloat(irInstruction.op1) THEN (* HUGEINT --> REAL / HUGEINT --> LONGREAL *)
  568. result := FALSE;
  569. ELSE
  570. result := ~IsFloat(irInstruction.op1) & ~IsFloat(irInstruction.op2)
  571. OR backend.useFPU32 & ~IsDoublePrecisionFloat(irInstruction.op1) & ~IsDoublePrecisionFloat(irInstruction.op2)
  572. OR backend.useFPU64;
  573. END;
  574. | IntermediateCode.mod:
  575. result := FALSE;
  576. (*
  577. result := IntermediateCode.IsConstantInteger(irInstruction.op3,value) & PowerOf2(value,exp)
  578. *)
  579. | IntermediateCode.rol, IntermediateCode.ror:
  580. result := ~IsComplex(irInstruction.op1)
  581. ELSE
  582. result := TRUE
  583. END;
  584. IF ~result THEN
  585. COPY(runtimeModuleName, moduleName);
  586. GetRuntimeProcedureName(irInstruction, procedureName);
  587. END;
  588. RETURN result
  589. END Supported;
  590. (* determines the name of a runtime procedure to handle a certain IR instruction *)
  591. PROCEDURE GetRuntimeProcedureName(CONST irInstruction: IntermediateCode.Instruction; VAR resultingName: ARRAY OF CHAR);
  592. PROCEDURE AppendType(VAR string: ARRAY OF CHAR; type: IntermediateCode.Type);
  593. VAR
  594. sizeString: ARRAY 3 OF CHAR;
  595. BEGIN
  596. CASE type.form OF
  597. | IntermediateCode.SignedInteger: Strings.AppendChar(string, 'S')
  598. | IntermediateCode.UnsignedInteger: Strings.AppendChar(string, 'U')
  599. | IntermediateCode.Float:Strings.AppendChar(string, 'F')
  600. ELSE HALT(200)
  601. END;
  602. Strings.IntToStr(type.sizeInBits, sizeString); Strings.Append(string, sizeString)
  603. END AppendType;
  604. BEGIN
  605. COPY(IntermediateCode.instructionFormat[irInstruction.opcode].name, resultingName);
  606. Strings.UpperCaseChar(resultingName[0]);
  607. AppendType(resultingName, irInstruction.op1.type);
  608. IF irInstruction.op1.mode # IntermediateCode.Undefined THEN
  609. IF (irInstruction.op1.type.form # irInstruction.op2.type.form) OR (irInstruction.op1.type.sizeInBits # irInstruction.op2.type.sizeInBits) THEN
  610. AppendType(resultingName, irInstruction.op2.type);
  611. (* special case: result returned in FPU register *)
  612. IF IsSinglePrecisionFloat(irInstruction.op1) & backend.useFPU32 THEN
  613. Strings.Append(resultingName, 'F')
  614. ELSIF IsDoublePrecisionFloat(irInstruction.op1) & backend.useFPU64 THEN
  615. Strings.Append(resultingName, 'F')
  616. END;
  617. END
  618. END;
  619. IF Trace THEN D.Ln; D.String(" runtime procedure name: "); D.String(resultingName); D.Ln; D.Update END
  620. END GetRuntimeProcedureName;
  621. (* check whether the instruction modifies the stack pointer (outside of a stack allocation )*)
  622. PROCEDURE CheckStackPointer(CONST destination: Operand);
  623. BEGIN
  624. IF stackSizeKnown & ~inStackAllocation THEN
  625. IF (destination.mode = InstructionSet.modeRegister) & (destination.register = InstructionSet.SP) THEN
  626. IF dump # NIL THEN dump.String("stackSize unkown"); dump.Ln END;
  627. stackSizeKnown := FALSE
  628. END
  629. END
  630. END CheckStackPointer;
  631. (** emit an ARM instruction with an arbitrary amount of operands **)
  632. PROCEDURE Emit(opCode, condition: LONGINT; flags: SET; CONST operands: ARRAY InstructionSet.MaxOperands OF Operand);
  633. VAR
  634. BEGIN
  635. (* check whether the instruction modifies the stack pointer *)
  636. CheckStackPointer(operands[0]);
  637. (*
  638. (* dump the instruction *)
  639. IF Trace THEN
  640. D.String("opCode="); D.Int(opCode, 0); D.Ln;
  641. D.String("condition="); D.Int(condition, 0); D.Ln;
  642. D.String("flags="); D.Set(flags); D.Ln;
  643. FOR i := 0 TO InstructionSet.MaxOperands - 1 DO
  644. D.String("operand #"); D.Int(i, 0); D.String(": ");
  645. InstructionSet.DumpOperand(D.Log, operands[i]);
  646. D.Ln
  647. END;
  648. D.Ln;
  649. D.Ln
  650. END;
  651. *)
  652. (* emit the instruction *)
  653. InstructionSet.Emit(opCode, condition, flags, operands, out);
  654. END Emit;
  655. (** emit an ARM instruction with no operand **)
  656. PROCEDURE Emit0(opCode: LONGINT);
  657. VAR
  658. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  659. BEGIN
  660. ASSERT(InstructionSet.MaxOperands = 6);
  661. operands[0] := emptyOperand;
  662. operands[1] := emptyOperand;
  663. operands[2] := emptyOperand;
  664. operands[3] := emptyOperand;
  665. operands[4] := emptyOperand;
  666. operands[5] := emptyOperand;
  667. Emit(opCode, InstructionSet.unconditional, {}, operands)
  668. END Emit0;
  669. (** emit an ARM instruction with 1 operand **)
  670. PROCEDURE Emit1(opCode: LONGINT; op: Operand);
  671. VAR
  672. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  673. BEGIN
  674. ASSERT(InstructionSet.MaxOperands = 6);
  675. operands[0] := op;
  676. operands[1] := emptyOperand;
  677. operands[2] := emptyOperand;
  678. operands[3] := emptyOperand;
  679. operands[4] := emptyOperand;
  680. operands[5] := emptyOperand;
  681. Emit(opCode, InstructionSet.unconditional, {}, operands)
  682. END Emit1;
  683. (** emit an ARM instruction with 2 operands **)
  684. PROCEDURE Emit2(opCode: LONGINT; op1, op2: Operand);
  685. VAR
  686. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  687. BEGIN
  688. ASSERT(InstructionSet.MaxOperands = 6);
  689. operands[0] := op1;
  690. operands[1] := op2;
  691. operands[2] := emptyOperand;
  692. operands[3] := emptyOperand;
  693. operands[4] := emptyOperand;
  694. operands[5] := emptyOperand;
  695. Emit(opCode, InstructionSet.unconditional, {}, operands)
  696. END Emit2;
  697. (** emit an ARM instruction with 3 operands **)
  698. PROCEDURE Emit3(opCode: LONGINT; op1, op2, op3: Operand);
  699. VAR
  700. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  701. BEGIN
  702. ASSERT(InstructionSet.MaxOperands = 6);
  703. operands[0] := op1;
  704. operands[1] := op2;
  705. operands[2] := op3;
  706. operands[3] := emptyOperand;
  707. operands[4] := emptyOperand;
  708. operands[5] := emptyOperand;
  709. Emit(opCode, InstructionSet.unconditional, {}, operands)
  710. END Emit3;
  711. (** emit an ARM instruction with 4 operands **)
  712. PROCEDURE Emit4(opCode: LONGINT; op1, op2, op3, op4: Operand);
  713. VAR
  714. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  715. BEGIN
  716. ASSERT(InstructionSet.MaxOperands = 6);
  717. operands[0] := op1;
  718. operands[1] := op2;
  719. operands[2] := op3;
  720. operands[3] := op4;
  721. operands[4] := emptyOperand;
  722. operands[5] := emptyOperand;
  723. Emit(opCode, InstructionSet.unconditional, {}, operands)
  724. END Emit4;
  725. (** emit an ARM instruction with 6 operands **)
  726. PROCEDURE Emit6(opCode: LONGINT; op1, op2, op3, op4, op5, op6: Operand);
  727. VAR
  728. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  729. BEGIN
  730. ASSERT(InstructionSet.MaxOperands = 6);
  731. operands[0] := op1;
  732. operands[1] := op2;
  733. operands[2] := op3;
  734. operands[3] := op4;
  735. operands[4] := op5;
  736. operands[5] := op6;
  737. Emit(opCode, InstructionSet.unconditional, {}, operands)
  738. END Emit6;
  739. (** emit an ARM instruction with 2 operands and certain flags **)
  740. PROCEDURE Emit2WithFlags(opCode: LONGINT; op1, op2: Operand; flags: SET);
  741. VAR
  742. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  743. BEGIN
  744. ASSERT(InstructionSet.MaxOperands = 6);
  745. operands[0] := op1;
  746. operands[1] := op2;
  747. operands[2] := emptyOperand;
  748. operands[3] := emptyOperand;
  749. operands[4] := emptyOperand;
  750. operands[5] := emptyOperand;
  751. Emit(opCode, InstructionSet.unconditional, flags, operands)
  752. END Emit2WithFlags;
  753. (** emit an ARM instruction with 3 operands and certain flags **)
  754. PROCEDURE Emit3WithFlags(opCode: LONGINT; op1, op2, op3: Operand; flags: SET);
  755. VAR
  756. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  757. BEGIN
  758. ASSERT(InstructionSet.MaxOperands = 6);
  759. operands[0] := op1;
  760. operands[1] := op2;
  761. operands[2] := op3;
  762. operands[3] := emptyOperand;
  763. operands[4] := emptyOperand;
  764. operands[5] := emptyOperand;
  765. Emit(opCode, InstructionSet.unconditional, flags, operands)
  766. END Emit3WithFlags;
  767. (** emit an ARM instruction with 1 operand and a condition **)
  768. PROCEDURE Emit1WithCondition(opCode: LONGINT; op1: Operand; condition: LONGINT);
  769. VAR
  770. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  771. BEGIN
  772. ASSERT(InstructionSet.MaxOperands = 6);
  773. operands[0] := op1;
  774. operands[1] := emptyOperand;
  775. operands[2] := emptyOperand;
  776. operands[3] := emptyOperand;
  777. operands[4] := emptyOperand;
  778. operands[5] := emptyOperand;
  779. Emit(opCode, condition, {}, operands)
  780. END Emit1WithCondition;
  781. (** emit an ARM instruction with 2 operands and a condition **)
  782. PROCEDURE Emit2WithCondition(opCode: LONGINT; op1, op2: Operand; condition: LONGINT);
  783. VAR
  784. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  785. BEGIN
  786. ASSERT(InstructionSet.MaxOperands = 6);
  787. operands[0] := op1;
  788. operands[1] := op2;
  789. operands[2] := emptyOperand;
  790. operands[3] := emptyOperand;
  791. operands[4] := emptyOperand;
  792. operands[5] := emptyOperand;
  793. Emit(opCode, condition, {}, operands)
  794. END Emit2WithCondition;
  795. (** emit an ARM instruction with 3 operands and a condition **)
  796. PROCEDURE Emit3WithCondition(opCode: LONGINT; op1, op2, op3: Operand; condition: LONGINT);
  797. VAR
  798. operands: ARRAY InstructionSet.MaxOperands OF Operand;
  799. BEGIN
  800. ASSERT(InstructionSet.MaxOperands = 6);
  801. operands[0] := op1;
  802. operands[1] := op2;
  803. operands[2] := op3;
  804. operands[3] := emptyOperand;
  805. operands[4] := emptyOperand;
  806. operands[5] := emptyOperand;
  807. Emit(opCode, condition, {}, operands)
  808. END Emit3WithCondition;
  809. (**
  810. - generate an arbitrary 32 bit value with as few as possible instructions and move the result into a specified target register
  811. - return the number of instructions required
  812. - if 'doEmit' is TRUE, emit the instructions
  813. **)
  814. PROCEDURE ValueComposition(value: LONGINT; doEmit: BOOLEAN; CONST targetRegister: Operand): LONGINT;
  815. VAR
  816. result: LONGINT;
  817. BEGIN
  818. IF doEmit THEN ASSERT(targetRegister.mode = InstructionSet.modeRegister) END;
  819. IF Trace & doEmit THEN D.Ln; D.String("original value: "); DBin(value, -32); D.String(" ("); D.Int(value, 0); D.String(") "); D.Ln; END;
  820. IF ValueComposition2(value, FALSE, emptyOperand) <= ValueComposition2(-value, FALSE, emptyOperand) + 1 THEN
  821. (* more efficient to calculate the value directly *)
  822. result := ValueComposition2(value, doEmit, targetRegister)
  823. ELSE
  824. (* more efficient to calculate the negation of the value and then negate it *)
  825. result := ValueComposition2(-value, doEmit, targetRegister) + 1;
  826. IF doEmit THEN
  827. Emit3(opRSB, targetRegister, targetRegister, InstructionSet.NewImmediate(0))
  828. END
  829. END;
  830. ASSERT((result >= 1) & (result <= 4));
  831. RETURN result
  832. END ValueComposition;
  833. (* note: used by 'ValueComposition'. do not call directly *)
  834. PROCEDURE ValueComposition2(value: LONGINT; doEmit: BOOLEAN; CONST targetRegister: Operand): LONGINT;
  835. VAR
  836. immediateOperand: Operand;
  837. result, position, partialValue, i: LONGINT;
  838. valueAsSet: SET;
  839. isFirst: BOOLEAN;
  840. BEGIN
  841. IF doEmit THEN ASSERT(targetRegister.mode = InstructionSet.modeRegister) END;
  842. IF Trace & doEmit THEN D.String("value to use: "); DBin(value, -32); D.String(" ("); D.Int(value, 0); D.String(") "); D.Ln; END;
  843. IF (value >= 0) & (value <= 255) THEN
  844. (* directly encodable as ARM immediate *)
  845. result := 1;
  846. IF doEmit THEN
  847. Emit2(opMOV, targetRegister, InstructionSet.NewImmediate(value))
  848. END
  849. ELSE
  850. valueAsSet := SYSTEM.VAL(SET, value);
  851. result := 0;
  852. position := 0;
  853. isFirst := TRUE;
  854. WHILE position < 32 DO
  855. IF (position IN valueAsSet) OR (position + 1 IN valueAsSet) THEN
  856. (* determine partial value for the 8 bit block *)
  857. partialValue := 0;
  858. FOR i := 7 TO 0 BY -1 DO
  859. partialValue := partialValue * 2;
  860. IF ((position + i) < 32) & ((position + i) IN valueAsSet) THEN INC(partialValue) END
  861. END;
  862. IF Trace & doEmit THEN
  863. D.String(" block found @ "); D.Int(position, 0); D.Ln;
  864. D.String(" unshifted partialValue: "); DBin(partialValue, -32); D.String(" ("); D.Int(partialValue, 0); D.String(") "); D.Ln;
  865. D.String(" shifted partialValue: "); DBin(ASH(partialValue, position), -32); D.String(" ("); D.Int(ASH(partialValue, position), 0); D.String(") "); D.Ln;
  866. END;
  867. ASSERT(~ODD(position));
  868. INC(result);
  869. IF doEmit THEN
  870. immediateOperand := InstructionSet.NewImmediate(ASH(partialValue, position)); (* TODO: check shift direction *)
  871. IF isFirst THEN
  872. Emit2(opMOV, targetRegister, immediateOperand);
  873. isFirst := FALSE
  874. ELSE
  875. Emit3(opADD, targetRegister, targetRegister, immediateOperand)
  876. END
  877. END;
  878. INC(position, 8)
  879. ELSE
  880. INC(position, 2)
  881. END
  882. END
  883. END;
  884. ASSERT((result >= 1) & (result <= 4));
  885. RETURN result
  886. END ValueComposition2;
  887. (** get the physical register number that corresponds to a virtual register number and part **)
  888. PROCEDURE PhysicalRegisterNumber(virtualRegisterNumber: LONGINT; part: LONGINT): LONGINT;
  889. VAR
  890. ticket: Ticket;
  891. result: LONGINT;
  892. BEGIN
  893. IF virtualRegisterNumber = IntermediateCode.FP THEN
  894. result := InstructionSet.FP
  895. ELSIF virtualRegisterNumber = IntermediateCode.SP THEN
  896. result := InstructionSet.SP
  897. ELSIF virtualRegisterNumber = IntermediateCode.LR THEN
  898. result := InstructionSet.LR
  899. ELSIF virtualRegisterNumber = IntermediateCode.AP THEN
  900. result := InstructionSet.R11
  901. ELSE
  902. ticket := virtualRegisters.Mapped(virtualRegisterNumber, part);
  903. IF ticket = NIL THEN
  904. result := None
  905. ELSE
  906. result := ticket.register
  907. END
  908. END;
  909. RETURN result
  910. END PhysicalRegisterNumber;
  911. (** get an ARM memory operand that represents a spill location (from a ticket) **)
  912. PROCEDURE GetSpillOperand(ticket: Ticket): Operand;
  913. VAR
  914. offset: LONGINT;
  915. result: Operand;
  916. BEGIN
  917. ASSERT(ticket.spilled);
  918. offset := spillStackStart + ticket.offset + 1; (* TODO: check this *)
  919. ASSERT((0 <= offset) & (offset < InstructionSet.Bits12));
  920. result := InstructionSet.NewImmediateOffsetMemory(PhysicalRegisterNumber(IntermediateCode.FP, Low), offset, {InstructionSet.Decrement});
  921. ASSERT(result.mode = InstructionSet.modeMemory);
  922. RETURN result
  923. END GetSpillOperand;
  924. (** get an ARM operand that represents a certain ticket (might be spilled or not) **)
  925. PROCEDURE OperandFromTicket(ticket: Ticket): Operand;
  926. VAR
  927. result: Operand;
  928. BEGIN
  929. ASSERT(ticket # NIL);
  930. IF ticket.spilled THEN
  931. (* the ticket is spilled *)
  932. result := GetSpillOperand(ticket)
  933. ELSE
  934. result := InstructionSet.NewRegister(ticket.register, None, None, 0)
  935. END;
  936. RETURN result
  937. END OperandFromTicket;
  938. (** get a free temporary register that holds data of a certain type **)
  939. PROCEDURE GetFreeRegister(CONST type: IntermediateCode.Type): Operand;
  940. VAR
  941. result: Operand;
  942. BEGIN
  943. result := OperandFromTicket(TemporaryTicket(IntermediateCode.GeneralPurposeRegister, type));
  944. ASSERT(result.mode = InstructionSet.modeRegister);
  945. RETURN result
  946. END GetFreeRegister;
  947. (** get a new free ARM register
  948. - if a register hint is provided that can hold data of the required type, it is returned instead
  949. **)
  950. PROCEDURE GetFreeRegisterOrHint(CONST type: IntermediateCode.Type; CONST registerHint: Operand): Operand;
  951. VAR
  952. result: Operand;
  953. BEGIN
  954. IF (registerHint.mode = InstructionSet.modeRegister) & IsRegisterForType(registerHint.register, type) THEN
  955. result := registerHint
  956. ELSE
  957. result := GetFreeRegister(type)
  958. END;
  959. ASSERT(result.mode = InstructionSet.modeRegister);
  960. RETURN result
  961. END GetFreeRegisterOrHint;
  962. (** whether a register can hold data of a certain IR type **)
  963. PROCEDURE IsRegisterForType(registerNumber: LONGINT; CONST type: IntermediateCode.Type): BOOLEAN;
  964. VAR
  965. result: BOOLEAN; form:LONGINT;
  966. BEGIN
  967. result := FALSE;
  968. form := type.form;
  969. IF type.form IN IntermediateCode.Integer THEN
  970. IF type.sizeInBits <= 32 THEN
  971. result := (registerNumber >= InstructionSet.R0) & (registerNumber <= InstructionSet.R15)
  972. END
  973. ELSIF type.form = IntermediateCode.Float THEN
  974. IF type.sizeInBits = 32 THEN
  975. result := (registerNumber >= InstructionSet.SR0) & (registerNumber <= InstructionSet.SR31)
  976. ELSE
  977. result := (registerNumber >= InstructionSet.DR0) & (registerNumber <= InstructionSet.DR31)
  978. END
  979. ELSE
  980. HALT(100)
  981. END;
  982. RETURN result
  983. END IsRegisterForType;
  984. (** get an ARM register that that is set off by a certain amount **)
  985. PROCEDURE RegisterAfterAppliedOffset(register: Operand; offset: LONGINT; registerHint: Operand): Operand;
  986. VAR
  987. result, offsetOperand: Operand;
  988. BEGIN
  989. IF offset = 0 THEN
  990. result := register
  991. ELSE
  992. result := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  993. offsetOperand := OperandFromValue(ABS(offset), result); (* might be immediate operand or register (tempRegister is given as a register hint) *)
  994. IF offset > 0 THEN
  995. Emit3(opADD, result, register, offsetOperand)
  996. ELSE
  997. Emit3(opSUB, result, register, offsetOperand)
  998. END
  999. END;
  1000. RETURN result
  1001. END RegisterAfterAppliedOffset;
  1002. (** get an ARM register from an IR register
  1003. - use register hint if provided
  1004. **)
  1005. PROCEDURE RegisterFromIrRegister(CONST irRegisterOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  1006. VAR
  1007. result: Operand;
  1008. BEGIN
  1009. ASSERT(irRegisterOperand.mode = IntermediateCode.ModeRegister);
  1010. result := InstructionSet.NewRegister(PhysicalRegisterNumber(irRegisterOperand.register, part), None, None, 0);
  1011. result := RegisterAfterAppliedOffset(result, irRegisterOperand.offset, registerHint);
  1012. ASSERT(result.mode = InstructionSet.modeRegister);
  1013. RETURN result
  1014. END RegisterFromIrRegister;
  1015. PROCEDURE Load(targetRegister, memoryOperand: Operand; irType: IntermediateCode.Type);
  1016. BEGIN
  1017. IF (irType.form IN IntermediateCode.Integer) THEN
  1018. CASE irType.sizeInBits OF
  1019. | 8: Emit2WithFlags(opLDR, targetRegister, memoryOperand, {InstructionSet.flagB}) (* LDRB *)
  1020. | 16: Emit2WithFlags(opLDR, targetRegister, memoryOperand, {InstructionSet.flagH}) (* LDRH *)
  1021. | 32: (* TM*)
  1022. Emit2(opLDR, targetRegister, memoryOperand)
  1023. ELSE HALT(100)
  1024. END
  1025. ELSIF irType.form = IntermediateCode.Float THEN
  1026. IF irType.sizeInBits=32 THEN
  1027. IF backend.useFPU32 THEN
  1028. ASSERT(irType.sizeInBits = 32, 200);
  1029. Emit2(opFLDS, targetRegister, memoryOperand)
  1030. ELSE
  1031. Emit2(opLDR, targetRegister, memoryOperand)
  1032. END;
  1033. ELSE
  1034. IF backend.useFPU64 THEN
  1035. ASSERT(irType.sizeInBits = 64, 200);
  1036. Emit2(opFLDD, targetRegister, memoryOperand)
  1037. ELSE
  1038. Emit2(opLDR, targetRegister, memoryOperand)
  1039. END;
  1040. END;
  1041. ELSE
  1042. HALT(100)
  1043. END
  1044. END Load;
  1045. PROCEDURE Store(sourceRegister, memoryOperand: Operand; type: IntermediateCode.Type);
  1046. BEGIN
  1047. IF (type.form IN IntermediateCode.Integer) THEN
  1048. CASE type.sizeInBits OF
  1049. | 8: Emit2WithFlags(opSTR, sourceRegister, memoryOperand, {InstructionSet.flagB}) (* STRB *)
  1050. | 16: Emit2WithFlags(opSTR, sourceRegister, memoryOperand, {InstructionSet.flagH}) (* STRH *)
  1051. | 32: Emit2(opSTR, sourceRegister, memoryOperand)
  1052. ELSE HALT(100)
  1053. END
  1054. ELSIF type.form = IntermediateCode.Float THEN
  1055. IF (type.sizeInBits = 32) & backend.useFPU32 THEN
  1056. Emit2(opFSTS, sourceRegister, memoryOperand)
  1057. ELSIF (type.sizeInBits=64) & backend.useFPU64 THEN
  1058. Emit2(opFSTD, sourceRegister, memoryOperand)
  1059. ELSE
  1060. Emit2(opSTR, sourceRegister, memoryOperand)
  1061. END;
  1062. ELSE
  1063. HALT(100)
  1064. END
  1065. END Store;
  1066. (** get an ARM register that contains the address of a symbol/section
  1067. - use register hint if provided **)
  1068. PROCEDURE RegisterFromSymbol(symbol: Sections.SectionName; fingerprint: LONGINT; resolved: Sections.Section; symbolOffset: LONGINT; CONST registerHint: Operand): Operand;
  1069. VAR
  1070. address: LONGINT;
  1071. result: Operand;
  1072. irSection: IntermediateCode.Section;
  1073. BEGIN
  1074. IF resolved # NIL THEN
  1075. irSection := resolved(IntermediateCode.Section);
  1076. END;
  1077. IF (irSection # NIL) & (irSection.resolved # NIL) & (irSection.resolved.os.fixed) THEN
  1078. (* optimization: if the IR section is already resolved and positioned at a fixed location, no fixup is required *)
  1079. address := irSection.resolved.os.alignment + irSection.instructions[symbolOffset].pc;
  1080. result := RegisterFromValue(address, registerHint)
  1081. ELSE
  1082. result := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  1083. listOfReferences.AddSymbol(symbol, fingerprint, symbolOffset, out.pc, 12);
  1084. Emit2(opLDR, result, InstructionSet.NewImmediateOffsetMemory(opPC.register, 0, {InstructionSet.Increment})); (* LDR ..., [PC, #+???] *)
  1085. END;
  1086. ASSERT(result.mode = InstructionSet.modeRegister);
  1087. RETURN result
  1088. END RegisterFromSymbol;
  1089. (** get an ARM memory operand from an IR memory operand
  1090. - note that the constraints on memory operands depend on the type of data (e.g., the allowed offset range is more restricted for memory operands on floating point values)
  1091. **)
  1092. PROCEDURE MemoryOperandFromIrMemoryOperand(VAR irMemoryOperand: IntermediateCode.Operand; part: LONGINT; CONST registerHint: Operand): Operand;
  1093. VAR
  1094. baseAddressRegisterNumber, offset: LONGINT;
  1095. indexingMode: SET;
  1096. result, baseAddressRegister, offsetRegister, tempRegister: Operand;
  1097. BEGIN
  1098. ASSERT(irMemoryOperand.mode = IntermediateCode.ModeMemory);
  1099. (* determine base address register *)
  1100. IF irMemoryOperand.register # IntermediateCode.None THEN
  1101. (* case 1: [r1] or [r1 + 7] *)
  1102. ASSERT(irMemoryOperand.symbol.name = "");
  1103. baseAddressRegisterNumber := PhysicalRegisterNumber(irMemoryOperand.register, Low); (* addresses always are in the lower part *)
  1104. baseAddressRegister := InstructionSet.NewRegister(baseAddressRegisterNumber, InstructionSet.None, InstructionSet.None, InstructionSet.None);
  1105. ELSIF irMemoryOperand.symbol.name # "" THEN
  1106. (* case 2: [symbol], [symbol:3], [symbol + 7] or [symbol:3 + 7] *)
  1107. Resolve(irMemoryOperand);
  1108. baseAddressRegister := RegisterFromSymbol(irMemoryOperand.symbol.name, irMemoryOperand.symbol.fingerprint, irMemoryOperand.resolved, irMemoryOperand.symbolOffset, registerHint);
  1109. baseAddressRegisterNumber := baseAddressRegister.register
  1110. ELSE
  1111. (* case 3: [123456] *)
  1112. ASSERT(irMemoryOperand.offset = 0);
  1113. baseAddressRegister := RegisterFromValue(LONGINT(irMemoryOperand.intValue), registerHint);
  1114. baseAddressRegisterNumber := baseAddressRegister.register
  1115. END;
  1116. ASSERT(baseAddressRegisterNumber # None);
  1117. (* get offset of part in question *)
  1118. offset := irMemoryOperand.offset + part * 4;
  1119. (* determine indexing mode *)
  1120. IF offset >= 0 THEN indexingMode := {InstructionSet.Increment} ELSE indexingMode := {InstructionSet.Decrement} END;
  1121. IF irMemoryOperand.type.form IN IntermediateCode.Integer THEN
  1122. (* regular ARM memory operand *)
  1123. (*! LDRH supports only 8 bits immediates, while LDR and LDRB support 12 bits immediates *)
  1124. IF ((irMemoryOperand.type.sizeInBits = 16) & (ABS(offset) < 256)) OR ((irMemoryOperand.type.sizeInBits # 16) & (ABS(offset) < InstructionSet.Bits12)) THEN
  1125. (* offset can be encoded directly *)
  1126. result := InstructionSet.NewImmediateOffsetMemory(baseAddressRegisterNumber, ABS(offset), indexingMode)
  1127. ELSE
  1128. (* offset has to be provided in a register *)
  1129. offsetRegister := RegisterFromValue(ABS(offset), emptyOperand);
  1130. result := InstructionSet.NewRegisterOffsetMemory(baseAddressRegisterNumber, offsetRegister.register, None, 0, indexingMode)
  1131. END
  1132. ELSIF irMemoryOperand.type.form = IntermediateCode.Float THEN
  1133. (* VFP memory operand *)
  1134. ASSERT((ABS(offset) MOD 4) = 0);
  1135. IF ABS(offset) >= 1024 THEN
  1136. (* offset cannot be encoded directly _> it has to be provided by means of an adapted base register *)
  1137. tempRegister := RegisterFromValue(ABS(offset), emptyOperand);
  1138. IF offset < 0 THEN
  1139. Emit3(opSUB, tempRegister, tempRegister, baseAddressRegister)
  1140. ELSE
  1141. Emit3(opADD, tempRegister, tempRegister, baseAddressRegister)
  1142. END;
  1143. ReleaseHint(baseAddressRegister.register);
  1144. baseAddressRegister := tempRegister;
  1145. baseAddressRegisterNumber := baseAddressRegister.register;
  1146. offset := 0;
  1147. END;
  1148. result := InstructionSet.NewImmediateOffsetMemory(baseAddressRegisterNumber, ABS(offset), indexingMode)
  1149. ELSE
  1150. HALT(100)
  1151. END;
  1152. ASSERT(result.mode = InstructionSet.modeMemory);
  1153. RETURN result
  1154. END MemoryOperandFromIrMemoryOperand;
  1155. (** get an ARM immediate operand or register from any IR operand
  1156. - if possible, the an immediate is returned
  1157. - if needed, use register hint if provided
  1158. **)
  1159. PROCEDURE RegisterOrImmediateFromIrOperand(VAR irOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  1160. VAR
  1161. result: Operand;
  1162. BEGIN
  1163. IF IrOperandIsDirectlyEncodable(irOperand, part) THEN
  1164. result := InstructionSet.NewImmediate(ValueOfPart(irOperand.intValue, part))
  1165. ELSE
  1166. result := RegisterFromIrOperand(irOperand, part, registerHint)
  1167. END;
  1168. RETURN result
  1169. END RegisterOrImmediateFromIrOperand;
  1170. (** get an ARM register operand from any IR operand
  1171. - use register hint if provided
  1172. **)
  1173. PROCEDURE RegisterFromIrOperand(VAR irOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  1174. VAR
  1175. result: Operand;
  1176. BEGIN
  1177. CASE irOperand.mode OF
  1178. | IntermediateCode.ModeRegister:
  1179. ASSERT((irOperand.intValue = 0) & (irOperand.symbol.name = ""));
  1180. result := RegisterFromIrRegister(irOperand, part, registerHint)
  1181. | IntermediateCode.ModeMemory:
  1182. result := GetFreeRegisterOrHint(PartType(irOperand.type, part), registerHint);
  1183. Load(result, MemoryOperandFromIrMemoryOperand(irOperand, part, result), PartType(irOperand.type, part))
  1184. | IntermediateCode.ModeImmediate:
  1185. ASSERT(irOperand.register = IntermediateCode.None);
  1186. IF irOperand.symbol.name # "" THEN
  1187. Resolve(irOperand);
  1188. result := RegisterFromSymbol(irOperand.symbol.name, irOperand.symbol.fingerprint, irOperand.resolved, irOperand.symbolOffset, emptyOperand);
  1189. result := RegisterAfterAppliedOffset(result, irOperand.offset, registerHint);
  1190. ELSE
  1191. ASSERT(irOperand.offset = 0);
  1192. IF IsInteger(irOperand) THEN result := RegisterFromValue(ValueOfPart(irOperand.intValue, part), registerHint)
  1193. ELSIF IsSinglePrecisionFloat(irOperand) & backend.useFPU32 THEN result := SinglePrecisionFloatRegisterFromValue(REAL(irOperand.floatValue), registerHint)
  1194. ELSIF IsDoublePrecisionFloat(irOperand) & backend.useFPU64 THEN result := DoublePrecisionFloatRegisterFromValue(irOperand.floatValue, registerHint)
  1195. ELSE
  1196. IF IsSinglePrecisionFloat(irOperand) THEN
  1197. result := RegisterFromValue(BinaryCode.ConvertReal(SHORT(irOperand.floatValue)), registerHint)
  1198. ELSE
  1199. result := RegisterFromValue(ValueOfPart(BinaryCode.ConvertLongreal(irOperand.floatValue),part), registerHint);
  1200. END;
  1201. END
  1202. END
  1203. ELSE
  1204. HALT(100)
  1205. END;
  1206. ASSERT(result.mode = InstructionSet.modeRegister);
  1207. RETURN result
  1208. END RegisterFromIrOperand;
  1209. (** whether an IR operand is complex, i.e., requires more than one ARM operands to be represented **)
  1210. PROCEDURE IsComplex(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1211. VAR
  1212. result: BOOLEAN;
  1213. BEGIN
  1214. IF (irOperand.type.form IN IntermediateCode.Integer) THEN
  1215. result := irOperand.type.sizeInBits > 32 (* integers above 32 bits have to be represented in multiple registers *)
  1216. ELSIF irOperand.type.form = IntermediateCode.Float THEN
  1217. result := (irOperand.type.sizeInBits > 32) & ~backend.useFPU64 (* integers above 32 bits have to be represented in multiple registers *)
  1218. ELSE
  1219. HALT(100)
  1220. END;
  1221. RETURN result
  1222. END IsComplex;
  1223. (** whether an IR operand hold a single precision floating point value **)
  1224. PROCEDURE IsSinglePrecisionFloat(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1225. BEGIN RETURN (irOperand.type.sizeInBits = 32) & (irOperand.type.form = IntermediateCode.Float)
  1226. END IsSinglePrecisionFloat;
  1227. (** whether an IR operand hold a single precision floating point value **)
  1228. PROCEDURE IsDoublePrecisionFloat(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1229. BEGIN RETURN (irOperand.type.sizeInBits = 64) & (irOperand.type.form = IntermediateCode.Float)
  1230. END IsDoublePrecisionFloat;
  1231. PROCEDURE IsFloat(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1232. BEGIN
  1233. RETURN irOperand.type.form = IntermediateCode.Float
  1234. END IsFloat;
  1235. (** whether an IR operand hold am integer value **)
  1236. PROCEDURE IsInteger(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1237. BEGIN RETURN irOperand.type.form IN IntermediateCode.Integer
  1238. END IsInteger;
  1239. (** whether an IR operand hold am integer value **)
  1240. PROCEDURE IsNonComplexInteger(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1241. BEGIN RETURN (irOperand.type.form IN IntermediateCode.Integer) & (irOperand.type.sizeInBits <= 32)
  1242. END IsNonComplexInteger;
  1243. (** whether an IR operand hold am integer value **)
  1244. PROCEDURE IsInteger64(CONST irOperand: IntermediateCode.Operand): BOOLEAN;
  1245. BEGIN RETURN (irOperand.type.form IN IntermediateCode.Integer) & (irOperand.type.sizeInBits = 64)
  1246. END IsInteger64;
  1247. PROCEDURE PartType(CONST type: IntermediateCode.Type; part: LONGINT): IntermediateCode.Type;
  1248. VAR
  1249. result: IntermediateCode.Type;
  1250. BEGIN
  1251. GetPartType(type, part, result);
  1252. RETURN result
  1253. END PartType;
  1254. (* the intermediate code type of a part
  1255. - a part type is by definition directly representable in a register *)
  1256. PROCEDURE GetPartType(CONST type: IntermediateCode.Type; part: LONGINT; VAR partType: IntermediateCode.Type);
  1257. BEGIN
  1258. ASSERT((part = Low) OR (part = High));
  1259. IF (type.sizeInBits <= 32) OR (type.form = IntermediateCode.Float) & backend.useFPU64 THEN
  1260. IF part = Low THEN
  1261. partType := type
  1262. ELSE
  1263. partType := IntermediateCode.undef
  1264. END
  1265. ELSIF type.sizeInBits = 64 THEN
  1266. IF part = Low THEN
  1267. partType := IntermediateCode.NewType(IntermediateCode.UnsignedInteger, 32) (* conceptually the low part is always unsigned *)
  1268. ELSE
  1269. IF type.form = IntermediateCode.Float THEN
  1270. partType := IntermediateCode.NewType(IntermediateCode.SignedInteger, 32)
  1271. ELSE
  1272. partType := IntermediateCode.NewType(type.form, 32)
  1273. END;
  1274. END
  1275. ELSE
  1276. HALT(100)
  1277. END;
  1278. ASSERT(partType.form > IntermediateCode.Undefined);
  1279. END GetPartType;
  1280. (** the value of a 32 bit part **)
  1281. PROCEDURE ValueOfPart(value: HUGEINT; part: LONGINT): LONGINT;
  1282. VAR
  1283. result: LONGINT;
  1284. BEGIN
  1285. IF part = Low THEN
  1286. result := LONGINT(value) (* get the 32 least significant bits *)
  1287. ELSIF part = High THEN
  1288. result := LONGINT(ASH(value, -32)) (* get the 32 most significant bits *)
  1289. ELSE
  1290. HALT(100)
  1291. END;
  1292. RETURN result
  1293. END ValueOfPart;
  1294. (** whether a 32 bit value can be directly encoded as an ARM immediate (using a 8-bit base value and 4-bit half rotation) **)
  1295. PROCEDURE ValueIsDirectlyEncodable(value: LONGINT): BOOLEAN;
  1296. VAR
  1297. baseValue, halfRotation: LONGINT;
  1298. result: BOOLEAN;
  1299. BEGIN
  1300. result := InstructionSet.EncodeImmediate(value, baseValue, halfRotation);
  1301. RETURN result
  1302. END ValueIsDirectlyEncodable;
  1303. (* whether an IR operand (or part thereof) can be directly encoded as an ARM immediate *)
  1304. PROCEDURE IrOperandIsDirectlyEncodable(irOperand: IntermediateCode.Operand; part: LONGINT): BOOLEAN;
  1305. BEGIN RETURN
  1306. (irOperand.mode = IntermediateCode.ModeImmediate) &
  1307. (irOperand.symbol.name = "") &
  1308. (irOperand.type.form IN IntermediateCode.Integer) &
  1309. ValueIsDirectlyEncodable(ValueOfPart(irOperand.intValue, part))
  1310. END IrOperandIsDirectlyEncodable;
  1311. (* whether the negation of an IR operand (or part thereof) can be directly encoded as an ARM immediate *)
  1312. PROCEDURE NegatedIrOperandIsDirectlyEncodable(irOperand: IntermediateCode.Operand; part: LONGINT): BOOLEAN;
  1313. BEGIN RETURN
  1314. (irOperand.mode = IntermediateCode.ModeImmediate) &
  1315. (irOperand.symbol.name = "") &
  1316. (irOperand.type.form IN IntermediateCode.Integer) &
  1317. ValueIsDirectlyEncodable(ValueOfPart(-irOperand.intValue, part)) (* note the minus sign *)
  1318. END NegatedIrOperandIsDirectlyEncodable;
  1319. (** generate code for a certain IR instruction **)
  1320. PROCEDURE Generate(VAR irInstruction: IntermediateCode.Instruction);
  1321. BEGIN
  1322. (* CheckFixups; *)
  1323. EmitFixupBlockIfNeeded;
  1324. (*
  1325. IF ((irInstruction.opcode = IntermediateCode.mov) OR (irInstruction.opcode = IntermediateCode.pop)) & (instruction.op1.register <= IntermediateCode.ParameterRegister) THEN
  1326. hwreg := ParameterRegister(IntermediateCode.ParameterRegister-instruction.op1.register, instruction.op1.type);
  1327. Spill(physicalRegisters.Mapped(hwreg));
  1328. lastUse := inPC+1;
  1329. WHILE (lastUse < in.pc) &
  1330. ((in.instructions[lastUse].opcode # IntermediateCode.push) OR (in.instructions[lastUse].op1.register # instruction.op1.register)) & (in.instructions[lastUse].opcode # IntermediateCode.call) DO
  1331. INC(lastUse)
  1332. END;
  1333. ticket := ReservePhysicalRegister(instruction.op1.type,hwreg,lastUse);
  1334. END;
  1335. *)
  1336. ReserveOperandRegisters(irInstruction.op1, TRUE);
  1337. ReserveOperandRegisters(irInstruction.op2, TRUE);
  1338. ReserveOperandRegisters(irInstruction.op3, TRUE);
  1339. CASE irInstruction.opcode OF
  1340. | IntermediateCode.nop: (* do nothing *)
  1341. | IntermediateCode.mov: EmitMov(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitMov(irInstruction, High) END
  1342. | IntermediateCode.conv: EmitConv(irInstruction)
  1343. | IntermediateCode.call: EmitCall(irInstruction)
  1344. | IntermediateCode.enter: EmitEnter(irInstruction)
  1345. | IntermediateCode.leave: EmitLeave(irInstruction)
  1346. | IntermediateCode.exit: EmitExit(irInstruction)
  1347. | IntermediateCode.return: EmitReturn(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitReturn(irInstruction, High) END;
  1348. | IntermediateCode.result: EmitResult(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitResult(irInstruction, High) END;
  1349. | IntermediateCode.trap: EmitTrap(irInstruction);
  1350. | IntermediateCode.br .. IntermediateCode.brlt: EmitBr(irInstruction)
  1351. | IntermediateCode.pop: EmitPop(irInstruction.op1, Low); IF IsComplex(irInstruction.op1) THEN EmitPop(irInstruction.op1, High) END
  1352. | IntermediateCode.push: IF IsComplex(irInstruction.op1) THEN EmitPush(irInstruction.op1, High) END; EmitPush(irInstruction.op1, Low)
  1353. | IntermediateCode.neg: EmitNeg(irInstruction)
  1354. | IntermediateCode.not: EmitNot(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitNot(irInstruction, High) END
  1355. | IntermediateCode.abs: EmitAbs(irInstruction)
  1356. | IntermediateCode.mul: EmitMul(irInstruction)
  1357. | IntermediateCode.div: EmitDiv(irInstruction)
  1358. | IntermediateCode.mod: EmitMod(irInstruction)
  1359. | IntermediateCode.sub, IntermediateCode.add: EmitAddOrSub(irInstruction)
  1360. | IntermediateCode.and: EmitAnd(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitAnd(irInstruction, High) END
  1361. | IntermediateCode.or: EmitOr(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitOr(irInstruction, High) END
  1362. | IntermediateCode.xor: EmitXor(irInstruction, Low); IF IsComplex(irInstruction.op1) THEN EmitXor(irInstruction, High) END
  1363. | IntermediateCode.shl: EmitShiftOrRotation(irInstruction)
  1364. | IntermediateCode.shr: EmitShiftOrRotation(irInstruction)
  1365. | IntermediateCode.rol: EmitShiftOrRotation(irInstruction)
  1366. | IntermediateCode.ror: EmitShiftOrRotation(irInstruction)
  1367. | IntermediateCode.cas: EmitCas(irInstruction);
  1368. | IntermediateCode.copy: EmitCopy(irInstruction)
  1369. | IntermediateCode.fill: EmitFill(irInstruction, FALSE)
  1370. | IntermediateCode.asm: EmitAsm(irInstruction)
  1371. | IntermediateCode.special: EmitSpecial(irInstruction)
  1372. END;
  1373. ReserveOperandRegisters(irInstruction.op3, FALSE);
  1374. ReserveOperandRegisters(irInstruction.op2 ,FALSE);
  1375. ReserveOperandRegisters(irInstruction.op1, FALSE);
  1376. END Generate;
  1377. PROCEDURE PostGenerate(CONST instruction: IntermediateCode.Instruction);
  1378. VAR ticket: Ticket;
  1379. BEGIN
  1380. TryUnmap(instruction.op3); TryUnmap(instruction.op2); TryUnmap(instruction.op1);
  1381. ticket := tickets.live;
  1382. WHILE (ticket # NIL) & (ticket.lastuse = inPC) DO
  1383. UnmapTicket(ticket);
  1384. ticket := tickets.live
  1385. END;
  1386. END PostGenerate;
  1387. PROCEDURE EmitFinalFixupBlock;
  1388. BEGIN
  1389. IF listOfReferences.size > 0 THEN
  1390. ASSERT(in.pc > 0);
  1391. IF in.instructions[in.pc - 1].opcode # IntermediateCode.exit THEN
  1392. (* there is no exit instruction at the end of the IR section -> emit a branch that skips the fixup block (in particular used by @BodyStub procedures)*)
  1393. Emit1(opB, InstructionSet.NewImmediate(4 + listOfReferences.size - 8))
  1394. END
  1395. END;
  1396. EmitFixupBlock; (* emit the fixup block *)
  1397. END EmitFinalFixupBlock;
  1398. (* if needed, emit fixup block for all used symbol references
  1399. - the fixup block is skipped by a branch instruction
  1400. - afterwards, the list of references is cleared
  1401. *)
  1402. PROCEDURE EmitFixupBlockIfNeeded;
  1403. BEGIN
  1404. IF out.pc >= listOfReferences.due THEN
  1405. listOfReferences.due := MAX(LONGINT);
  1406. Emit1(opB, InstructionSet.NewImmediate(4 + listOfReferences.size - 8 )); (* emit branch instruction that skips the fixup block *)
  1407. EmitFixupBlock; (* emit the fixup block *)
  1408. listOfReferences.Init (* clear the list *)
  1409. END
  1410. END EmitFixupBlockIfNeeded;
  1411. (* emit fixup block for all used symbol references, and clear the list *)
  1412. PROCEDURE EmitFixupBlock;
  1413. VAR
  1414. reference: Reference;
  1415. citation: Citation;
  1416. patchValue: LONGINT;
  1417. BEGIN
  1418. IF listOfReferences.size > 0 THEN
  1419. IF out.comments # NIL THEN
  1420. out.comments.String("REFERENCES BLOCK"); out.comments.String(" (");
  1421. out.comments.Int(listOfReferences.size, 0);
  1422. out.comments.String(" bytes):"); out.comments.Ln; out.comments.Update
  1423. END;
  1424. reference := listOfReferences.firstReference;
  1425. WHILE reference # NIL DO
  1426. (* 1. patch all of the citations, i.e., the LDR instructions that use the symbol reference *)
  1427. citation := reference.firstCitation;
  1428. WHILE citation # NIL DO
  1429. patchValue := out.pc - 8 - citation.pc;
  1430. patchValue := ASH(patchValue, -citation.shift); (* FLDS/VLDR reference counts number of words *)
  1431. ASSERT((0 <= patchValue) & (patchValue < ASH(1, citation.bits)));
  1432. out.PutBitsAt(citation.pc, patchValue, citation.bits);
  1433. citation := citation.next
  1434. END;
  1435. reference.Emit(out);
  1436. reference := reference.next
  1437. END
  1438. END
  1439. END EmitFixupBlock;
  1440. (** get an ARM operand that hold a certain value
  1441. - if possible the value is returned as an ARM immediate operand
  1442. - otherwise a register is returned instead (if a register hint is present, it is used) **)
  1443. PROCEDURE OperandFromValue(value: LONGINT; registerHint: Operand): Operand;
  1444. VAR
  1445. result: Operand;
  1446. BEGIN
  1447. IF ValueIsDirectlyEncodable(value) THEN
  1448. result := InstructionSet.NewImmediate(value)
  1449. ELSE
  1450. result := RegisterFromValue(value, registerHint)
  1451. END;
  1452. RETURN result
  1453. END OperandFromValue;
  1454. (** get a single precision VFP register that holds a certain floating point value **)
  1455. PROCEDURE SinglePrecisionFloatRegisterFromValue(value: REAL; registerHint: Operand): Operand;
  1456. VAR
  1457. intValue, dummy: LONGINT;
  1458. result, temp: Operand;
  1459. BEGIN
  1460. intValue := SYSTEM.VAL(LONGINT, value);
  1461. (* alternative: integerValue := BinaryCode.ConvertReal(value) *)
  1462. temp := RegisterFromValue(intValue, registerHint);
  1463. result := GetFreeRegisterOrHint(IntermediateCode.FloatType(32), registerHint);
  1464. Emit2(opFMSR, result, temp);
  1465. ASSERT(result.mode = InstructionSet.modeRegister);
  1466. ASSERT((result.register >= InstructionSet.SR0) & (result.register <= InstructionSet.SR31));
  1467. RETURN result;
  1468. END SinglePrecisionFloatRegisterFromValue;
  1469. (** get a single precision VFP register that holds a certain floating point value **)
  1470. PROCEDURE DoublePrecisionFloatRegisterFromValue(value: LONGREAL; registerHint: Operand): Operand;
  1471. VAR
  1472. intValue: HUGEINT; dummy: LONGINT;
  1473. result, temp: Operand;
  1474. BEGIN
  1475. intValue := SYSTEM.VAL(HUGEINT, value);
  1476. (* alternative: integerValue := BinaryCode.ConvertReal(value) *)
  1477. result := GetFreeRegisterOrHint(IntermediateCode.FloatType(64), registerHint);
  1478. listOfReferences.AddHImmediate(intValue, out.pc, 8);
  1479. Emit2(opFLDD, result, InstructionSet.NewImmediateOffsetMemory(opPC.register, 0, {InstructionSet.Increment})); (* LDR ..., [PC, #+???] *)
  1480. ASSERT(result.mode = InstructionSet.modeRegister);
  1481. ASSERT((result.register >= InstructionSet.DR0) & (result.register <= InstructionSet.DR31));
  1482. RETURN result;
  1483. END DoublePrecisionFloatRegisterFromValue;
  1484. (** get an ARM register that holds a certain integer value
  1485. - if a register hint is present, it is used **)
  1486. PROCEDURE RegisterFromValue(value: LONGINT; registerHint: Operand): Operand;
  1487. VAR
  1488. dummy: LONGINT;
  1489. result: Operand;
  1490. BEGIN
  1491. result := GetFreeRegisterOrHint(IntermediateCode.SignedIntegerType(32), registerHint);
  1492. IF ValueComposition(value, FALSE, result) < 3 THEN
  1493. dummy := ValueComposition(value, TRUE, result);
  1494. ELSE
  1495. result := GetFreeRegisterOrHint(IntermediateCode.UnsignedIntegerType(32), registerHint);
  1496. listOfReferences.AddImmediate(value, out.pc, 12);
  1497. Emit2(opLDR, result, InstructionSet.NewImmediateOffsetMemory(opPC.register, 0, {InstructionSet.Increment})); (* LDR ..., [PC, #+???] *)
  1498. END;
  1499. ASSERT(result.mode = InstructionSet.modeRegister);
  1500. ASSERT((result.register >= InstructionSet.R0) & (result.register <= InstructionSet.R15));
  1501. RETURN result
  1502. END RegisterFromValue;
  1503. (** allocate or deallocate on the stack
  1504. - note: updateStackSize is important as intermediate RETURNs should not change stack size
  1505. **)
  1506. PROCEDURE AllocateStack(allocationSize: LONGINT; doUpdateStackSize: BOOLEAN; clear: BOOLEAN);
  1507. VAR
  1508. operand, zero, count: InstructionSet.Operand; i: LONGINT;
  1509. BEGIN
  1510. inStackAllocation := TRUE;
  1511. operand := OperandFromValue(ABS(allocationSize), emptyOperand);
  1512. IF allocationSize > 0 THEN
  1513. IF clear THEN
  1514. zero := InstructionSet.NewRegister(0, None, None, 0);
  1515. Emit2(opMOV, zero , InstructionSet.NewImmediate(0));
  1516. IF allocationSize < 16 THEN
  1517. FOR i := 0 TO allocationSize-1 BY 4 DO
  1518. Emit2(opSTR, InstructionSet.NewRegister(0, None, None, 0), InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1519. END;
  1520. ELSE
  1521. count := InstructionSet.NewRegister(1, None, None, 0);
  1522. Emit1(opB, InstructionSet.NewImmediate(0)); (* PC offset = 8 ! Jump over immediate *)
  1523. out.PutBits(allocationSize DIV 4, 32);
  1524. Emit2(opLDR, count, InstructionSet.NewImmediateOffsetMemory(InstructionSet.PC, 8+4, {InstructionSet.Decrement}));
  1525. (* label *)
  1526. Emit2(opSTR, zero, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1527. Emit3WithFlags(opSUB, count, count, InstructionSet.NewImmediate(1),{InstructionSet.flagS});
  1528. Emit1WithCondition(opB, InstructionSet.NewImmediate(-8 -8), InstructionSet.conditionGT); (* label *)
  1529. END;
  1530. ELSE
  1531. Emit3(opSUB, opSP, opSP, operand) (* decreasing SP: allocation *)
  1532. END;
  1533. ELSIF allocationSize < 0 THEN
  1534. Emit3(opADD, opSP, opSP, operand) (* increasing SP: deallocation *)
  1535. END;
  1536. IF doUpdateStackSize THEN stackSize := stackSize + allocationSize END;
  1537. inStackAllocation := FALSE
  1538. END AllocateStack;
  1539. (** whether two ARM operands represent the same physical register **)
  1540. PROCEDURE IsSameRegister(CONST a, b: Operand): BOOLEAN;
  1541. BEGIN RETURN (a.mode = InstructionSet.modeRegister) & (b.mode = InstructionSet.modeRegister) & (a.register = b.register)
  1542. END IsSameRegister;
  1543. (** emit a MOV instruction if the two operands do not represent the same register
  1544. - for moves involving floating point registers special VFP instructions opFCPYS, opFMSR and opFMRS are used
  1545. **)
  1546. PROCEDURE MovIfDifferent(CONST a, b: Operand);
  1547. BEGIN
  1548. IF ~IsSameRegister(a, b) THEN
  1549. ASSERT(a.mode = InstructionSet.modeRegister);
  1550. IF IsRegisterForType(a.register, IntermediateCode.FloatType(64)) THEN
  1551. IF IsRegisterForType(b.register, IntermediateCode.FloatType(64)) THEN
  1552. (* mov float, double: *)
  1553. Emit2(opFCPYD, a, b)
  1554. ELSIF IsRegisterForType(b.register, IntermediateCode.FloatType(32)) THEN
  1555. (* mov float, float: *)
  1556. Emit2(opFCVTSD, a, b)
  1557. ELSE
  1558. HALT(200);
  1559. END
  1560. ELSIF IsRegisterForType(a.register, IntermediateCode.FloatType(32)) THEN
  1561. IF IsRegisterForType(b.register, IntermediateCode.FloatType(64)) THEN
  1562. (* mov float, double: *)
  1563. Emit2(opFCVTSD, a, b)
  1564. ELSIF IsRegisterForType(b.register, IntermediateCode.FloatType(32)) THEN
  1565. (* mov float, float: *)
  1566. Emit2(opFCPYS, a, b)
  1567. ELSE
  1568. (* mov float, int: *)
  1569. Emit2(opFMSR, a, b)
  1570. END
  1571. ELSE
  1572. IF IsRegisterForType(b.register, IntermediateCode.FloatType(32)) THEN
  1573. (* mov int, float: *)
  1574. Emit2(opFMRS, a, b)
  1575. ELSIF IsRegisterForType(b.register, IntermediateCode.FloatType(64)) THEN
  1576. HALT(200)
  1577. ELSE
  1578. (* mov int, int: *)
  1579. Emit2(opMOV, a, b)
  1580. END
  1581. END
  1582. END
  1583. END MovIfDifferent;
  1584. (** acquire an ARM register fr oa IR destination operand part
  1585. - if IR operand is a memory location, get a temporary register (if provided the hinted register is used)
  1586. - if IR operand is an IR register, get the ARM register that is mapped to the corresponding part
  1587. **)
  1588. PROCEDURE AcquireDestinationRegister(CONST irDestinationOperand: IntermediateCode.Operand; part: LONGINT; registerHint: Operand): Operand;
  1589. VAR
  1590. result: Operand;
  1591. BEGIN
  1592. IF irDestinationOperand.mode = IntermediateCode.ModeMemory THEN
  1593. result := GetFreeRegisterOrHint(PartType(irDestinationOperand.type, part), registerHint)
  1594. ELSIF irDestinationOperand.mode = IntermediateCode.ModeRegister THEN
  1595. ASSERT(irDestinationOperand.offset = 0);
  1596. IF virtualRegisters.Mapped(irDestinationOperand.register, part) = NIL THEN TryAllocate(irDestinationOperand, part) END; (* create the mapping if not yet done *)
  1597. result := InstructionSet.NewRegister(PhysicalRegisterNumber(irDestinationOperand.register, part), None, None, 0)
  1598. ELSE
  1599. HALT(100)
  1600. END;
  1601. ASSERT(result.mode = InstructionSet.modeRegister);
  1602. RETURN result
  1603. END AcquireDestinationRegister;
  1604. (** write the content of an ARM register to an IR destination operand (memory location or IR register)
  1605. - afterwards, try to release the register
  1606. **)
  1607. PROCEDURE WriteBack(VAR irDestinationOperand: IntermediateCode.Operand; part: LONGINT; register: Operand);
  1608. VAR
  1609. mappedArmRegister: Operand;
  1610. BEGIN
  1611. ASSERT(register.mode = InstructionSet.modeRegister);
  1612. IF irDestinationOperand.mode = IntermediateCode.ModeMemory THEN
  1613. Store(register, MemoryOperandFromIrMemoryOperand(irDestinationOperand, part, emptyOperand), PartType(irDestinationOperand.type, part))
  1614. ELSIF irDestinationOperand.mode = IntermediateCode.ModeRegister THEN
  1615. ASSERT((virtualRegisters.Mapped(irDestinationOperand.register, part) # NIL)
  1616. OR (irDestinationOperand.register = IntermediateCode.SP)
  1617. OR (irDestinationOperand.register = IntermediateCode.FP)
  1618. OR (irDestinationOperand.register = IntermediateCode.LR)
  1619. OR (irDestinationOperand.register = IntermediateCode.AP));
  1620. mappedArmRegister := InstructionSet.NewRegister(PhysicalRegisterNumber(irDestinationOperand.register, part), None, None, 0);
  1621. MovIfDifferent(mappedArmRegister, register)
  1622. ELSE
  1623. HALT(100)
  1624. END;
  1625. ReleaseHint(register.register)
  1626. END WriteBack;
  1627. PROCEDURE ZeroExtendOperand(operand: Operand; sizeInBits: LONGINT);
  1628. BEGIN
  1629. ASSERT(sizeInBits <= 32);
  1630. IF operand.mode = InstructionSet.modeRegister THEN
  1631. IF sizeInBits = 8 THEN
  1632. Emit3(opAND, operand, operand, InstructionSet.NewImmediate(255)); (* AND reg, reg, 11111111b *)
  1633. ELSIF sizeInBits = 16 THEN
  1634. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSL, None, 16));
  1635. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSR, None, 16))
  1636. ELSIF sizeInBits = 32 THEN
  1637. (* nothing to do *)
  1638. ELSE
  1639. HALT(100)
  1640. END
  1641. ELSIF (sizeInBits < 32) THEN
  1642. ASSERT(operand.mode = InstructionSet.modeImmediate);
  1643. END
  1644. END ZeroExtendOperand;
  1645. PROCEDURE SignExtendOperand(operand: Operand; sizeInBits: LONGINT);
  1646. BEGIN
  1647. ASSERT(sizeInBits <= 32);
  1648. IF operand.mode = InstructionSet.modeRegister THEN
  1649. IF sizeInBits < 32 THEN
  1650. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftLSL, None, 32 - sizeInBits));
  1651. Emit2(opMOV, operand, InstructionSet.NewRegister(operand.register, InstructionSet.shiftASR, None, 32 - sizeInBits))
  1652. END
  1653. ELSIF (sizeInBits < 32) THEN
  1654. ASSERT(operand.mode = InstructionSet.modeImmediate);
  1655. END
  1656. END SignExtendOperand;
  1657. (** sign or zero-extends the content of an operand to 32 bits, depending on the IR type **)
  1658. PROCEDURE SignOrZeroExtendOperand(operand: Operand; irType: IntermediateCode.Type);
  1659. BEGIN
  1660. ASSERT(irType.sizeInBits <= 32);
  1661. IF irType.form = IntermediateCode.UnsignedInteger THEN
  1662. ZeroExtendOperand(operand, irType.sizeInBits)
  1663. ELSE
  1664. SignExtendOperand(operand, irType.sizeInBits)
  1665. END
  1666. END SignOrZeroExtendOperand;
  1667. (* ACTUAL CODE GENERATION *)
  1668. PROCEDURE EmitPush(VAR irOperand: IntermediateCode.Operand; part: LONGINT);
  1669. VAR
  1670. register: Operand;
  1671. partType: IntermediateCode.Type;
  1672. (*pc: LONGINT;*)
  1673. BEGIN
  1674. register := RegisterFromIrOperand(irOperand, part, emptyOperand);
  1675. IF ~IsRegisterForType(register.register, IntermediateCode.FloatType(32)) & ~IsRegisterForType(register.register, IntermediateCode.FloatType(64)) THEN
  1676. Emit2(opSTR, register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Decrement, InstructionSet.PreIndexed}));
  1677. ELSE
  1678. partType := PartType(irOperand.type, part);
  1679. AllocateStack(MAX(4, partType.sizeInBits DIV 8), TRUE,FALSE);
  1680. Store(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 0, {InstructionSet.Increment}), PartType(irOperand.type, part));
  1681. END;
  1682. (*
  1683. (* optimization for push chains (THIS DOES NOT WORK IF inEmulation) *)
  1684. IF pushChainLength = 0 THEN
  1685. pc := inPC;
  1686. (* search for consecutive push instructions *)
  1687. WHILE (pc < in.pc) & (in.instructions[pc].opcode = IntermediateCode.push) DO
  1688. ASSERT(in.instructions[pc].op1.mode # IntermediateCode.Undefined);
  1689. INC(pushChainLength, MAX(4, in.instructions[pc].op1.type.sizeInBits DIV 8));
  1690. INC(pc)
  1691. END;
  1692. AllocateStack(pushChainLength, TRUE)
  1693. END;
  1694. DEC(pushChainLength, 4); (* for 64 bit operands, this procedure is executed twice -> the push chain will be decremented by 8 bytes *)
  1695. register := RegisterFromIrOperand(irOperand, part, emptyOperand);
  1696. ASSERT(pushChainLength < InstructionSet.Bits12, 100);
  1697. ASSERT((pushChainLength MOD 4) = 0);
  1698. Store(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, pushChainLength, {InstructionSet.Increment}), PartType(irOperand.type, part))
  1699. *)
  1700. END EmitPush;
  1701. PROCEDURE EmitPop(VAR irOperand: IntermediateCode.Operand; part: LONGINT);
  1702. VAR
  1703. register: Operand; partType: IntermediateCode.Type;
  1704. BEGIN
  1705. register := AcquireDestinationRegister(irOperand, part, emptyOperand);
  1706. IF ~IsRegisterForType(register.register, IntermediateCode.FloatType(32)) & ~IsRegisterForType(register.register, IntermediateCode.FloatType(64)) THEN
  1707. (*Emit2(opLDR, register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}));*)
  1708. Load(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}), PartType(irOperand.type, part));
  1709. ELSE
  1710. Load(register, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 0, {InstructionSet.Increment}), PartType(irOperand.type, part));
  1711. partType := PartType(irOperand.type, part);
  1712. AllocateStack(-MAX(4, partType.sizeInBits DIV 8), TRUE,FALSE);
  1713. END;
  1714. WriteBack(irOperand, part, register)
  1715. END EmitPop;
  1716. PROCEDURE Resolve(VAR op: IntermediateCode.Operand);
  1717. BEGIN
  1718. IF (op.symbol.name # "") & (op.resolved = NIL) THEN op.resolved := module.allSections.FindByName(op.symbol.name) END
  1719. END Resolve;
  1720. (* call <address>, <parSize> *)
  1721. PROCEDURE EmitCall(VAR irInstruction: IntermediateCode.Instruction);
  1722. VAR
  1723. code: BinaryCode.Section;
  1724. fixup, newFixup: BinaryCode.Fixup;
  1725. BEGIN
  1726. Resolve(irInstruction.op1);
  1727. IF (irInstruction.op1.resolved # NIL) & (irInstruction.op1.resolved.type = Sections.InlineCodeSection) THEN
  1728. (* call of an inline procedure: *)
  1729. code := irInstruction.op1.resolved(IntermediateCode.Section).resolved;
  1730. ASSERT(code # NIL); (* TODO: what if section is not yet resolved, i.e., code has not yet been generated? *)
  1731. IF (out.comments # NIL) THEN
  1732. out.comments.String("inlined code sequence:");
  1733. out.comments.Ln;
  1734. out.comments.Update;
  1735. END;
  1736. (* emit the generated code of the other section *)
  1737. out.CopyBits(code.os.bits, 0, code.os.bits.GetSize());
  1738. (* transfer the fixups *)
  1739. fixup := code.fixupList.firstFixup;
  1740. WHILE fixup # NIL DO
  1741. newFixup := BinaryCode.NewFixup(fixup.mode, fixup.offset + code.pc, fixup.symbol, fixup.symbolOffset, fixup.displacement, fixup.scale, fixup.pattern);
  1742. out.fixupList.AddFixup(newFixup);
  1743. fixup := fixup.nextFixup
  1744. END
  1745. ELSE
  1746. (* store the address of the procedure in a register and branch and link there *)
  1747. Emit1(opBLX, RegisterFromIrOperand(irInstruction.op1, Low, emptyOperand));
  1748. (* remove parameters on stack *)
  1749. AllocateStack(-LONGINT(irInstruction.op2.intValue), TRUE, FALSE)
  1750. END
  1751. END EmitCall;
  1752. (* enter <callingConvention>, <pafSize>, <numRegParams> *)
  1753. PROCEDURE EmitEnter(CONST irInstruction: IntermediateCode.Instruction);
  1754. VAR allocationSize: LONGINT;
  1755. BEGIN
  1756. (* store registers for interrupts, if required *)
  1757. IF (irInstruction.op1.intValue = SyntaxTree.InterruptCallingConvention) THEN (* TODO: needed? *)
  1758. (* push R0-R11, FP and LR *)
  1759. Emit2WithFlags(opSTM, opSP, InstructionSet.NewRegisterList(0, {InstructionSet.FP, InstructionSet.LR, 0..11}), {InstructionSet.flagDB, InstructionSet.flagBaseRegisterUpdate});
  1760. Emit2(opMOV, opFP, opSP);
  1761. END;
  1762. stackSize := 0;
  1763. (* allocate space on stack for local variables *)
  1764. allocationSize := LONGINT(irInstruction.op2.intValue);
  1765. Basic.Align(allocationSize, 4); (* 4 byte alignment *)
  1766. AllocateStack(allocationSize, TRUE, backend.initLocals);
  1767. (* allocate space on stack for register spills *)
  1768. spillStackStart := -stackSize;
  1769. IF spillStack.MaxSize() > 0 THEN AllocateStack(spillStack.MaxSize(), TRUE, FALSE) END
  1770. END EmitEnter;
  1771. (* leave <callingConvention> *)
  1772. PROCEDURE EmitLeave(CONST irInstruction: IntermediateCode.Instruction);
  1773. BEGIN
  1774. (* LDMFD (Full Descending) aka LDMIA (Increment After) *)
  1775. IF (irInstruction.op1.intValue = SyntaxTree.InterruptCallingConvention) THEN
  1776. (* pop R0-R11, FP and LR *)
  1777. Emit2(opMOV, opSP, opFP);
  1778. Emit2WithFlags(opLDM, opSP, InstructionSet.NewRegisterList(0, {InstructionSet.FP, InstructionSet.LR, 0..11}), {InstructionSet.flagIA, InstructionSet.flagBaseRegisterUpdate})
  1779. END
  1780. END EmitLeave;
  1781. (* exit <parSize>, <pcOffset> *)
  1782. PROCEDURE EmitExit(CONST irInstruction: IntermediateCode.Instruction);
  1783. BEGIN
  1784. Emit2(opLDR, opLR, InstructionSet.NewImmediateOffsetMemory(InstructionSet.SP, 4, {InstructionSet.Increment, InstructionSet.PostIndexed}));
  1785. IF (irInstruction.op1.intValue = 0) & (irInstruction.op2.intValue # SyntaxTree.InterruptCallingConvention) THEN
  1786. (* Emit2(opMOV, opPC, opLR) *)
  1787. Emit1(opBX, opLR) (* recommended for better interoperability between ARM and Thumb *)
  1788. ELSE
  1789. IF (irInstruction.op2.intValue = SyntaxTree.InterruptCallingConvention) THEN
  1790. Emit3WithFlags(opSUB, opPC, opLR, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue)),{InstructionSet.flagS})
  1791. ELSE
  1792. (* exit from an ARM interrupt procedure that has a PC offset *)
  1793. Emit3(opSUB, opPC, opLR, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue)))
  1794. END;
  1795. END
  1796. END EmitExit;
  1797. PROCEDURE EmitMov(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1798. VAR
  1799. destinationRegister, sourceOperand: Operand;
  1800. BEGIN
  1801. IF irInstruction.op1.mode # IntermediateCode.ModeRegister THEN
  1802. (* optimization: mov [?], r? it is more optimal to determine the source operand first *)
  1803. sourceOperand := RegisterOrImmediateFromIrOperand(irInstruction.op2, part, emptyOperand);
  1804. destinationRegister := GetFreeRegisterOrHint(PartType(irInstruction.op2.type, part), sourceOperand) (* note that the source operand (possibly a register) is used as hint *)
  1805. ELSE
  1806. PrepareSingleSourceOpWithImmediate(irInstruction, part, destinationRegister, sourceOperand);
  1807. END;
  1808. MovIfDifferent(destinationRegister, sourceOperand);
  1809. WriteBack(irInstruction.op1, part, destinationRegister)
  1810. END EmitMov;
  1811. (* BITWISE LOGICAL OPERATIONS *)
  1812. PROCEDURE EmitNot(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1813. VAR
  1814. destination, source: Operand;
  1815. BEGIN
  1816. PrepareSingleSourceOpWithImmediate(irInstruction, part, destination, source);
  1817. Emit2(opMVN, destination, source); (* invert bits *)
  1818. WriteBack(irInstruction.op1, part, destination)
  1819. END EmitNot;
  1820. PROCEDURE EmitAnd(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1821. VAR
  1822. dummy: BOOLEAN;
  1823. destination, left, right: Operand;
  1824. BEGIN
  1825. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1826. Emit3(opAND, destination, left, right);
  1827. WriteBack(irInstruction.op1, part, destination)
  1828. END EmitAnd;
  1829. PROCEDURE EmitOr(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1830. VAR
  1831. dummy: BOOLEAN;
  1832. destination, left, right: Operand;
  1833. BEGIN
  1834. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1835. Emit3(opORR, destination, left, right);
  1836. WriteBack(irInstruction.op1, part, destination)
  1837. END EmitOr;
  1838. PROCEDURE EmitXor(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  1839. VAR
  1840. dummy: BOOLEAN;
  1841. destination, left, right: Operand;
  1842. BEGIN
  1843. PrepareDoubleSourceOpWithImmediate(irInstruction, part, destination, left, right, dummy);
  1844. Emit3(opEOR, destination, left, right);
  1845. WriteBack(irInstruction.op1, part, destination)
  1846. END EmitXor;
  1847. (* ARITHMETIC OPERATIONS *)
  1848. (*
  1849. - TODO: double precision floats
  1850. - note that for operand sizes 8 and 16, the unused bits of the result might be in a unpredictable state (sign/zero-extension is not done on purpose)
  1851. *)
  1852. PROCEDURE EmitAddOrSub(VAR irInstruction: IntermediateCode.Instruction);
  1853. VAR
  1854. destination, left, right: Operand;
  1855. (* registerSR0, registerSR1, registerSR2: Operand; *)
  1856. BEGIN
  1857. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1858. ASSERT(backend.useFPU32);
  1859. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  1860. IF irInstruction.opcode = IntermediateCode.add THEN
  1861. Emit3(opFADDS, destination, left, right)
  1862. ELSE
  1863. Emit3(opFSUBS, destination, left, right)
  1864. END;
  1865. WriteBack(irInstruction.op1, Low, destination)
  1866. ELSIF IsDoublePrecisionFloat(irInstruction.op1) THEN
  1867. ASSERT(backend.useFPU32);
  1868. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  1869. IF irInstruction.opcode = IntermediateCode.add THEN
  1870. Emit3(opFADDD, destination, left, right)
  1871. ELSE
  1872. Emit3(opFSUBD, destination, left, right)
  1873. END;
  1874. WriteBack(irInstruction.op1, Low, destination)
  1875. ELSIF IsInteger(irInstruction.op1) THEN
  1876. IF IsComplex(irInstruction.op1) THEN
  1877. EmitPartialAddOrSub(irInstruction, Low, TRUE);
  1878. EmitPartialAddOrSub(irInstruction, High, FALSE)
  1879. ELSE
  1880. EmitPartialAddOrSub(irInstruction, Low, FALSE)
  1881. END
  1882. ELSE
  1883. HALT(200)
  1884. END
  1885. END EmitAddOrSub;
  1886. PROCEDURE EmitPartialAddOrSub(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; doUpdateFlags: BOOLEAN);
  1887. VAR
  1888. destination, left, right, hint: Operand;
  1889. irDestination, irLeft, irRight: IntermediateCode.Operand;
  1890. operation: LONGINT;
  1891. doSwap, doNegateRight: BOOLEAN;
  1892. BEGIN
  1893. irDestination := irInstruction.op1; irLeft := irInstruction.op2; irRight := irInstruction.op3;
  1894. doSwap := FALSE; doNegateRight := FALSE; (* defaults *)
  1895. IF irInstruction.opcode = IntermediateCode.add THEN
  1896. IF IrOperandIsDirectlyEncodable(irRight, part) THEN
  1897. (* add r0, r1, 16 ~> ADD R0, R1, #16 *)
  1898. operation := opADD
  1899. ELSIF IrOperandIsDirectlyEncodable(irLeft, part) THEN
  1900. (* add r0, 16, r1 ~> ADD R0, R1, #16 *)
  1901. operation := opADD; doSwap := TRUE
  1902. ELSIF NegatedIrOperandIsDirectlyEncodable(irRight, part) THEN
  1903. (* add r0, r1, -16 ~> SUB R0, R1, #16 *)
  1904. operation := opSUB; doNegateRight := TRUE
  1905. ELSIF NegatedIrOperandIsDirectlyEncodable(irLeft, part) THEN
  1906. (* add r0, -16, r1 ~> SUB R0, R1, #16 *)
  1907. operation := opSUB; doSwap := TRUE; doNegateRight := TRUE
  1908. ELSE
  1909. operation := opADD
  1910. END
  1911. ELSIF irInstruction.opcode = IntermediateCode.sub THEN
  1912. IF IrOperandIsDirectlyEncodable(irRight, part) THEN
  1913. (* sub r0, r1, 16 ~> SUB R0, R1, #16 *)
  1914. operation := opSUB
  1915. ELSIF IrOperandIsDirectlyEncodable(irLeft, part) THEN
  1916. (* sub r0, 16, r1 ~> RSB R0, R1, #16 *)
  1917. operation := opRSB; doSwap := TRUE
  1918. ELSIF NegatedIrOperandIsDirectlyEncodable(irRight, part) THEN
  1919. (* sub r0, r1, -16 ~> ADD R0, R1, #16 *)
  1920. operation := opADD; doNegateRight := TRUE
  1921. ELSE
  1922. operation := opSUB
  1923. END
  1924. ELSE
  1925. HALT(100)
  1926. END;
  1927. (* get destination operand *)
  1928. destination := AcquireDestinationRegister(irDestination, part, emptyOperand);
  1929. (* get source operands *)
  1930. IF doSwap THEN SwapIrOperands(irLeft, irRight) END; (* if needed, swap operands *)
  1931. (* TODO: revise this! *)
  1932. IF IsSameRegister(right, destination) THEN hint := destination ELSE hint := emptyOperand END;
  1933. left := RegisterFromIrOperand(irLeft, part, hint);
  1934. IF doNegateRight THEN
  1935. ASSERT(NegatedIrOperandIsDirectlyEncodable(irRight, part));
  1936. right := InstructionSet.NewImmediate(-ValueOfPart(irRight.intValue, part))
  1937. ELSE
  1938. right := RegisterOrImmediateFromIrOperand(irRight, part, emptyOperand)
  1939. END;
  1940. (* if needed, use operation that incorporates carry *)
  1941. IF part # Low THEN
  1942. CASE operation OF
  1943. | opADD: operation := opADC
  1944. | opSUB: operation := opSBC
  1945. | opRSB: operation := opRSC
  1946. ELSE HALT(100)
  1947. END
  1948. END;
  1949. IF doUpdateFlags THEN
  1950. Emit3WithFlags(operation, destination, left, right, {InstructionSet.flagS})
  1951. ELSE
  1952. Emit3(operation, destination, left, right)
  1953. END;
  1954. WriteBack(irDestination, part, destination)
  1955. END EmitPartialAddOrSub;
  1956. PROCEDURE EmitMul(VAR irInstruction: IntermediateCode.Instruction);
  1957. VAR
  1958. destination, left, right: ARRAY 2 OF Operand;
  1959. BEGIN
  1960. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  1961. ASSERT(backend.useFPU32);
  1962. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1963. Emit3(opFMULS, destination[Low], left[Low], right[Low]);
  1964. WriteBack(irInstruction.op1, Low, destination[Low])
  1965. ELSIF IsDoublePrecisionFloat(irInstruction.op1) THEN
  1966. ASSERT(backend.useFPU64);
  1967. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1968. Emit3(opFMULD, destination[Low], left[Low], right[Low]);
  1969. WriteBack(irInstruction.op1, Low, destination[Low])
  1970. ELSIF IsInteger(irInstruction.op1) THEN
  1971. IF IsComplex(irInstruction.op1) THEN
  1972. ASSERT(irInstruction.op1.type.form = IntermediateCode.SignedInteger);
  1973. HALT(200);
  1974. (* TODO: fix signed 64 bit integer multiplication:
  1975. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1976. PrepareDoubleSourceOp(irInstruction, High, destination[High], left[High], right[High]);
  1977. Emit4(opSMULL, destination[Low], destination[High], left[Low], right[Low]); (* signed long multiplication *)
  1978. Emit3(opMLA, destination[High], left[Low], right[High]); (* multiply and accumulate *)
  1979. Emit3(opMLA, destination[High], left[High], right[Low]);
  1980. WriteBack(irInstruction.op1, Low, destination[Low]);
  1981. WriteBack(irInstruction.op1, High, destination[High]);
  1982. *)
  1983. ELSE
  1984. (* signed or unsigned integer multiplication: *)
  1985. PrepareDoubleSourceOp(irInstruction, Low, destination[Low], left[Low], right[Low]);
  1986. SignOrZeroExtendOperand(left[Low], irInstruction.op2.type);
  1987. SignOrZeroExtendOperand(right[Low], irInstruction.op3.type);
  1988. Emit3(opMUL, destination[Low], left[Low], right[Low]); (* note that the sign does not matter for the least 32 significant bits *)
  1989. WriteBack(irInstruction.op1, Low, destination[Low])
  1990. END
  1991. ELSE
  1992. HALT(200)
  1993. END
  1994. END EmitMul;
  1995. PROCEDURE EmitDiv(VAR irInstruction: IntermediateCode.Instruction);
  1996. VAR
  1997. destination, left, right, float, leftd, rightd, fpstatus: Operand;
  1998. BEGIN
  1999. IF IsSinglePrecisionFloat(irInstruction.op1) THEN
  2000. ASSERT(backend.useFPU32);
  2001. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  2002. Emit3(opFDIVS, destination, left, right);
  2003. WriteBack(irInstruction.op1, Low, destination)
  2004. ELSIF IsDoublePrecisionFloat(irInstruction.op1) THEN
  2005. ASSERT(backend.useFPU64);
  2006. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  2007. Emit3(opFDIVD, destination, left, right);
  2008. WriteBack(irInstruction.op1, Low, destination)
  2009. ELSIF IsNonComplexInteger(irInstruction.op1) THEN
  2010. ASSERT(backend.useFPU64);
  2011. PrepareDoubleSourceOp(irInstruction, Low, destination, left, right);
  2012. (* left and right operands to double *)
  2013. float := GetFreeRegister(IntermediateCode.FloatType(32));
  2014. Emit2(opFMSR, float, left);
  2015. leftd := GetFreeRegister(IntermediateCode.FloatType(64));
  2016. IF irInstruction.op1.type.form = IntermediateCode.UnsignedInteger THEN
  2017. Emit2(opFUITOD, leftd, float)
  2018. ELSE
  2019. Emit2(opFSITOD,leftd, float)
  2020. END;
  2021. Emit2(opFMSR, float,right);
  2022. rightd := GetFreeRegister(IntermediateCode.FloatType(64));
  2023. IF irInstruction.op1.type.form = IntermediateCode.UnsignedInteger THEN
  2024. Emit2(opFUITOD, rightd, float)
  2025. ELSE
  2026. Emit2(opFSITOD,rightd, float)
  2027. END;
  2028. (* div *)
  2029. Emit3(opFDIVD, leftd, leftd, rightd);
  2030. (* result to destination *)
  2031. RoundDown(fpstatus);
  2032. IF irInstruction.op1.type.form = IntermediateCode.UnsignedInteger THEN
  2033. Emit2(opFTOUID, float, leftd)
  2034. ELSE
  2035. Emit2(opFTOSID, float, leftd)
  2036. END;
  2037. ResetRounding(fpstatus);
  2038. Emit2(opFMRS, destination, float);
  2039. WriteBack(irInstruction.op1, Low, destination)
  2040. ELSE
  2041. HALT(200)
  2042. END
  2043. END EmitDiv;
  2044. PROCEDURE EmitMod(CONST irInstruction: IntermediateCode.Instruction);
  2045. BEGIN HALT(100) (* handled by a runtime call *)
  2046. END EmitMod;
  2047. PROCEDURE EmitAbs(VAR irInstruction: IntermediateCode.Instruction);
  2048. VAR
  2049. destination, source: ARRAY 2 OF Operand;
  2050. zero: Operand;
  2051. BEGIN
  2052. IF IsInteger(irInstruction.op1) THEN
  2053. zero := InstructionSet.NewImmediate(0);
  2054. IF IsComplex(irInstruction.op1) THEN
  2055. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  2056. PrepareSingleSourceOpWithImmediate(irInstruction, High, destination[High], source[High]);
  2057. MovIfDifferent(destination[Low], source[Low]);
  2058. MovIfDifferent(destination[High], source[High]);
  2059. (* negate the value if it is negative *)
  2060. IF irInstruction.op2.type.form = IntermediateCode.SignedInteger THEN
  2061. Emit2(opCMP, destination[High], zero); (* note that only the high part has to be looked at to determine the sign *)
  2062. Emit1WithCondition(opB, InstructionSet.NewImmediate(4), InstructionSet.conditionGE); (* BGE #4 = skip the following two instructions if greater or equal *)
  2063. Emit3WithFlags(opRSB, destination[Low], destination[Low], zero, {InstructionSet.flagS}); (* RSBS *)
  2064. Emit3(opRSC, destination[High], destination[High], zero); (* RSC - reverse subtraction with carry *)
  2065. END;
  2066. WriteBack(irInstruction.op1, Low, destination[Low]);
  2067. WriteBack(irInstruction.op1, High, destination[High])
  2068. ELSE
  2069. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  2070. SignOrZeroExtendOperand(source[Low], irInstruction.op2.type);
  2071. MovIfDifferent(destination[Low], source[Low]);
  2072. (* negate the value if it is negative *)
  2073. IF irInstruction.op2.type.form = IntermediateCode.SignedInteger THEN
  2074. SignExtendOperand(destination[Low], irInstruction.op2.type.sizeInBits);
  2075. Emit2(opCMP, destination[Low], zero);
  2076. Emit3WithCondition(opRSB, destination[Low], destination[Low], zero, InstructionSet.conditionLT)
  2077. END;
  2078. WriteBack(irInstruction.op1, Low, destination[Low])
  2079. END
  2080. ELSIF IsSinglePrecisionFloat(irInstruction.op1) THEN
  2081. ASSERT(backend.useFPU32);
  2082. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  2083. Emit2(opFABSS, destination[Low], source[Low]);
  2084. WriteBack(irInstruction.op1, Low, destination[Low])
  2085. ELSIF IsDoublePrecisionFloat(irInstruction.op1) THEN
  2086. ASSERT(backend.useFPU64);
  2087. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  2088. Emit2(opFABSD, destination[Low], source[Low]);
  2089. WriteBack(irInstruction.op1, Low, destination[Low])
  2090. ELSE
  2091. HALT(200)
  2092. END
  2093. END EmitAbs;
  2094. (* TODO: floats *)
  2095. PROCEDURE EmitNeg(VAR irInstruction: IntermediateCode.Instruction);
  2096. VAR
  2097. destination, source: ARRAY 2 OF Operand;
  2098. zero: Operand;
  2099. BEGIN
  2100. IF IsInteger(irInstruction.op1) THEN
  2101. zero := InstructionSet.NewImmediate(0);
  2102. IF IsComplex(irInstruction.op1) THEN
  2103. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  2104. PrepareSingleSourceOpWithImmediate(irInstruction, High, destination[High], source[High]);
  2105. Emit3WithFlags(opRSB, destination[Low], source[Low], zero, {InstructionSet.flagS}); (* RSBS *)
  2106. Emit3(opRSC, destination[High], source[High], zero); (* RSC - reverse subtraction with carry *)
  2107. WriteBack(irInstruction.op1, Low, destination[Low]);
  2108. WriteBack(irInstruction.op1, High, destination[High])
  2109. ELSE
  2110. PrepareSingleSourceOpWithImmediate(irInstruction, Low, destination[Low], source[Low]);
  2111. SignOrZeroExtendOperand(source[Low], irInstruction.op2.type);
  2112. Emit3(opRSB, destination[Low], source[Low], zero); (* reverse subtraction with zero *)
  2113. WriteBack(irInstruction.op1, Low, destination[Low])
  2114. END
  2115. ELSIF IsSinglePrecisionFloat(irInstruction.op1) THEN
  2116. ASSERT(backend.useFPU32);
  2117. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  2118. Emit2(opFNEGS, destination[Low], source[Low]);
  2119. WriteBack(irInstruction.op1, Low, destination[Low])
  2120. ELSIF IsDoublePrecisionFloat(irInstruction.op1) THEN
  2121. ASSERT(backend.useFPU64);
  2122. PrepareSingleSourceOp(irInstruction, Low, destination[Low], source[Low]);
  2123. Emit2(opFNEGD, destination[Low], source[Low]);
  2124. WriteBack(irInstruction.op1, Low, destination[Low])
  2125. ELSE
  2126. HALT(200)
  2127. END
  2128. END EmitNeg;
  2129. (*
  2130. - note that the ARM instructions ASR, LSL, LSR, ROR, etc. are actually aliases for a MOV with a shifted register operand
  2131. - note that ARM does not support LSL by 32 bits
  2132. - note that for operand sizes 8 and 16, the unused bits of the result might be in a unpredictable state (sign/zero-extension is not done on purpose)
  2133. *)
  2134. PROCEDURE EmitShiftOrRotation(VAR irInstruction: IntermediateCode.Instruction);
  2135. VAR
  2136. shiftAmountImmediate, shiftMode: LONGINT;
  2137. destination, source: ARRAY 2 OF Operand;
  2138. irShiftOperand: IntermediateCode.Operand;
  2139. temp, shiftAmountRegister: Operand;
  2140. BEGIN
  2141. ASSERT(IsInteger(irInstruction.op1), 100); (* shifts are only allowed on integers *)
  2142. destination[Low] := AcquireDestinationRegister(irInstruction.op1, Low, emptyOperand);
  2143. source[Low] := RegisterFromIrOperand(irInstruction.op2, Low, emptyOperand); (* note that the destination register cannot be used as hint for the source *)
  2144. IF IsComplex(irInstruction.op1) THEN
  2145. destination[High] := AcquireDestinationRegister(irInstruction.op1, High, emptyOperand);
  2146. source[High] := RegisterFromIrOperand(irInstruction.op2, High, emptyOperand); (* note that the destination register cannot be used as hint for the source *)
  2147. END;
  2148. irShiftOperand := irInstruction.op3;
  2149. ASSERT((irShiftOperand.type.form = IntermediateCode.UnsignedInteger) & ~IsComplex(irShiftOperand)); (* the shift operand is assumed to be a single part unsigned integer *)
  2150. (* use ARM register or shift immediate to represent IR shift operand *)
  2151. IF (irShiftOperand.mode = IntermediateCode.ModeImmediate) & (irShiftOperand.symbol.name = "") THEN
  2152. shiftAmountImmediate := LONGINT(irShiftOperand.intValue); (* note that at this point the shift amount could also be >= 32 *)
  2153. shiftAmountRegister := emptyOperand;
  2154. ASSERT(shiftAmountImmediate >= 0);
  2155. ELSE
  2156. shiftAmountImmediate := 0;
  2157. shiftAmountRegister := RegisterFromIrOperand(irShiftOperand, Low, emptyOperand);
  2158. ZeroExtendOperand(shiftAmountRegister, irShiftOperand.type.sizeInBits)
  2159. END;
  2160. CASE irInstruction.opcode OF
  2161. | IntermediateCode.ror, IntermediateCode.rol:
  2162. (* rotation: *)
  2163. IF IsComplex(irInstruction.op1) THEN HALT(100) END; (* complex rotations are handled as runtime calls *)
  2164. IF irInstruction.opcode = IntermediateCode.rol THEN
  2165. (* simple left rotation: rotate right with complementary rotation amount, since ARM does not support left rotations *)
  2166. IF shiftAmountRegister.register = None THEN
  2167. shiftAmountImmediate := 32 - shiftAmountImmediate
  2168. ELSE
  2169. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  2170. Emit3(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32));
  2171. shiftAmountRegister := temp
  2172. END
  2173. END;
  2174. shiftAmountImmediate := shiftAmountImmediate MOD 32; (* make sure rotation amount is in range 0..31 *)
  2175. IF (shiftAmountRegister.register = None) & (shiftAmountImmediate = 0) THEN
  2176. (* simple rotation by 0: *)
  2177. Emit2(opMOV, destination[Low], source[Low])
  2178. ELSE
  2179. IF irInstruction.op1.type.sizeInBits = 8 THEN
  2180. (* simple 8 bit rotation: *)
  2181. ZeroExtendOperand(source[Low], 8);
  2182. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  2183. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate));
  2184. Emit3(opORR, temp, temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 8));
  2185. Emit3(opORR, temp, temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 16));
  2186. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 24))
  2187. ELSIF irInstruction.op1.type.sizeInBits = 16 THEN
  2188. (* simple 16 bit rotation: *)
  2189. ZeroExtendOperand(source[Low], 16);
  2190. IF IsSameRegister(destination[Low], source[Low]) THEN temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) ELSE temp := destination[Low] END;
  2191. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate));
  2192. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(temp.register, InstructionSet.shiftLSR, None, 16))
  2193. ELSIF irInstruction.op1.type.sizeInBits = 32 THEN
  2194. (* simple 32 bit rotation: *)
  2195. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftROR, shiftAmountRegister.register, shiftAmountImmediate))
  2196. ELSE
  2197. HALT(100)
  2198. END
  2199. END
  2200. | IntermediateCode.shl:
  2201. (* left shift: *)
  2202. IF IsComplex(irInstruction.op1) THEN
  2203. (* complex left shift: *)
  2204. IF shiftAmountRegister.register = None THEN
  2205. (* complex left immediate shift: *)
  2206. IF shiftAmountImmediate = 0 THEN
  2207. Emit2(opMOV, destination[High], source[High]);
  2208. Emit2(opMOV, destination[Low], source[Low])
  2209. ELSIF (shiftAmountImmediate > 0) & (shiftAmountImmediate < 32) THEN
  2210. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2211. Emit2(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, None, 32 - shiftAmountImmediate));
  2212. Emit3(opORR, destination[High], temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, None, shiftAmountImmediate));
  2213. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate))
  2214. ELSIF (shiftAmountImmediate >= 32) & (shiftAmountImmediate < 64) THEN
  2215. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate - 32));
  2216. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  2217. ELSIF shiftAmountImmediate >= 64 THEN
  2218. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  2219. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  2220. ELSE
  2221. HALT(100)
  2222. END
  2223. ELSE
  2224. (* complex left register shift: *)
  2225. IF ~IsSameRegister(destination[Low], source[Low]) THEN temp := destination[Low] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2226. Emit2(opCMP, shiftAmountRegister, InstructionSet.NewImmediate(32));
  2227. (* shiftAmount < 32: *)
  2228. Emit3WithCondition(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionLT);
  2229. Emit2WithCondition(opMOV, temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, temp.register, 0), InstructionSet.conditionLT);
  2230. Emit3WithCondition(opORR, destination[High], temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2231. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2232. (* shift amount >= 32: *)
  2233. Emit3WithCondition(opSUB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionGE);
  2234. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, temp.register, 0), InstructionSet.conditionGE);
  2235. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewImmediate(0), InstructionSet.conditionGE)
  2236. END
  2237. ELSE
  2238. (* simple left shift: *)
  2239. IF shiftAmountRegister.register = None THEN
  2240. (* simple left immediate shift *)
  2241. IF (shiftAmountImmediate >= 0) & (shiftAmountImmediate < 32) THEN
  2242. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, None, shiftAmountImmediate)) (* note: LSL has to be in the range 0..31 *)
  2243. ELSIF shiftAmountImmediate >= 32 THEN
  2244. Emit2(opMOV, destination[Low], InstructionSet.NewImmediate(0))
  2245. ELSE
  2246. HALT(100)
  2247. END
  2248. ELSE
  2249. (* simple left register shift: *)
  2250. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSL, shiftAmountRegister.register, 0))
  2251. END
  2252. END
  2253. | IntermediateCode.shr:
  2254. (* right shift: *)
  2255. (* determine shift mode (depends on if source operand is signed) *)
  2256. IF irInstruction.op1.type.form = IntermediateCode.UnsignedInteger THEN
  2257. (* logical right shift: *)
  2258. shiftMode := InstructionSet.shiftLSR
  2259. ELSE
  2260. (* arithmetic right shift: *)
  2261. shiftMode := InstructionSet.shiftASR
  2262. END;
  2263. IF IsComplex(irInstruction.op1) THEN
  2264. (* complex right shift: *)
  2265. IF shiftAmountRegister.register = None THEN
  2266. (* complex right immediate shift: *)
  2267. IF shiftAmountImmediate = 0 THEN
  2268. Emit2(opMOV, destination[High], source[High]);
  2269. Emit2(opMOV, destination[Low], source[Low])
  2270. ELSIF (shiftAmountImmediate > 0) & (shiftAmountImmediate < 32) THEN
  2271. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2272. Emit2(opMOV, temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, None, 32 - shiftAmountImmediate));
  2273. Emit3(opORR, destination[Low], temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, None, shiftAmountImmediate));
  2274. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, None, shiftAmountImmediate))
  2275. ELSIF shiftAmountImmediate >= 32 THEN
  2276. IF shiftAmountImmediate > 64 THEN shiftAmountImmediate := 64 END;
  2277. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[High].register, shiftMode, None, shiftAmountImmediate - 32));
  2278. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, None, 32))
  2279. ELSE
  2280. HALT(100)
  2281. END
  2282. ELSE
  2283. (* complex right register shift: *)
  2284. IF ~IsSameRegister(destination[High], source[High]) THEN temp := destination[High] ELSE temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)) END;
  2285. Emit2(opCMP, shiftAmountRegister, InstructionSet.NewImmediate(32));
  2286. (* shiftAmount < 32: *)
  2287. Emit3WithCondition(opRSB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionLT);
  2288. Emit2WithCondition(opMOV, temp, InstructionSet.NewRegister(source[High].register, InstructionSet.shiftLSL, temp.register, 0), InstructionSet.conditionLT);
  2289. Emit3WithCondition(opORR, destination[Low], temp, InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftLSR, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2290. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, shiftAmountRegister.register, 0), InstructionSet.conditionLT);
  2291. (* shift amount >= 32: *)
  2292. Emit3WithCondition(opSUB, temp, shiftAmountRegister, InstructionSet.NewImmediate(32), InstructionSet.conditionGE);
  2293. Emit2WithCondition(opMOV, destination[Low], InstructionSet.NewRegister(source[High].register, shiftMode, temp.register, 0), InstructionSet.conditionGE);
  2294. Emit2WithCondition(opMOV, destination[High], InstructionSet.NewRegister(source[High].register, shiftMode, shiftAmountRegister.register, 0), InstructionSet.conditionGE)
  2295. END
  2296. ELSE
  2297. (* simple right shift: *)
  2298. SignOrZeroExtendOperand(source[Low], irInstruction.op1.type);
  2299. IF shiftAmountRegister.register = None THEN
  2300. (* simple right immediate shift: *)
  2301. IF shiftAmountImmediate > 32 THEN shiftAmountImmediate := 32 END;
  2302. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, shiftMode, None, shiftAmountImmediate))
  2303. ELSE
  2304. (* simple right register shift: *)
  2305. Emit2(opMOV, destination[Low], InstructionSet.NewRegister(source[Low].register, shiftMode, shiftAmountRegister.register, 0))
  2306. END
  2307. END
  2308. ELSE
  2309. HALT(100)
  2310. END;
  2311. WriteBack(irInstruction.op1, Low, destination[Low]);
  2312. IF IsComplex(irInstruction.op1) THEN WriteBack(irInstruction.op1, High, destination[High]) END
  2313. END EmitShiftOrRotation;
  2314. PROCEDURE EmitAsm(CONST irInstruction: IntermediateCode.Instruction);
  2315. VAR
  2316. reader: Streams.StringReader;
  2317. procedure: SyntaxTree.Procedure;
  2318. scope: SyntaxTree.Scope;
  2319. symbol: SyntaxTree.Symbol;
  2320. assembler: Assembler.Assembler;
  2321. scanner: Scanner.AssemblerScanner;
  2322. len: LONGINT;
  2323. BEGIN
  2324. len := Strings.Length(irInstruction.op1.string^);
  2325. NEW(reader, len);
  2326. reader.Set(irInstruction.op1.string^);
  2327. (* determine scope of the section *)
  2328. symbol := in.symbol;
  2329. IF symbol = NIL THEN
  2330. scope := NIL
  2331. ELSE
  2332. procedure := symbol(SyntaxTree.Procedure);
  2333. scope := procedure.procedureScope
  2334. END;
  2335. NEW(assembler, diagnostics);
  2336. scanner := Scanner.NewAssemblerScanner(module.moduleName(*module.module.sourceName*), reader, LONGINT(irInstruction.op1.intValue) (* ? *), diagnostics);
  2337. assembler.InlineAssemble(scanner, in, scope, module);
  2338. error := error OR assembler.error
  2339. END EmitAsm;
  2340. PROCEDURE EmitSpecial(VAR instruction: IntermediateCode.Instruction);
  2341. VAR
  2342. psrNumber, code, a, b, c, d: LONGINT;
  2343. register, register2, register3, register4, temp, cpOperand, cpRegister1, cpRegister2, opCode1Operand, opCode2Operand: Operand;
  2344. BEGIN
  2345. CASE instruction.subtype OF
  2346. | GetSP: Emit2(opMOV, opRES, opSP)
  2347. | SetSP: Emit2(opMOV, opSP, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2348. | GetFP: Emit2(opMOV, opRES, opFP)
  2349. | SetFP: Emit2(opMOV, opFP, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2350. | GetLNK: Emit2(opMOV, opRES, opLR)
  2351. | SetLNK: Emit2(opMOV, opLR, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2352. | GetPC: Emit2(opMOV, opRES, opPC)
  2353. | SetPC: Emit2(opMOV, opPC, RegisterOrImmediateFromIrOperand(instruction.op1, Low, emptyOperand))
  2354. | LDPSR, STPSR:
  2355. ASSERT(instruction.op1.type.form IN IntermediateCode.Integer);
  2356. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2357. Error(instruction.textPosition,"first operand must be immediate")
  2358. ELSIF (instruction.op1.intValue < 0) OR (instruction.op1.intValue > 1) THEN
  2359. Error(instruction.textPosition,"first operand must be 0 or 1")
  2360. ELSE
  2361. IF instruction.op1.intValue = 0 THEN
  2362. psrNumber := InstructionSet.CPSR
  2363. ELSE
  2364. psrNumber := InstructionSet.SPSR
  2365. END;
  2366. register := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2367. IF instruction.subtype = LDPSR THEN
  2368. Emit2(opMSR, InstructionSet.NewRegisterWithFields(psrNumber, {InstructionSet.fieldF, InstructionSet.fieldC}), register)
  2369. ELSE
  2370. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2371. Emit2(opMRS, temp, InstructionSet.NewRegister(psrNumber, None, None, 0));
  2372. Emit2(opSTR, temp, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment}))
  2373. END
  2374. END
  2375. | LDCPR, STCPR:
  2376. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2377. Error(instruction.textPosition,"first operand must be immediate")
  2378. ELSIF (instruction.op2.mode # IntermediateCode.ModeImmediate) THEN
  2379. Error(instruction.textPosition,"second operand must be immediate")
  2380. ELSIF (instruction.op2.intValue < 0) OR (instruction.op2.intValue > 15) THEN
  2381. Error(instruction.textPosition,"second operand must be between 0 or 15")
  2382. ELSE
  2383. code := LONGINT(instruction.op1.intValue); (* code = a00bcdH *)
  2384. a := (code DIV 100000H) MOD 10H; (* opcode1 * 2 *)
  2385. b := (code DIV 100H) MOD 10H; (* coprocessor number *)
  2386. c := (code DIV 10H) MOD 10H; (* opcode2 * 2 *)
  2387. d := code MOD 10H; (* coprocessor register2 number *)
  2388. InstructionSet.InitCoprocessor(cpOperand, InstructionSet.CP0 + b);
  2389. InstructionSet.InitOpcode(opCode1Operand, a DIV 2);
  2390. register := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2391. InstructionSet.InitRegister(cpRegister1, InstructionSet.CR0 + LONGINT(instruction.op2.intValue), None, None, 0);
  2392. InstructionSet.InitRegister(cpRegister2, InstructionSet.CR0 + d, None, None, 0);
  2393. InstructionSet.InitOpcode(opCode2Operand, c DIV 2);
  2394. IF instruction.subtype = LDCPR THEN
  2395. Emit6(opMCR, cpOperand, opCode1Operand, register, cpRegister1, cpRegister2, opCode2Operand)
  2396. ELSE
  2397. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2398. Emit6(opMRC, cpOperand, opCode1Operand, temp, cpRegister1, cpRegister2, opCode2Operand);
  2399. Emit2(opSTR, temp, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment}))
  2400. END
  2401. END
  2402. | FLUSH:
  2403. IF instruction.op1.mode # IntermediateCode.ModeImmediate THEN
  2404. Error(instruction.textPosition,"first operand must be immediate")
  2405. ELSIF (instruction.op1.intValue < 0) OR (instruction.op2.intValue > 0FFH) THEN
  2406. Error(instruction.textPosition,"first operand must be between 0 and 255")
  2407. ELSE
  2408. code := LONGINT(instruction.op1.intValue); (* code = aaa1bbbbB *)
  2409. a := (code DIV 20H) MOD 8; (* coprocessor opcode 2 *)
  2410. b := (code MOD 10H); (* coprocessor register2 number *)
  2411. (* examples:
  2412. 9AH = 10011000B -> MCR p15, 0, R0, c7, c10, 4
  2413. 17H = 00010111B -> MCR p15, 0, R0, c7, c7, 0
  2414. *)
  2415. InstructionSet.InitCoprocessor(cpOperand, InstructionSet.CP15);
  2416. InstructionSet.InitOpcode(opCode1Operand, 0);
  2417. InstructionSet.InitRegister(register, InstructionSet.R0, None, None, 0);
  2418. InstructionSet.InitRegister(cpRegister1, InstructionSet.CR7, None, None, 0);
  2419. InstructionSet.InitRegister(cpRegister2, InstructionSet.CR0 + b, None, None, 0);
  2420. InstructionSet.InitOpcode(opCode2Operand, a);
  2421. Emit6(opMCR, cpOperand, opCode1Operand, register, cpRegister1, cpRegister2, opCode2Operand);
  2422. Emit2(opMOV, register, register); (* NOP (register = R0) *)
  2423. Emit2(opMOV, register, register); (* NOP *)
  2424. Emit2(opMOV, register, register); (* NOP *)
  2425. Emit2(opMOV, register, register) (* NOP *)
  2426. END
  2427. | NULL:
  2428. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2429. Emit3(opBIC, register, register, InstructionSet.NewImmediate(LONGINT(80000000H)));
  2430. Emit2(opCMP, register, InstructionSet.NewImmediate(0));
  2431. Emit2WithCondition(opMOV, opRES, InstructionSet.NewImmediate(1), InstructionSet.conditionEQ);
  2432. Emit2WithCondition(opMOV, opRES, InstructionSet.NewImmediate(0), InstructionSet.conditionNE);
  2433. | XOR:
  2434. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2435. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2436. (*
  2437. register3 := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2438. *)
  2439. Emit3(opEOR, opRES, register, register2);
  2440. | MULD:
  2441. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* note that 'register' contains an address *)
  2442. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2443. register3 := RegisterFromIrOperand(instruction.op3, Low, emptyOperand);
  2444. Emit4(opUMULL, opRES, opRESHI, register2, register3);
  2445. Emit2(opSTR, opRES, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* JCH: 15.05.2012 *)
  2446. Emit2(opSTR, opRESHI, InstructionSet.NewImmediateOffsetMemory(register.register, 4, {InstructionSet.Increment}))
  2447. | ADDC:
  2448. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand);
  2449. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand);
  2450. Emit3(opADC, opRES, register, register2)
  2451. | PACK:
  2452. (* PACK(x, y):
  2453. add y to the binary exponent of y. PACK(x, y) is equivalent to x := x * 2^y. *)
  2454. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* register = address of x *)
  2455. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand); (* register2 = value of y *)
  2456. register3 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)); (* a temporary INTEGER (!) register that is used to store a float *)
  2457. Emit2(opLDR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* register3 = value of x *)
  2458. Emit3(opADD, register3, register3, InstructionSet.NewRegister(register2.register, InstructionSet.shiftLSL, None, 23)); (* increase the (biased) exponent of x by y*)
  2459. Emit2(opSTR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})) (* store new value of x *)
  2460. | UNPK:
  2461. (* UNPK(x, y):
  2462. remove the binary exponent on x and put it into y. UNPK is the reverse operation of PACK. The resulting x is normalized, i.e. 1.0 <= x < 2.0.
  2463. *)
  2464. register := RegisterFromIrOperand(instruction.op1, Low, emptyOperand); (* register = address of x *)
  2465. register2 := RegisterFromIrOperand(instruction.op2, Low, emptyOperand); (* register2 = address of y *)
  2466. register3 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32)); (* a temporary INTEGER (!) register that is used to store a float *)
  2467. Emit2(opLDR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})); (* register3 = value of x *)
  2468. register4 := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2469. Emit2(opMOV, register4, InstructionSet.NewRegister(register3.register, InstructionSet.shiftLSR, None, 23)); (* register4 = biased exponent (and sign) of x *)
  2470. Emit3(opSUB, register4, register4, InstructionSet.NewImmediate(127)); (* register4 = exponent of x (biased exponent - 127) *)
  2471. Emit2(opSTR, register4, InstructionSet.NewImmediateOffsetMemory(register2.register, 0, {InstructionSet.Increment})); (* store exponent of x as value for y *)
  2472. Emit3(opSUB, register3, register3, InstructionSet.NewRegister(register4.register, InstructionSet.shiftLSL, None, 23)); (* reduce the biased exponent of x by the value of y *)
  2473. Emit2(opSTR, register3, InstructionSet.NewImmediateOffsetMemory(register.register, 0, {InstructionSet.Increment})) (* store new value of x *)
  2474. ELSE
  2475. HALT(100)
  2476. END
  2477. END EmitSpecial;
  2478. PROCEDURE EmitBr(VAR irInstruction: IntermediateCode.Instruction);
  2479. VAR
  2480. branchDistance: LONGINT;
  2481. isSwapped: BOOLEAN;
  2482. left, right: ARRAY 2 OF Operand;
  2483. temp: Operand;
  2484. irLeft, irRight: IntermediateCode.Operand;
  2485. fixup,failFixup: BinaryCode.Fixup;
  2486. fixupPatternList: ObjectFile.FixupPatterns;
  2487. identifier: ObjectFile.Identifier;
  2488. hiHit, hiFail, lowHit: LONGINT;
  2489. PROCEDURE JmpDest(branchConditionCode: LONGINT);
  2490. BEGIN
  2491. IF (irInstruction.op1.mode = IntermediateCode.ModeImmediate) & (irInstruction.op1.symbol.name = in.name) & (irInstruction.op1.offset = 0) THEN
  2492. (* branch within same section at a certain IR offset *)
  2493. (* optimization: abort if branch is to the next instruction *)
  2494. IF irInstruction.op1.symbolOffset = inPC + 1 THEN
  2495. IF dump # NIL THEN dump.String("branch to next instruction ignored"); dump.Ln END;
  2496. RETURN
  2497. END;
  2498. IF irInstruction.op1.symbolOffset <= inPC THEN
  2499. (* backward branch: calculate the branch distance *)
  2500. branchDistance := in.instructions[irInstruction.op1.symbolOffset].pc - out.pc - 8;
  2501. ASSERT((-33554432 <= branchDistance) & (branchDistance <= 0) & ((ABS(branchDistance) MOD 4) = 0), 200);
  2502. ELSE
  2503. (* forward branch: the distance is not yet known, use some placeholder and add a relative fixup *)
  2504. branchDistance := -4;
  2505. (* TODO: what about a branch to the next instruction? this would require the fixup meachnism to patch a negative value! (-> -4) *)
  2506. NEW(fixupPatternList, 1);
  2507. fixupPatternList[0].offset := 0;
  2508. fixupPatternList[0].bits := 24;
  2509. identifier.name := in.name;
  2510. identifier.fingerprint := in.fingerprint;
  2511. fixup := BinaryCode.NewFixup(BinaryCode.Relative, out.pc, identifier, irInstruction.op1.symbolOffset, -8, -2, fixupPatternList);
  2512. out.fixupList.AddFixup(fixup)
  2513. END;
  2514. Emit1WithCondition(opB, InstructionSet.NewImmediate(branchDistance), branchConditionCode)
  2515. ELSE
  2516. (* any other type of branch -> do register branch *)
  2517. Emit1WithCondition(opBX, RegisterFromIrOperand(irInstruction.op1, Low, emptyOperand), branchConditionCode)
  2518. END;
  2519. END JmpDest;
  2520. PROCEDURE Cmp(CONST left, right: InstructionSet.Operand; float: BOOLEAN);
  2521. BEGIN
  2522. IF float THEN
  2523. IF ~backend.useFPU32 (* NO FPU *) OR IsComplex(irLeft) (* 64 bit but not DP FPU *) THEN
  2524. (* floating point comparisons without VFP unit *)
  2525. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2526. Emit3WithFlags(opAND, temp, left, right, {InstructionSet.flagS});
  2527. Emit2(opCMP, temp, InstructionSet.NewImmediate(0));
  2528. Emit1WithCondition(opB, InstructionSet.NewImmediate(4), InstructionSet.conditionLT); (* skip two instructions *)
  2529. Emit2(opCMP, left, right);
  2530. Emit1(opB, InstructionSet.NewImmediate(0)); (* skip one instructions *)
  2531. Emit2(opCMP, right, left);
  2532. ELSIF IsSinglePrecisionFloat(irLeft) THEN
  2533. Emit2(opFCMPS, left, right);
  2534. Emit0(opFMSTAT); (* transfer the VFP flags to the standard ARM flags *)
  2535. ELSIF IsDoublePrecisionFloat(irLeft) THEN
  2536. Emit2(opFCMPD, left, right);
  2537. Emit0(opFMSTAT); (* transfer the VFP flags to the standard ARM flags *)
  2538. END
  2539. ELSE
  2540. Emit2(opCMP, left, right);
  2541. END;
  2542. END Cmp;
  2543. BEGIN
  2544. hiFail := None;
  2545. hiHit := None;
  2546. IF irInstruction.opcode = IntermediateCode.br THEN
  2547. (* unconditional branch: *)
  2548. lowHit := InstructionSet.conditionAL
  2549. ELSE
  2550. (* conditional branch: *)
  2551. irLeft := irInstruction.op2; irRight := irInstruction.op3;
  2552. ASSERT((irLeft.type.form = irRight.type.form) & (irLeft.type.sizeInBits = irRight.type.sizeInBits));
  2553. IF IsInteger(irLeft) THEN
  2554. IF IsComplex(irLeft) THEN
  2555. CASE irInstruction.opcode OF
  2556. | IntermediateCode.breq, IntermediateCode.brne: (* left = right, left # right *)
  2557. lowHit := InstructionSet.conditionEQ;
  2558. left[High] := RegisterFromIrOperand(irLeft, High, emptyOperand);
  2559. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, emptyOperand);
  2560. Emit2(opCMP, left[High], right[High]);
  2561. left[Low] := RegisterFromIrOperand(irLeft, Low, left[High]);
  2562. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, right[High]);
  2563. Emit2WithCondition(opCMP, left[Low], right[Low], lowHit);
  2564. IF irInstruction.opcode = IntermediateCode.brne THEN lowHit := InstructionSet.conditionNE END;
  2565. | IntermediateCode.brlt, IntermediateCode.brge: (* left < right, left >= right *)
  2566. IF irInstruction.opcode = IntermediateCode.brlt THEN lowHit := InstructionSet.conditionLT ELSE lowHit := InstructionSet.conditionGE END;
  2567. ASSERT(irLeft.type.form = IntermediateCode.SignedInteger);
  2568. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2569. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, emptyOperand);
  2570. temp := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2571. Emit3WithFlags(opSUB, temp, left[Low], right[Low], {InstructionSet.flagS});
  2572. left[High] := RegisterFromIrOperand(irLeft, High, left[Low]);
  2573. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, right[Low]);
  2574. Emit3WithFlags(opSBC, temp, left[High], right[High], {InstructionSet.flagS}) (* the high part of the subtraction determines the sign *)
  2575. ELSE
  2576. HALT(100)
  2577. END
  2578. ELSE
  2579. ASSERT((irLeft.type.form IN IntermediateCode.Integer) & (irLeft.type.sizeInBits <= 32));
  2580. (* swap operands if beneficial *)
  2581. IF ~IrOperandIsDirectlyEncodable(irRight, Low) & IrOperandIsDirectlyEncodable(irLeft, Low) THEN
  2582. isSwapped := TRUE;
  2583. SwapIrOperands(irLeft, irRight)
  2584. END;
  2585. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2586. right[Low] := RegisterOrImmediateFromIrOperand(irRight, Low, emptyOperand);
  2587. SignOrZeroExtendOperand(left[Low], irLeft.type);
  2588. SignOrZeroExtendOperand(right[Low], irRight.type);
  2589. Cmp(left[Low], right[Low], FALSE);
  2590. (* determine condition code for the branch (take into consideration that operands could have been swapped) *)
  2591. CASE irInstruction.opcode OF
  2592. | IntermediateCode.breq: (* left = right *) lowHit := InstructionSet.conditionEQ
  2593. | IntermediateCode.brne: (* left # right *) lowHit := InstructionSet.conditionNE
  2594. | IntermediateCode.brlt: (* left < right *)
  2595. IF irInstruction.op2.type.form = IntermediateCode.UnsignedInteger THEN
  2596. IF isSwapped THEN lowHit := InstructionSet.conditionHI ELSE lowHit := InstructionSet.conditionLO END
  2597. ELSE
  2598. IF isSwapped THEN lowHit := InstructionSet.conditionGT ELSE lowHit := InstructionSet.conditionLT END
  2599. END
  2600. | IntermediateCode.brge: (* left >= right *)
  2601. IF irInstruction.op2.type.form = IntermediateCode.UnsignedInteger THEN
  2602. IF isSwapped THEN lowHit := InstructionSet.conditionLS ELSE lowHit := InstructionSet.conditionHS END
  2603. ELSE
  2604. IF isSwapped THEN lowHit := InstructionSet.conditionLE ELSE lowHit := InstructionSet.conditionGE END
  2605. END
  2606. ELSE HALT(100)
  2607. END
  2608. END
  2609. ELSIF IsSinglePrecisionFloat(irLeft) OR IsDoublePrecisionFloat(irLeft) & backend.useFPU64 THEN
  2610. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2611. right[Low] := RegisterFromIrOperand(irRight, Low, emptyOperand);
  2612. Cmp(left[Low], right[Low], TRUE);
  2613. CASE irInstruction.opcode OF
  2614. | IntermediateCode.breq: (* left = right *) lowHit := InstructionSet.conditionEQ
  2615. | IntermediateCode.brne: (* left # right *) lowHit := InstructionSet.conditionNE
  2616. | IntermediateCode.brlt: (* left < right *) lowHit := InstructionSet.conditionLT
  2617. | IntermediateCode.brge: (* left >= right *) lowHit := InstructionSet.conditionGE
  2618. ELSE HALT(100)
  2619. END
  2620. ELSIF IsDoublePrecisionFloat(irLeft) THEN
  2621. CASE irInstruction.opcode OF
  2622. IntermediateCode.breq:
  2623. hiHit := None; hiFail := InstructionSet.conditionNE; lowHit := InstructionSet.conditionEQ
  2624. |IntermediateCode.brne:
  2625. hiHit := InstructionSet.conditionNE; hiFail := None; lowHit := InstructionSet.conditionNE
  2626. |IntermediateCode.brge:
  2627. IF isSwapped THEN
  2628. hiHit := InstructionSet.conditionLT; hiFail := InstructionSet.conditionGT; lowHit := InstructionSet.conditionLS
  2629. ELSE
  2630. hiHit := InstructionSet.conditionGT; hiFail := InstructionSet.conditionLT; lowHit := InstructionSet.conditionHS
  2631. END;
  2632. |IntermediateCode.brlt:
  2633. IF isSwapped THEN
  2634. hiHit := InstructionSet.conditionGT; hiFail := InstructionSet.conditionLT; lowHit := InstructionSet.conditionHI
  2635. ELSE
  2636. hiHit := InstructionSet.conditionLT; hiFail := InstructionSet.conditionGT; lowHit := InstructionSet.conditionLO
  2637. END;
  2638. END;
  2639. (*
  2640. compare hi part (as float)
  2641. if hiHit then br dest
  2642. elsif hiFail then br fail
  2643. else compare low part (as unsigned int)
  2644. if lowHit then br dest
  2645. end
  2646. end,
  2647. fail:
  2648. *)
  2649. (* hi part *)
  2650. left[High] := RegisterFromIrOperand(irLeft, High, emptyOperand);
  2651. right[High] := RegisterOrImmediateFromIrOperand(irRight, High, emptyOperand);
  2652. Cmp(left[High], right[High], TRUE);
  2653. IF hiHit # None THEN
  2654. JmpDest(hiHit)
  2655. END;
  2656. IF hiFail # None THEN
  2657. NEW(fixupPatternList, 1);
  2658. fixupPatternList[0].offset := 0;
  2659. fixupPatternList[0].bits := 24;
  2660. identifier.name := in.name;
  2661. identifier.fingerprint := in.fingerprint;
  2662. failFixup := BinaryCode.NewFixup(BinaryCode.Relative, out.pc, identifier, irInstruction.op1.symbolOffset, -8, -2, fixupPatternList);
  2663. out.fixupList.AddFixup(failFixup);
  2664. Emit1WithCondition(opB, InstructionSet.NewImmediate(branchDistance), hiFail)
  2665. END;
  2666. (* low part *)
  2667. left[Low] := RegisterFromIrOperand(irLeft, Low, emptyOperand);
  2668. right[Low] := RegisterFromIrOperand(irRight, Low, emptyOperand);
  2669. Cmp(left[Low], right[Low], FALSE);
  2670. ELSE
  2671. HALT(200)
  2672. END
  2673. END;
  2674. JmpDest(lowHit);
  2675. IF failFixup # NIL THEN
  2676. failFixup.SetSymbol(in.name, in.fingerprint, 0, out.pc+failFixup.displacement (* displacement offset computed during operand emission, typically -1 *) );
  2677. failFixup.resolved := in;
  2678. END;
  2679. END EmitBr;
  2680. PROCEDURE RoundDown(VAR fpstatus: Operand);
  2681. BEGIN
  2682. fpstatus := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2683. (* round to minus infitinity *)
  2684. Emit2(InstructionSet.opVMRS, fpstatus, fpscr);
  2685. Emit3(opORR, fpstatus, fpstatus, InstructionSet.NewImmediate(0x800000));
  2686. Emit2(InstructionSet.opVMSR, fpscr, fpstatus);
  2687. END RoundDown;
  2688. PROCEDURE ResetRounding(VAR fpstatus: Operand);
  2689. BEGIN
  2690. (* reset rounding mode *)
  2691. Emit3(opBIC, fpstatus, fpstatus, InstructionSet.NewImmediate(0x800000));
  2692. Emit2(InstructionSet.opVMSR, fpscr, fpstatus);
  2693. END ResetRounding;
  2694. PROCEDURE EmitConv(VAR irInstruction: IntermediateCode.Instruction);
  2695. VAR
  2696. irDestination, irSource: IntermediateCode.Operand;
  2697. destination, source: ARRAY 2 OF Operand;
  2698. temp, fpstatus: Operand;
  2699. partType: IntermediateCode.Type;
  2700. BEGIN
  2701. irDestination := irInstruction.op1; irSource := irInstruction.op2;
  2702. (* prepare operands *)
  2703. destination[Low] := AcquireDestinationRegister(irDestination, Low, emptyOperand); (* TODO: find more optimal register allocation *)
  2704. source[Low] := RegisterOrImmediateFromIrOperand(irSource, Low, destination[Low]);
  2705. IF IsComplex(irDestination) THEN destination[High]:= AcquireDestinationRegister(irDestination, High, emptyOperand) END;
  2706. IF IsComplex(irSource) THEN source[High] := RegisterOrImmediateFromIrOperand(irSource, High, destination[High]) END; (* note that the corresponding destination register is used as hint *)
  2707. IF IsInteger(irDestination) THEN
  2708. (* to integer: *)
  2709. IF IsComplex(irDestination) THEN
  2710. ASSERT(IsInteger(irDestination));
  2711. (* to complex integer: *)
  2712. IF IsInteger(irSource) THEN
  2713. (* integer to complex integer: *)
  2714. IF IsComplex(irSource) THEN
  2715. (* complex integer to complex integer: *)
  2716. MovIfDifferent(destination[Low], source[Low]);
  2717. MovIfDifferent(destination[High], source[High]);
  2718. ELSE
  2719. (* non-complex integer to complex integer: *)
  2720. SignOrZeroExtendOperand(source[Low], irSource.type);
  2721. MovIfDifferent(destination[Low], source[Low]);
  2722. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2723. Emit2(opMOV, destination[High], InstructionSet.NewImmediate(0));
  2724. ELSE
  2725. (* for signed values the high part is set to 0...0 or 1...1, depending on the sign of the low part *)
  2726. Emit2(opMOV, destination[High], InstructionSet.NewRegister(source[Low].register, InstructionSet.shiftASR, None, 31))
  2727. END
  2728. END
  2729. ELSIF IsFloat(irSource) THEN (* ENTIERH not supported natively *)
  2730. HALT(200);
  2731. ELSE
  2732. HALT(100);
  2733. END;
  2734. ELSE
  2735. (* to non-complex integer: *)
  2736. IF IsInteger(irSource) THEN
  2737. (* integer to non-complex integer *)
  2738. GetPartType(irSource.type, Low, partType);
  2739. SignOrZeroExtendOperand(source[Low], partType);
  2740. MovIfDifferent(destination[Low], source[Low])
  2741. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2742. (* REAL --> INTEGER *)
  2743. ASSERT(backend.useFPU32);
  2744. (* single precision float to non-complex integer: *)
  2745. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2746. RoundDown(fpstatus);
  2747. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2748. (* single precision float to non-complex unsigned integer: *)
  2749. Emit2(opFTOUIS, temp, source[Low]);
  2750. ELSE
  2751. (* single precision float to non-complex signed integer: *)
  2752. Emit2(opFTOSIS, temp, source[Low]);
  2753. END;
  2754. ResetRounding(fpstatus);
  2755. Emit2(opFMRS, destination[Low], temp)
  2756. ELSIF IsDoublePrecisionFloat(irSource) THEN
  2757. (* LONGREAL --> INTEGER *)
  2758. ASSERT(backend.useFPU64);
  2759. (* single precision float to non-complex integer: *)
  2760. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2761. RoundDown(fpstatus);
  2762. IF irDestination.type.form = IntermediateCode.UnsignedInteger THEN
  2763. (* single precision float to non-complex unsigned integer: *)
  2764. Emit2(opFTOUID, temp, source[Low]);
  2765. ELSE
  2766. (* single precision float to non-complex signed integer: *)
  2767. Emit2(opFTOSID, temp, source[Low]);
  2768. END;
  2769. ResetRounding(fpstatus);
  2770. Emit2(opFMRS, destination[Low], temp)
  2771. ELSE
  2772. (* anything to non-complex integer: *)
  2773. HALT(200)
  2774. END
  2775. END
  2776. ELSIF IsSinglePrecisionFloat(irDestination) THEN
  2777. (* to single precision float: *)
  2778. IF IsInteger(irSource) THEN
  2779. ASSERT(~IsComplex(irSource));
  2780. (* integer to single precision float: ignore high part of source *)
  2781. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2782. Emit2(opFMSR, temp, source[Low]);
  2783. IF irSource.type.form = IntermediateCode.UnsignedInteger THEN
  2784. (* non-complex unsigned integer to single precision float: *)
  2785. Emit2(opFUITOS, destination[Low], temp)
  2786. ELSE
  2787. (* non-complex signed integer to single precision float: *)
  2788. Emit2(opFSITOS, destination[Low], temp)
  2789. END
  2790. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2791. (* single precision float to single precision float: *)
  2792. MovIfDifferent(destination[Low], source[Low])
  2793. ELSIF IsDoublePrecisionFloat(irSource) THEN
  2794. (* LONGREAL --> REAL *)
  2795. Emit2(opFCVTSD, destination[Low], source[Low])
  2796. ELSE
  2797. (* anything else to single precision float: *)
  2798. HALT(200)
  2799. END
  2800. ELSIF IsDoublePrecisionFloat(irDestination) THEN
  2801. (* to double precision float: *)
  2802. IF IsInteger(irSource) THEN
  2803. ASSERT(~IsComplex(irSource));
  2804. (* integer to double precision float: ignore high part of source *)
  2805. temp := GetFreeRegister(IntermediateCode.FloatType(32));
  2806. Emit2(opFMSR, temp, source[Low]);
  2807. IF irSource.type.form = IntermediateCode.UnsignedInteger THEN
  2808. (* non-complex unsigned integer to double precision float: *)
  2809. Emit2(opFUITOD, destination[Low], temp)
  2810. ELSE
  2811. (* non-complex signed integer to double precision float: *)
  2812. Emit2(opFSITOD, destination[Low], temp)
  2813. END
  2814. ELSIF IsSinglePrecisionFloat(irSource) THEN
  2815. (* REAL --> LONGREAL *)
  2816. Emit2(opFCVTDS, destination[Low], source[Low])
  2817. ELSIF IsDoublePrecisionFloat(irSource) THEN
  2818. (* single precision float to single precision float: *)
  2819. MovIfDifferent(destination[Low], source[Low])
  2820. ELSE
  2821. (* anything else to single precision float: *)
  2822. HALT(200)
  2823. END
  2824. ELSE
  2825. (* to anything else: *)
  2826. HALT(200)
  2827. END;
  2828. WriteBack(irDestination, Low, destination[Low]);
  2829. IF IsComplex(irDestination) THEN WriteBack(irInstruction.op1, High, destination[High]) END
  2830. END EmitConv;
  2831. (** get the register that is dedicated to store a return value of a function **)
  2832. PROCEDURE ResultRegister(part: LONGINT; type: IntermediateCode.Type): InstructionSet.Operand;
  2833. VAR
  2834. result: Operand;
  2835. BEGIN
  2836. IF (type.form IN IntermediateCode.Integer) THEN
  2837. IF part = Low THEN result := opRES
  2838. ELSIF part = High THEN result := opRESHI
  2839. ELSE HALT(200)
  2840. END
  2841. ELSIF type.form = IntermediateCode.Float THEN
  2842. IF (type.sizeInBits = 32) THEN
  2843. IF backend.useFPU32 THEN
  2844. result := opRESFS
  2845. ELSE
  2846. result := opRES
  2847. END;
  2848. ELSE
  2849. IF backend.useFPU64 THEN
  2850. result := opRESFD
  2851. ELSE
  2852. IF part = Low THEN result := opRES
  2853. ELSIF part = High THEN result := opRESHI
  2854. ELSE HALT(200)
  2855. END
  2856. END;
  2857. END;
  2858. END;
  2859. RETURN result
  2860. END ResultRegister;
  2861. PROCEDURE EmitReturn(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  2862. VAR
  2863. source: Operand;
  2864. BEGIN
  2865. source := RegisterOrImmediateFromIrOperand(irInstruction.op1, part, ResultRegister(part, irInstruction.op1.type)); (* note: the result register is given as a hint *)
  2866. MovIfDifferent(ResultRegister(part, irInstruction.op1.type), source)
  2867. END EmitReturn;
  2868. PROCEDURE EmitResult(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT);
  2869. VAR
  2870. destinationRegister: Operand;
  2871. BEGIN
  2872. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2873. MovIfDifferent(destinationRegister, ResultRegister(part, irInstruction.op1.type));
  2874. WriteBack(irInstruction.op1, part, destinationRegister)
  2875. END EmitResult;
  2876. PROCEDURE EmitTrap(CONST irInstruction: IntermediateCode.Instruction);
  2877. BEGIN
  2878. ASSERT(irInstruction.op1.mode = IntermediateCode.ModeNumber);
  2879. Emit1(opSWI, InstructionSet.NewImmediate(LONGINT(irInstruction.op1.intValue))) (* software interrupt *)
  2880. END EmitTrap;
  2881. PROCEDURE EmitCas(VAR irInstruction: IntermediateCode.Instruction);
  2882. VAR
  2883. addressReg, addressBaseReg, comparandReg, comparandBaseReg, comparatorReg, comparatorBaseReg, tempReg: Operand
  2884. BEGIN
  2885. addressReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2886. addressBaseReg := RegisterFromIrOperand(irInstruction.op1, Low, addressReg);
  2887. MovIfDifferent(addressReg, addressBaseReg);
  2888. IF IntermediateCode.OperandEquals (irInstruction.op2, irInstruction.op3) THEN
  2889. Emit2(opLDR, opRES, InstructionSet.NewImmediateOffsetMemory(addressReg.register, 0, {InstructionSet.Increment}));
  2890. ELSE
  2891. comparandReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2892. comparandBaseReg := RegisterFromIrOperand(irInstruction.op2, Low, comparandReg);
  2893. MovIfDifferent(comparandReg, comparandBaseReg);
  2894. comparatorReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2895. comparatorBaseReg := RegisterFromIrOperand(irInstruction.op3, Low, comparatorReg);
  2896. MovIfDifferent(comparatorReg, comparatorBaseReg);
  2897. Emit2(opLDREX, opRES, addressReg);
  2898. Emit2(opCMP, opRES, comparandReg);
  2899. tempReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2900. Emit3WithCondition(opSTREX, tempReg, comparatorReg, addressReg, InstructionSet.conditionEQ);
  2901. Emit2WithCondition(opCMP, tempReg, InstructionSet.NewImmediate(1), InstructionSet.conditionEQ);
  2902. Emit1WithCondition(opB, InstructionSet.NewImmediate (-24), InstructionSet.conditionEQ);
  2903. END;
  2904. END EmitCas;
  2905. (* possible optimization: use a combination of LDR and LDRB (would be 4x faster on average) *)
  2906. PROCEDURE EmitCopy(VAR irInstruction: IntermediateCode.Instruction);
  2907. VAR
  2908. targetBaseReg, sourceBaseReg, length, lastSourceAddress, currentTargetReg, currentSourceReg, tempReg: Operand;
  2909. BEGIN
  2910. ASSERT((irInstruction.op1.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op1.type.sizeInBits = 32));
  2911. ASSERT((irInstruction.op2.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op2.type.sizeInBits = 32));
  2912. ASSERT((irInstruction.op3.type.form = IntermediateCode.UnsignedInteger) & (irInstruction.op3.type.sizeInBits = 32));
  2913. currentTargetReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2914. currentSourceReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2915. (* note that the registers that store the current addresses are used as hints: *)
  2916. targetBaseReg := RegisterFromIrOperand(irInstruction.op1, Low, currentTargetReg);
  2917. sourceBaseReg := RegisterFromIrOperand(irInstruction.op2, Low, currentSourceReg);
  2918. MovIfDifferent(currentTargetReg, targetBaseReg);
  2919. MovIfDifferent(currentSourceReg, sourceBaseReg);
  2920. lastSourceAddress := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2921. length := RegisterOrImmediateFromIrOperand(irInstruction.op3, Low, lastSourceAddress); (* note that the last source address register is used as hint*)
  2922. Emit3(opADD, lastSourceAddress, sourceBaseReg, length);
  2923. tempReg := GetFreeRegister(IntermediateCode.UnsignedIntegerType(32));
  2924. Emit2WithFlags(opLDR, tempReg, InstructionSet.NewImmediateOffsetMemory(currentSourceReg.register, 1, {InstructionSet.Increment, InstructionSet.PostIndexed}), {InstructionSet.flagB});
  2925. Emit2WithFlags(opSTR, tempReg, InstructionSet.NewImmediateOffsetMemory(currentTargetReg.register, 1, {InstructionSet.Increment, InstructionSet.PostIndexed}), {InstructionSet.flagB});
  2926. Emit2(opCMP, currentSourceReg, lastSourceAddress);
  2927. Emit1WithCondition(opB, InstructionSet.NewImmediate(-20), InstructionSet.conditionLT)
  2928. END EmitCopy;
  2929. PROCEDURE EmitFill(CONST irInstruction: IntermediateCode.Instruction; down: BOOLEAN);
  2930. BEGIN
  2931. HALT(200) (* note that this instruction is not used at the moment *)
  2932. END EmitFill;
  2933. (* PREPARATION OF OPERATIONS *)
  2934. (** swap a pair of IR operands **)
  2935. PROCEDURE SwapIrOperands(VAR left, right: IntermediateCode.Operand);
  2936. VAR
  2937. temp: IntermediateCode.Operand;
  2938. BEGIN
  2939. temp := left;
  2940. left := right;
  2941. right := temp
  2942. END SwapIrOperands;
  2943. PROCEDURE PrepareSingleSourceOp(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, sourceOperand: Operand);
  2944. BEGIN
  2945. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2946. sourceOperand := RegisterFromIrOperand(irInstruction.op2, part, destinationRegister); (* note that the destination register is used as hint *)
  2947. END PrepareSingleSourceOp;
  2948. PROCEDURE PrepareSingleSourceOpWithImmediate(VAR irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, sourceOperand: Operand);
  2949. BEGIN
  2950. destinationRegister := AcquireDestinationRegister(irInstruction.op1, part, emptyOperand);
  2951. sourceOperand := RegisterOrImmediateFromIrOperand(irInstruction.op2, part, destinationRegister); (* note that the destination register is used as hint *)
  2952. END PrepareSingleSourceOpWithImmediate;
  2953. PROCEDURE PrepareDoubleSourceOpWithImmediate(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, leftSourceOperand, rightSourceOperand: Operand; VAR isSwapped: BOOLEAN);
  2954. VAR
  2955. irDestination, irLeft, irRight: IntermediateCode.Operand;
  2956. BEGIN
  2957. irDestination := irInstruction.op1;
  2958. irLeft := irInstruction.op2;
  2959. irRight := irInstruction.op3;
  2960. destinationRegister:= AcquireDestinationRegister(irDestination, part, emptyOperand);
  2961. (* swap operands such that the right one is an immediate *)
  2962. IF IrOperandIsDirectlyEncodable(irLeft, part) & ~IrOperandIsDirectlyEncodable(irRight, part) THEN
  2963. SwapIrOperands(irLeft, irRight);
  2964. isSwapped := TRUE
  2965. ELSIF IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2966. SwapIrOperands(irLeft, irRight);
  2967. isSwapped := TRUE
  2968. ELSE
  2969. isSwapped := FALSE
  2970. END;
  2971. leftSourceOperand := RegisterFromIrOperand(irLeft, part, destinationRegister); (* the destination register is used as hint *)
  2972. IF IsSameRegister(leftSourceOperand, destinationRegister) THEN
  2973. rightSourceOperand := RegisterOrImmediateFromIrOperand(irRight, part, emptyOperand) (* no hint is provided *)
  2974. ELSE
  2975. rightSourceOperand := RegisterOrImmediateFromIrOperand(irRight, part, destinationRegister) (* the destination register is again used as hint *)
  2976. END
  2977. END PrepareDoubleSourceOpWithImmediate;
  2978. PROCEDURE PrepareDoubleSourceOp(CONST irInstruction: IntermediateCode.Instruction; part: LONGINT; VAR destinationRegister, leftSourceOperand, rightSourceOperand: Operand);
  2979. VAR
  2980. irDestination, irLeft, irRight: IntermediateCode.Operand;
  2981. BEGIN
  2982. irDestination := irInstruction.op1;
  2983. irLeft := irInstruction.op2;
  2984. irRight := irInstruction.op3;
  2985. destinationRegister:= AcquireDestinationRegister(irDestination, part, emptyOperand);
  2986. IF IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2987. leftSourceOperand := RegisterFromIrOperand(irLeft, part, emptyOperand); (* do not use destination register as hint *)
  2988. ELSE
  2989. leftSourceOperand := RegisterFromIrOperand(irLeft, part, destinationRegister); (* the destination register is used as hint *)
  2990. END;
  2991. IF IsSameRegister(leftSourceOperand, destinationRegister) OR IntermediateCode.OperandEquals(irRight, irDestination) THEN
  2992. rightSourceOperand := RegisterFromIrOperand(irRight, part, emptyOperand) (* no hint is provided *)
  2993. ELSE
  2994. rightSourceOperand := RegisterFromIrOperand(irRight, part, destinationRegister) (* the destination register is again used as hint *)
  2995. END
  2996. END PrepareDoubleSourceOp;
  2997. END CodeGeneratorARM;
  2998. BackendARM = OBJECT(IntermediateBackend.IntermediateBackend)
  2999. VAR
  3000. cg: CodeGeneratorARM;
  3001. system: Global.System;
  3002. useFPU32: BOOLEAN;
  3003. useFPU64: BOOLEAN;
  3004. initLocals: BOOLEAN;
  3005. PROCEDURE & InitBackendARM;
  3006. BEGIN
  3007. useFPU32 := FALSE;
  3008. useFPU64 := FALSE;
  3009. InitIntermediateBackend;
  3010. SetRuntimeModuleName(DefaultRuntimeModuleName);
  3011. SetNewObjectFile(TRUE,FALSE);
  3012. system := NIL;
  3013. initLocals := TRUE;
  3014. SetHasLinkRegister;
  3015. SetName("ARM");
  3016. END InitBackendARM;
  3017. PROCEDURE Initialize(diagnostics: Diagnostics.Diagnostics; log: Streams.Writer; flags: SET; checker: SemanticChecker.Checker; system: Global.System);
  3018. BEGIN
  3019. Initialize^(diagnostics, log, flags, checker, system);
  3020. NEW(cg, runtimeModuleName, diagnostics, SELF)
  3021. END Initialize;
  3022. PROCEDURE EnterCustomBuiltins;
  3023. VAR
  3024. procedureType: SyntaxTree.ProcedureType;
  3025. parameter: SyntaxTree.Parameter;
  3026. PROCEDURE New;
  3027. BEGIN procedureType := SyntaxTree.NewProcedureType(-1, NIL)
  3028. END New;
  3029. PROCEDURE BoolRet;
  3030. BEGIN procedureType.SetReturnType(system.booleanType)
  3031. END BoolRet;
  3032. PROCEDURE IntRet;
  3033. BEGIN procedureType.SetReturnType(Global.Integer32)
  3034. END IntRet;
  3035. PROCEDURE IntPar;
  3036. BEGIN
  3037. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.ValueParameter);
  3038. parameter.SetType(Global.Integer32); procedureType.AddParameter(parameter)
  3039. END IntPar;
  3040. PROCEDURE AddressPar;
  3041. BEGIN
  3042. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.ValueParameter);
  3043. parameter.SetType(Global.Unsigned32); procedureType.AddParameter(parameter)
  3044. END AddressPar;
  3045. PROCEDURE IntVarPar;
  3046. BEGIN
  3047. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.VarParameter);
  3048. parameter.SetType(Global.Integer32); procedureType.AddParameter(parameter)
  3049. END IntVarPar;
  3050. PROCEDURE RealVarPar;
  3051. BEGIN
  3052. parameter := SyntaxTree.NewParameter(-1, procedureType, SyntaxTree.NewIdentifier(""), SyntaxTree.VarParameter);
  3053. parameter.SetType(Global.Float32); procedureType.AddParameter(parameter)
  3054. END RealVarPar;
  3055. PROCEDURE Finish(CONST name: ARRAY OF CHAR; number: SHORTINT);
  3056. BEGIN Global.NewCustomBuiltin(name, system.systemScope, number, procedureType);
  3057. END Finish;
  3058. BEGIN
  3059. New; IntRet; Finish("SP", GetSP);
  3060. New; AddressPar; Finish("SetSP", SetSP);
  3061. New; IntRet; Finish("FP", GetFP);
  3062. New; AddressPar; Finish("SetFP", SetFP);
  3063. New; IntRet; Finish("PC", GetPC);
  3064. New; AddressPar; Finish("SetPC", SetPC);
  3065. New; IntRet; Finish("LNK", GetLNK);
  3066. New; AddressPar; Finish("SetLNK", SetLNK);
  3067. New; IntPar; IntPar; Finish("LDPSR", LDPSR);
  3068. New; IntPar; IntVarPar; Finish("STPSR", STPSR);
  3069. New; IntPar; IntPar; IntPar; Finish("LDCPR", LDCPR);
  3070. New; IntPar; IntPar; IntVarPar; Finish("STCPR", STCPR);
  3071. New; IntPar; Finish("FLUSH", FLUSH);
  3072. New; BoolRet; IntPar; Finish("NULL", NULL);
  3073. New; IntRet; IntPar; IntPar; Finish("XOR", XOR);
  3074. New; IntVarPar; IntPar; IntPar; Finish("MULD", MULD);
  3075. New; IntVarPar; IntPar; IntPar; Finish("ADDC", ADDC);
  3076. New; RealVarPar; IntPar; Finish("PACK", PACK);
  3077. New; RealVarPar; IntVarPar; Finish("UNPK", UNPK);
  3078. END EnterCustomBuiltins;
  3079. PROCEDURE GetSystem(): Global.System;
  3080. BEGIN
  3081. (* create system object if not yet existing *)
  3082. IF system = NIL THEN
  3083. (* used stack frame layout:
  3084. param 1
  3085. param 2
  3086. ...
  3087. param n-1
  3088. FP+8 -> param n
  3089. FP+4 -> old LR
  3090. FP -> old FP
  3091. FP-4 -> local 1
  3092. local 2
  3093. ...
  3094. spill 1
  3095. spill 2
  3096. ....
  3097. *)
  3098. (*
  3099. codeUnit, dataUnit = 8, 8
  3100. addressSize = 32
  3101. minVarAlign, maxVarAlign = 32, 32
  3102. minParAlign, maxParAlign = 8, 32
  3103. offsetFirstPar = 32 * 2
  3104. registerParameters = 0
  3105. *)
  3106. NEW(system, 8, 8, 32, (*32*) 8, 32, 8, 32, 32 * 2, cooperative);
  3107. IF oberon07 THEN
  3108. IF Trace THEN D.String("Oberon07"); D.Ln END;
  3109. Global.SetDefaultDeclarations(system, 32) (* each basic type uses at least 32 bits -> INTEGER will be 32 bits long *)
  3110. ELSE
  3111. IF Trace THEN D.String("not Oberon07"); D.Ln END;
  3112. Global.SetDefaultDeclarations(system, 8) (* INTEGER will be 16 bits long *)
  3113. END;
  3114. Global.SetDefaultOperators(system);
  3115. EnterCustomBuiltins
  3116. END;
  3117. RETURN system
  3118. END GetSystem;
  3119. (** whether the code generator can generate code for a certain IR instruction
  3120. if not, where to find the runtime procedure that is to be called instead **)
  3121. PROCEDURE SupportedInstruction(CONST irInstruction: IntermediateCode.Instruction; VAR moduleName, procedureName: ARRAY OF CHAR): BOOLEAN;
  3122. BEGIN
  3123. (* only necessary for binary object file format for symbol / module entry in IntermediateBackend *)
  3124. RETURN cg.Supported(irInstruction, moduleName, procedureName);
  3125. END SupportedInstruction;
  3126. (** whether a certain intermediate code immediate value can be directly appear in code
  3127. if not, the value is stored in a const section and loaded from there **)
  3128. PROCEDURE SupportedImmediate(CONST irImmediateOperand: IntermediateCode.Operand): BOOLEAN;
  3129. VAR
  3130. result: BOOLEAN;
  3131. BEGIN
  3132. (* TODO: remove this *)
  3133. RETURN TRUE; (* tentatively generate all immediates, as symbol fixups are not yet implemented *)
  3134. result := FALSE;
  3135. IF (irImmediateOperand.type.form IN IntermediateCode.Integer) & (irImmediateOperand.type.sizeInBits <= 32) THEN
  3136. (* 32 bit integers *)
  3137. IF cg.ValueIsDirectlyEncodable(LONGINT(irImmediateOperand.intValue)) THEN
  3138. (* the value can be directly encoded as an ARM immediate operand *)
  3139. result := TRUE
  3140. ELSIF cg.ValueComposition(LONGINT(irImmediateOperand.intValue), FALSE, emptyOperand) <= 2 THEN (* TODO: find reasonable limit *)
  3141. (* the value can be generated using a limited amount of intructions *)
  3142. result := TRUE
  3143. END
  3144. END;
  3145. RETURN result
  3146. END SupportedImmediate;
  3147. PROCEDURE GenerateBinary(module: Sections.Module; dump: Streams.Writer);
  3148. VAR
  3149. in: Sections.Section;
  3150. out: BinaryCode.Section;
  3151. name: Basic.SectionName;
  3152. procedure: SyntaxTree.Procedure;
  3153. i, j, initialSectionCount: LONGINT;
  3154. (* recompute fixup positions and assign binary sections *)
  3155. PROCEDURE PatchFixups(section: BinaryCode.Section);
  3156. VAR resolved: BinaryCode.Section; fixup: BinaryCode.Fixup; displacement,symbolOffset: LONGINT; in: IntermediateCode.Section;
  3157. symbol: Sections.Section;
  3158. BEGIN
  3159. fixup := section.fixupList.firstFixup;
  3160. WHILE fixup # NIL DO
  3161. symbol := module.allSections.FindByName(fixup.symbol.name);
  3162. IF (symbol # NIL) & (symbol(IntermediateCode.Section).resolved # NIL) THEN
  3163. resolved := symbol(IntermediateCode.Section).resolved(BinaryCode.Section);
  3164. in := symbol(IntermediateCode.Section);
  3165. symbolOffset := fixup.symbolOffset;
  3166. IF symbolOffset = in.pc THEN
  3167. displacement := resolved.pc
  3168. ELSIF (symbolOffset # 0) THEN
  3169. ASSERT(in.pc > symbolOffset);
  3170. displacement := in.instructions[symbolOffset].pc;
  3171. ELSE
  3172. displacement := 0;
  3173. END;
  3174. fixup.SetSymbol(fixup.symbol.name,fixup.symbol.fingerprint,0,fixup.displacement+displacement);
  3175. END;
  3176. fixup := fixup.nextFixup;
  3177. END;
  3178. END PatchFixups;
  3179. (*
  3180. PROCEDURE Resolve(VAR fixup: BinaryCode.Fixup);
  3181. BEGIN
  3182. IF (fixup.symbol.name # "") & (fixup.resolved = NIL) THEN fixup.resolved := module.allSections.FindByName(fixup.symbol.name) END;
  3183. END Resolve;
  3184. (* recompute fixup positions and assign binary sections *)
  3185. PROCEDURE PatchFixups(section: BinaryCode.Section);
  3186. VAR resolved: BinaryCode.Section; fixup: BinaryCode.Fixup; symbolOffset, offsetWithinSection: LONGINT; in: IntermediateCode.Section;
  3187. BEGIN
  3188. fixup := section.fixupList.firstFixup;
  3189. WHILE fixup # NIL DO
  3190. Resolve(fixup);
  3191. IF (fixup.resolved # NIL) & (fixup.resolved(IntermediateCode.Section).resolved # NIL) THEN
  3192. resolved := fixup.resolved(IntermediateCode.Section).resolved(BinaryCode.Section);
  3193. in := fixup.resolved(IntermediateCode.Section);
  3194. (* TODO: is this correct? *)
  3195. symbolOffset := fixup.symbolOffset;
  3196. ASSERT(fixup.symbolOffset < in.pc);
  3197. IF (fixup.symbolOffset # 0) & (symbolOffset < in.pc) THEN
  3198. offsetWithinSection := in.instructions[fixup.symbolOffset].pc;
  3199. (*
  3200. (* TENTATIVE *)
  3201. D.String("FIXUP PATCH:"); D.Ln;
  3202. D.String(" symbol name: "); fixup.symbol.DumpName(D.Log); D.String("/");
  3203. D.String(" symbol offset: "); D.Int(fixup.symbolOffset, 0); D.Ln;
  3204. D.String(" offsetWithinSection"); D.Int(offsetWithinSection, 0); D.Ln;
  3205. D.String(" fixup.displacement (before)"); D.Int(fixup.displacement, 0); D.Ln; ; D.Ln;
  3206. D.Update;
  3207. *)
  3208. (* remove the fixup's symbol offset (in IR units) and change the displacement (in system units) accordingly: *)
  3209. fixup.SetSymbol(fixup.symbol.name, fixup.symbol.fingerprint, 0, offsetWithinSection + fixup.displacement)
  3210. END
  3211. END;
  3212. fixup := fixup.nextFixup;
  3213. END;
  3214. END PatchFixups;
  3215. *)
  3216. BEGIN
  3217. cg.SetModule(module);
  3218. cg.dump := dump;
  3219. FOR i := 0 TO module.allSections.Length() - 1 DO
  3220. in := module.allSections.GetSection(i);
  3221. IF in.type = Sections.InlineCodeSection THEN
  3222. Basic.SegmentedNameToString(in.name, name);
  3223. out := ResolvedSection(in(IntermediateCode.Section));
  3224. cg.dump := out.comments;
  3225. cg.Section(in(IntermediateCode.Section), out);
  3226. IF in.symbol # NIL THEN
  3227. procedure := in.symbol(SyntaxTree.Procedure);
  3228. procedure.procedureScope.body.code.SetBinaryCode(out.os.bits);
  3229. END;
  3230. END
  3231. END;
  3232. initialSectionCount := 0;
  3233. REPEAT
  3234. j := initialSectionCount;
  3235. initialSectionCount := module.allSections.Length() ;
  3236. FOR i := j TO initialSectionCount - 1 DO
  3237. in := module.allSections.GetSection(i);
  3238. Basic.SegmentedNameToString(in.name, name);
  3239. IF (in.type # Sections.InlineCodeSection) (*& (in(IntermediateCode.Section).resolved = NIL) *) THEN
  3240. out := ResolvedSection(in(IntermediateCode.Section));
  3241. cg.Section(in(IntermediateCode.Section),out);
  3242. END
  3243. END
  3244. UNTIL initialSectionCount = module.allSections.Length(); (* process remaining sections that have been added during traversal of sections *)
  3245. FOR i := 0 TO module.allSections.Length() - 1 DO
  3246. in := module.allSections.GetSection(i);
  3247. Basic.SegmentedNameToString(in.name, name);
  3248. in := module.allSections.GetSection(i);
  3249. PatchFixups(in(IntermediateCode.Section).resolved)
  3250. END;
  3251. IF cg.error THEN Error("", Diagnostics.Invalid, Diagnostics.Invalid, "") END
  3252. END GenerateBinary;
  3253. (** create an ARM code module from an intermediate code module **)
  3254. PROCEDURE ProcessIntermediateCodeModule*(intermediateCodeModule: Formats.GeneratedModule): Formats.GeneratedModule;
  3255. VAR
  3256. result: Formats.GeneratedModule;
  3257. BEGIN
  3258. ASSERT(intermediateCodeModule IS Sections.Module);
  3259. result := ProcessIntermediateCodeModule^(intermediateCodeModule);
  3260. IF ~error THEN
  3261. GenerateBinary(result(Sections.Module), dump);
  3262. IF dump # NIL THEN
  3263. dump.Ln; dump.Ln;
  3264. dump.String("------------------ binary code -------------------"); dump.Ln;
  3265. IF (traceString="") OR (traceString="*") THEN
  3266. result.Dump(dump);
  3267. dump.Update
  3268. ELSE
  3269. Sections.DumpFiltered(dump, result(Sections.Module), traceString);
  3270. dump.Update;
  3271. END
  3272. END;
  3273. END;
  3274. RETURN result
  3275. FINALLY
  3276. IF dump # NIL THEN
  3277. dump.Ln; dump.Ln;
  3278. dump.String("------------------ rescued code (code generation trapped) -------------------"); dump.Ln;
  3279. IF (traceString="") OR (traceString="*") THEN
  3280. result.Dump(dump);
  3281. dump.Update
  3282. ELSE
  3283. Sections.DumpFiltered(dump,result(Sections.Module),traceString);
  3284. dump.Update;
  3285. END
  3286. END;
  3287. RETURN result
  3288. END ProcessIntermediateCodeModule;
  3289. PROCEDURE DefineOptions(options: Options.Options);
  3290. BEGIN
  3291. options.Add(0X, UseFPU32Flag, Options.Flag);
  3292. options.Add(0X, UseFPU64Flag, Options.Flag);
  3293. options.Add(0X, "noInitLocals", Options.Flag);
  3294. DefineOptions^(options);
  3295. END DefineOptions;
  3296. PROCEDURE GetOptions(options: Options.Options);
  3297. BEGIN
  3298. IF options.GetFlag(UseFPU32Flag) THEN useFPU32 := TRUE END;
  3299. IF options.GetFlag(UseFPU64Flag) THEN useFPU64 := TRUE; useFPU32 := TRUE END;
  3300. IF options.GetFlag("noInitLocals") THEN initLocals := FALSE END;
  3301. GetOptions^(options);
  3302. END GetOptions;
  3303. PROCEDURE DefaultObjectFileFormat(): Formats.ObjectFileFormat;
  3304. BEGIN RETURN ObjectFileFormat.Get();
  3305. END DefaultObjectFileFormat;
  3306. PROCEDURE DefaultSymbolFileFormat(): Formats.SymbolFileFormat;
  3307. BEGIN RETURN NIL
  3308. END DefaultSymbolFileFormat;
  3309. (** get the name of the backend **)
  3310. PROCEDURE GetDescription(VAR instructionSet: ARRAY OF CHAR);
  3311. BEGIN instructionSet := "ARM"
  3312. END GetDescription;
  3313. PROCEDURE FindPC(x: SyntaxTree.Module; CONST sectionName: ARRAY OF CHAR; sectionOffset: LONGINT);
  3314. VAR
  3315. section: Sections.Section; binarySection: BinaryCode.Section; label: BinaryCode.LabelList; module: Formats.GeneratedModule;
  3316. i: LONGINT; pooledName: Basic.SegmentedName;
  3317. BEGIN
  3318. module := ProcessSyntaxTreeModule(x);
  3319. Basic.ToSegmentedName(sectionName, pooledName);
  3320. i := 0;
  3321. REPEAT
  3322. section := module(Sections.Module).allSections.GetSection(i);
  3323. INC(i);
  3324. UNTIL (i = module(Sections.Module).allSections.Length()) OR (section.name = pooledName);
  3325. IF section.name # pooledName THEN
  3326. diagnostics.Error(module.module.sourceName,Diagnostics.Invalid,Diagnostics.Invalid," could not locate pc");
  3327. ELSE
  3328. binarySection := section(IntermediateCode.Section).resolved;
  3329. label := binarySection.labels;
  3330. WHILE (label # NIL) & (label.offset >= sectionOffset) DO
  3331. label := label.prev;
  3332. END;
  3333. IF label # NIL THEN
  3334. diagnostics.Information(module.module.sourceName,label.position,Diagnostics.Invalid," pc position");
  3335. ELSE
  3336. diagnostics.Error(module.module.sourceName,Diagnostics.Invalid,Diagnostics.Invalid," could not locate pc");
  3337. END;
  3338. END;
  3339. END FindPC;
  3340. END BackendARM;
  3341. VAR
  3342. emptyOperand: Operand;
  3343. rFixupPattern: ObjectFile.FixupPatterns; (* pattern for an absolute 32-bit fixup *)
  3344. PROCEDURE Assert(condition: BOOLEAN; CONST message: ARRAY OF CHAR);
  3345. BEGIN ASSERT(condition, 100)
  3346. END Assert;
  3347. PROCEDURE Halt(CONST message: ARRAY OF CHAR);
  3348. BEGIN HALT(100)
  3349. END Halt;
  3350. PROCEDURE PowerOf2(val: HUGEINT; VAR exp: LONGINT): BOOLEAN;
  3351. BEGIN
  3352. IF val <= 0 THEN RETURN FALSE END;
  3353. exp := 0;
  3354. WHILE ~ODD(val) DO
  3355. val := val DIV 2;
  3356. INC(exp)
  3357. END;
  3358. RETURN val = 1
  3359. END PowerOf2;
  3360. (** get the ARM code section that corresponds to an intermediate code section **)
  3361. PROCEDURE ResolvedSection(irSection: IntermediateCode.Section): BinaryCode.Section;
  3362. VAR
  3363. result: BinaryCode.Section;
  3364. BEGIN
  3365. IF irSection.resolved = NIL THEN
  3366. NEW(result, irSection.type, irSection.priority, 8, irSection.name, irSection.comments # NIL, FALSE);
  3367. (* set fixed position or alignment
  3368. (also make sure that any section has an alignment of at least 4 bytes) *)
  3369. IF ~irSection.fixed & (irSection.positionOrAlignment < 4) THEN
  3370. result.SetAlignment(FALSE, 4)
  3371. ELSE
  3372. result.SetAlignment(irSection.fixed, irSection.positionOrAlignment);
  3373. END;
  3374. irSection.SetResolved(result)
  3375. ELSE
  3376. result := irSection.resolved
  3377. END;
  3378. RETURN result
  3379. END ResolvedSection;
  3380. (** initialize the module **)
  3381. PROCEDURE Init;
  3382. BEGIN
  3383. InstructionSet.InitOperand(emptyOperand);
  3384. NEW(rFixupPattern, 1);
  3385. rFixupPattern[0].offset := 0;
  3386. rFixupPattern[0].bits := 32;
  3387. END Init;
  3388. (** get an instance of the ARM backend **)
  3389. PROCEDURE Get*(): Backend.Backend;
  3390. VAR
  3391. result: BackendARM;
  3392. BEGIN
  3393. NEW(result);
  3394. RETURN result
  3395. END Get;
  3396. (* only for testing purposes *)
  3397. PROCEDURE Test*;
  3398. VAR
  3399. codeGenerator: CodeGeneratorARM;
  3400. value, count: LONGINT;
  3401. BEGIN
  3402. NEW(codeGenerator, "", NIL, NIL);
  3403. FOR value := 0 TO 300 BY 1 DO
  3404. count := codeGenerator.ValueComposition(value, FALSE, emptyOperand);
  3405. D.String("value: "); D.Int(value, 0); D.String(" -> "); D.Int(count, 0); D.String(" instructions"); D.Ln;
  3406. END;
  3407. D.Ln; D.Update
  3408. END Test;
  3409. (* TODO: move this to Debugging.Mod or even Streams.Mod *)
  3410. (** write an integer in binary right-justified in a field of at least ABS(w) characters.
  3411. If w < 0 THEN ABS(w) least significant hex digits of 'value' are written (potentially including leading zeros or ones)
  3412. **)
  3413. PROCEDURE DBin*(value: HUGEINT; numberDigits: LONGINT);
  3414. CONST
  3415. MaxBitSize = SIZEOF(HUGEINT) * 8;
  3416. VAR
  3417. i, firstRelevantPos: LONGINT;
  3418. prefixWithSpaces: BOOLEAN;
  3419. chars: ARRAY MaxBitSize OF CHAR;
  3420. prefixChar: CHAR;
  3421. BEGIN
  3422. prefixWithSpaces := numberDigits >= 0;
  3423. numberDigits := ABS(numberDigits);
  3424. (*
  3425. - calculate an array containing the full bitstring
  3426. - determine the position of the first relevant digit
  3427. *)
  3428. firstRelevantPos := 0;
  3429. FOR i := MaxBitSize - 1 TO 0 BY -1 DO
  3430. IF ODD(value) THEN
  3431. chars[i] := '1';
  3432. firstRelevantPos := i (* occurence of a '1' -> changes the first relevant position *)
  3433. ELSE
  3434. chars[i] := '0'
  3435. END;
  3436. value := value DIV 2
  3437. END;
  3438. (* if space prefixing is enabled, limit the number of digits to the relevant digits *)
  3439. IF prefixWithSpaces THEN numberDigits := MAX(numberDigits, MaxBitSize - firstRelevantPos) END;
  3440. IF numberDigits > MaxBitSize THEN
  3441. IF prefixWithSpaces THEN prefixChar := ' ' ELSE prefixChar := chars[0] END; (* use spaces or sign bit *)
  3442. FOR i := 1 TO numberDigits - MaxBitSize DO D.Char(prefixChar) END;
  3443. numberDigits := MaxBitSize
  3444. END;
  3445. ASSERT((numberDigits >= 0) & (numberDigits <= MaxBitSize));
  3446. FOR i := MaxBitSize - numberDigits TO MaxBitSize - 1 DO
  3447. IF prefixWithSpaces & (i < firstRelevantPos) THEN D.Char(' ') ELSE D.Char(chars[i]) END
  3448. END;
  3449. D.Ln;
  3450. END DBin;
  3451. BEGIN
  3452. Init;
  3453. END FoxARMBackend.
  3454. SystemTools.FreeDownTo FoxARMBackend ~