FoxARMBackend.Mod 159 KB

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