FoxARMBackend.Mod 153 KB

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