ARMFrameLowering.cpp 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360
  1. //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the ARM implementation of TargetFrameLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //
  13. // This file contains the ARM implementation of TargetFrameLowering class.
  14. //
  15. // On ARM, stack frames are structured as follows:
  16. //
  17. // The stack grows downward.
  18. //
  19. // All of the individual frame areas on the frame below are optional, i.e. it's
  20. // possible to create a function so that the particular area isn't present
  21. // in the frame.
  22. //
  23. // At function entry, the "frame" looks as follows:
  24. //
  25. // | | Higher address
  26. // |-----------------------------------|
  27. // | |
  28. // | arguments passed on the stack |
  29. // | |
  30. // |-----------------------------------| <- sp
  31. // | | Lower address
  32. //
  33. //
  34. // After the prologue has run, the frame has the following general structure.
  35. // Technically the last frame area (VLAs) doesn't get created until in the
  36. // main function body, after the prologue is run. However, it's depicted here
  37. // for completeness.
  38. //
  39. // | | Higher address
  40. // |-----------------------------------|
  41. // | |
  42. // | arguments passed on the stack |
  43. // | |
  44. // |-----------------------------------| <- (sp at function entry)
  45. // | |
  46. // | varargs from registers |
  47. // | |
  48. // |-----------------------------------|
  49. // | |
  50. // | prev_lr |
  51. // | prev_fp |
  52. // | (a.k.a. "frame record") |
  53. // | |
  54. // |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11)
  55. // | |
  56. // | callee-saved gpr registers |
  57. // | |
  58. // |-----------------------------------|
  59. // | |
  60. // | callee-saved fp/simd regs |
  61. // | |
  62. // |-----------------------------------|
  63. // |.empty.space.to.make.part.below....|
  64. // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
  65. // |.the.standard.8-byte.alignment.....| compile time; if present)
  66. // |-----------------------------------|
  67. // | |
  68. // | local variables of fixed size |
  69. // | including spill slots |
  70. // |-----------------------------------| <- base pointer (not defined by ABI,
  71. // |.variable-sized.local.variables....| LLVM chooses r6)
  72. // |.(VLAs)............................| (size of this area is unknown at
  73. // |...................................| compile time)
  74. // |-----------------------------------| <- sp
  75. // | | Lower address
  76. //
  77. //
  78. // To access the data in a frame, at-compile time, a constant offset must be
  79. // computable from one of the pointers (fp, bp, sp) to access it. The size
  80. // of the areas with a dotted background cannot be computed at compile-time
  81. // if they are present, making it required to have all three of fp, bp and
  82. // sp to be set up to be able to access all contents in the frame areas,
  83. // assuming all of the frame areas are non-empty.
  84. //
  85. // For most functions, some of the frame areas are empty. For those functions,
  86. // it may not be necessary to set up fp or bp:
  87. // * A base pointer is definitely needed when there are both VLAs and local
  88. // variables with more-than-default alignment requirements.
  89. // * A frame pointer is definitely needed when there are local variables with
  90. // more-than-default alignment requirements.
  91. //
  92. // In some cases when a base pointer is not strictly needed, it is generated
  93. // anyway when offsets from the frame pointer to access local variables become
  94. // so large that the offset can't be encoded in the immediate fields of loads
  95. // or stores.
  96. //
  97. // The frame pointer might be chosen to be r7 or r11, depending on the target
  98. // architecture and operating system. See ARMSubtarget::getFramePointerReg for
  99. // details.
  100. //
  101. // Outgoing function arguments must be at the bottom of the stack frame when
  102. // calling another function. If we do not have variable-sized stack objects, we
  103. // can allocate a "reserved call frame" area at the bottom of the local
  104. // variable area, large enough for all outgoing calls. If we do have VLAs, then
  105. // the stack pointer must be decremented and incremented around each call to
  106. // make space for the arguments below the VLAs.
  107. //
  108. //===----------------------------------------------------------------------===//
  109. #include "ARMFrameLowering.h"
  110. #include "ARMBaseInstrInfo.h"
  111. #include "ARMBaseRegisterInfo.h"
  112. #include "ARMConstantPoolValue.h"
  113. #include "ARMMachineFunctionInfo.h"
  114. #include "ARMSubtarget.h"
  115. #include "MCTargetDesc/ARMAddressingModes.h"
  116. #include "MCTargetDesc/ARMBaseInfo.h"
  117. #include "Utils/ARMBaseInfo.h"
  118. #include "llvm/ADT/BitVector.h"
  119. #include "llvm/ADT/STLExtras.h"
  120. #include "llvm/ADT/SmallPtrSet.h"
  121. #include "llvm/ADT/SmallVector.h"
  122. #include "llvm/CodeGen/MachineBasicBlock.h"
  123. #include "llvm/CodeGen/MachineConstantPool.h"
  124. #include "llvm/CodeGen/MachineFrameInfo.h"
  125. #include "llvm/CodeGen/MachineFunction.h"
  126. #include "llvm/CodeGen/MachineInstr.h"
  127. #include "llvm/CodeGen/MachineInstrBuilder.h"
  128. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  129. #include "llvm/CodeGen/MachineModuleInfo.h"
  130. #include "llvm/CodeGen/MachineOperand.h"
  131. #include "llvm/CodeGen/MachineRegisterInfo.h"
  132. #include "llvm/CodeGen/RegisterScavenging.h"
  133. #include "llvm/CodeGen/TargetInstrInfo.h"
  134. #include "llvm/CodeGen/TargetOpcodes.h"
  135. #include "llvm/CodeGen/TargetRegisterInfo.h"
  136. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  137. #include "llvm/IR/Attributes.h"
  138. #include "llvm/IR/CallingConv.h"
  139. #include "llvm/IR/DebugLoc.h"
  140. #include "llvm/IR/Function.h"
  141. #include "llvm/MC/MCAsmInfo.h"
  142. #include "llvm/MC/MCContext.h"
  143. #include "llvm/MC/MCDwarf.h"
  144. #include "llvm/MC/MCInstrDesc.h"
  145. #include "llvm/MC/MCRegisterInfo.h"
  146. #include "llvm/Support/CodeGen.h"
  147. #include "llvm/Support/CommandLine.h"
  148. #include "llvm/Support/Compiler.h"
  149. #include "llvm/Support/Debug.h"
  150. #include "llvm/Support/ErrorHandling.h"
  151. #include "llvm/Support/MathExtras.h"
  152. #include "llvm/Support/raw_ostream.h"
  153. #include "llvm/Target/TargetMachine.h"
  154. #include "llvm/Target/TargetOptions.h"
  155. #include <algorithm>
  156. #include <cassert>
  157. #include <cstddef>
  158. #include <cstdint>
  159. #include <iterator>
  160. #include <utility>
  161. #include <vector>
  162. #define DEBUG_TYPE "arm-frame-lowering"
  163. using namespace llvm;
  164. static cl::opt<bool>
  165. SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
  166. cl::desc("Align ARM NEON spills in prolog and epilog"));
  167. static MachineBasicBlock::iterator
  168. skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
  169. unsigned NumAlignedDPRCS2Regs);
  170. ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
  171. : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
  172. STI(sti) {}
  173. bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
  174. // iOS always has a FP for backtracking, force other targets to keep their FP
  175. // when doing FastISel. The emitted code is currently superior, and in cases
  176. // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
  177. return MF.getSubtarget<ARMSubtarget>().useFastISel();
  178. }
  179. /// Returns true if the target can safely skip saving callee-saved registers
  180. /// for noreturn nounwind functions.
  181. bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
  182. assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
  183. MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
  184. !MF.getFunction().hasFnAttribute(Attribute::UWTable));
  185. // Frame pointer and link register are not treated as normal CSR, thus we
  186. // can always skip CSR saves for nonreturning functions.
  187. return true;
  188. }
  189. /// hasFP - Return true if the specified function should have a dedicated frame
  190. /// pointer register. This is true if the function has variable sized allocas
  191. /// or if frame pointer elimination is disabled.
  192. bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
  193. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  194. const MachineFrameInfo &MFI = MF.getFrameInfo();
  195. // ABI-required frame pointer.
  196. if (MF.getTarget().Options.DisableFramePointerElim(MF))
  197. return true;
  198. // Frame pointer required for use within this function.
  199. return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
  200. MFI.isFrameAddressTaken());
  201. }
  202. /// isFPReserved - Return true if the frame pointer register should be
  203. /// considered a reserved register on the scope of the specified function.
  204. bool ARMFrameLowering::isFPReserved(const MachineFunction &MF) const {
  205. return hasFP(MF) || MF.getSubtarget<ARMSubtarget>().createAAPCSFrameChain();
  206. }
  207. /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
  208. /// not required, we reserve argument space for call sites in the function
  209. /// immediately on entry to the current function. This eliminates the need for
  210. /// add/sub sp brackets around call sites. Returns true if the call frame is
  211. /// included as part of the stack frame.
  212. bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
  213. const MachineFrameInfo &MFI = MF.getFrameInfo();
  214. unsigned CFSize = MFI.getMaxCallFrameSize();
  215. // It's not always a good idea to include the call frame as part of the
  216. // stack frame. ARM (especially Thumb) has small immediate offset to
  217. // address the stack frame. So a large call frame can cause poor codegen
  218. // and may even makes it impossible to scavenge a register.
  219. if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
  220. return false;
  221. return !MFI.hasVarSizedObjects();
  222. }
  223. /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
  224. /// call frame pseudos can be simplified. Unlike most targets, having a FP
  225. /// is not sufficient here since we still may reference some objects via SP
  226. /// even when FP is available in Thumb2 mode.
  227. bool
  228. ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
  229. return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
  230. }
  231. // Returns how much of the incoming argument stack area we should clean up in an
  232. // epilogue. For the C calling convention this will be 0, for guaranteed tail
  233. // call conventions it can be positive (a normal return or a tail call to a
  234. // function that uses less stack space for arguments) or negative (for a tail
  235. // call to a function that needs more stack space than us for arguments).
  236. static int getArgumentStackToRestore(MachineFunction &MF,
  237. MachineBasicBlock &MBB) {
  238. MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
  239. bool IsTailCallReturn = false;
  240. if (MBB.end() != MBBI) {
  241. unsigned RetOpcode = MBBI->getOpcode();
  242. IsTailCallReturn = RetOpcode == ARM::TCRETURNdi ||
  243. RetOpcode == ARM::TCRETURNri;
  244. }
  245. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  246. int ArgumentPopSize = 0;
  247. if (IsTailCallReturn) {
  248. MachineOperand &StackAdjust = MBBI->getOperand(1);
  249. // For a tail-call in a callee-pops-arguments environment, some or all of
  250. // the stack may actually be in use for the call's arguments, this is
  251. // calculated during LowerCall and consumed here...
  252. ArgumentPopSize = StackAdjust.getImm();
  253. } else {
  254. // ... otherwise the amount to pop is *all* of the argument space,
  255. // conveniently stored in the MachineFunctionInfo by
  256. // LowerFormalArguments. This will, of course, be zero for the C calling
  257. // convention.
  258. ArgumentPopSize = AFI->getArgumentStackToRestore();
  259. }
  260. return ArgumentPopSize;
  261. }
  262. static bool needsWinCFI(const MachineFunction &MF) {
  263. const Function &F = MF.getFunction();
  264. return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() &&
  265. F.needsUnwindTableEntry();
  266. }
  267. // Given a load or a store instruction, generate an appropriate unwinding SEH
  268. // code on Windows.
  269. static MachineBasicBlock::iterator insertSEH(MachineBasicBlock::iterator MBBI,
  270. const TargetInstrInfo &TII,
  271. unsigned Flags) {
  272. unsigned Opc = MBBI->getOpcode();
  273. MachineBasicBlock *MBB = MBBI->getParent();
  274. MachineFunction &MF = *MBB->getParent();
  275. DebugLoc DL = MBBI->getDebugLoc();
  276. MachineInstrBuilder MIB;
  277. const ARMSubtarget &Subtarget = MF.getSubtarget<ARMSubtarget>();
  278. const ARMBaseRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
  279. Flags |= MachineInstr::NoMerge;
  280. switch (Opc) {
  281. default:
  282. report_fatal_error("No SEH Opcode for instruction " + TII.getName(Opc));
  283. break;
  284. case ARM::t2ADDri: // add.w r11, sp, #xx
  285. case ARM::t2ADDri12: // add.w r11, sp, #xx
  286. case ARM::t2MOVTi16: // movt r4, #xx
  287. case ARM::tBL: // bl __chkstk
  288. // These are harmless if used for just setting up a frame pointer,
  289. // but that frame pointer can't be relied upon for unwinding, unless
  290. // set up with SEH_SaveSP.
  291. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
  292. .addImm(/*Wide=*/1)
  293. .setMIFlags(Flags);
  294. break;
  295. case ARM::t2MOVi16: { // mov(w) r4, #xx
  296. bool Wide = MBBI->getOperand(1).getImm() >= 256;
  297. if (!Wide) {
  298. MachineInstrBuilder NewInstr =
  299. BuildMI(MF, DL, TII.get(ARM::tMOVi8)).setMIFlags(MBBI->getFlags());
  300. NewInstr.add(MBBI->getOperand(0));
  301. NewInstr.add(t1CondCodeOp(/*isDead=*/true));
  302. for (unsigned i = 1, NumOps = MBBI->getNumOperands(); i != NumOps; ++i)
  303. NewInstr.add(MBBI->getOperand(i));
  304. MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr);
  305. MBB->erase(MBBI);
  306. MBBI = NewMBBI;
  307. }
  308. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)).addImm(Wide).setMIFlags(Flags);
  309. break;
  310. }
  311. case ARM::tBLXr: // blx r12 (__chkstk)
  312. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
  313. .addImm(/*Wide=*/0)
  314. .setMIFlags(Flags);
  315. break;
  316. case ARM::t2MOVi32imm: // movw+movt
  317. // This pseudo instruction expands into two mov instructions. If the
  318. // second operand is a symbol reference, this will stay as two wide
  319. // instructions, movw+movt. If they're immediates, the first one can
  320. // end up as a narrow mov though.
  321. // As two SEH instructions are appended here, they won't get interleaved
  322. // between the two final movw/movt instructions, but it doesn't make any
  323. // practical difference.
  324. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
  325. .addImm(/*Wide=*/1)
  326. .setMIFlags(Flags);
  327. MBB->insertAfter(MBBI, MIB);
  328. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
  329. .addImm(/*Wide=*/1)
  330. .setMIFlags(Flags);
  331. break;
  332. case ARM::t2LDMIA_RET:
  333. case ARM::t2LDMIA_UPD:
  334. case ARM::t2STMDB_UPD: {
  335. unsigned Mask = 0;
  336. bool Wide = false;
  337. for (unsigned i = 4, NumOps = MBBI->getNumOperands(); i != NumOps; ++i) {
  338. const MachineOperand &MO = MBBI->getOperand(i);
  339. if (!MO.isReg() || MO.isImplicit())
  340. continue;
  341. unsigned Reg = RegInfo->getSEHRegNum(MO.getReg());
  342. if (Reg == 15)
  343. Reg = 14;
  344. if (Reg >= 8 && Reg <= 13)
  345. Wide = true;
  346. else if (Opc == ARM::t2LDMIA_UPD && Reg == 14)
  347. Wide = true;
  348. Mask |= 1 << Reg;
  349. }
  350. if (!Wide) {
  351. unsigned NewOpc;
  352. switch (Opc) {
  353. case ARM::t2LDMIA_RET:
  354. NewOpc = ARM::tPOP_RET;
  355. break;
  356. case ARM::t2LDMIA_UPD:
  357. NewOpc = ARM::tPOP;
  358. break;
  359. case ARM::t2STMDB_UPD:
  360. NewOpc = ARM::tPUSH;
  361. break;
  362. default:
  363. llvm_unreachable("");
  364. }
  365. MachineInstrBuilder NewInstr =
  366. BuildMI(MF, DL, TII.get(NewOpc)).setMIFlags(MBBI->getFlags());
  367. for (unsigned i = 2, NumOps = MBBI->getNumOperands(); i != NumOps; ++i)
  368. NewInstr.add(MBBI->getOperand(i));
  369. MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr);
  370. MBB->erase(MBBI);
  371. MBBI = NewMBBI;
  372. }
  373. unsigned SEHOpc =
  374. (Opc == ARM::t2LDMIA_RET) ? ARM::SEH_SaveRegs_Ret : ARM::SEH_SaveRegs;
  375. MIB = BuildMI(MF, DL, TII.get(SEHOpc))
  376. .addImm(Mask)
  377. .addImm(Wide ? 1 : 0)
  378. .setMIFlags(Flags);
  379. break;
  380. }
  381. case ARM::VSTMDDB_UPD:
  382. case ARM::VLDMDIA_UPD: {
  383. int First = -1, Last = 0;
  384. for (unsigned i = 4, NumOps = MBBI->getNumOperands(); i != NumOps; ++i) {
  385. const MachineOperand &MO = MBBI->getOperand(i);
  386. unsigned Reg = RegInfo->getSEHRegNum(MO.getReg());
  387. if (First == -1)
  388. First = Reg;
  389. Last = Reg;
  390. }
  391. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveFRegs))
  392. .addImm(First)
  393. .addImm(Last)
  394. .setMIFlags(Flags);
  395. break;
  396. }
  397. case ARM::tSUBspi:
  398. case ARM::tADDspi:
  399. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc))
  400. .addImm(MBBI->getOperand(2).getImm() * 4)
  401. .addImm(/*Wide=*/0)
  402. .setMIFlags(Flags);
  403. break;
  404. case ARM::t2SUBspImm:
  405. case ARM::t2SUBspImm12:
  406. case ARM::t2ADDspImm:
  407. case ARM::t2ADDspImm12:
  408. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc))
  409. .addImm(MBBI->getOperand(2).getImm())
  410. .addImm(/*Wide=*/1)
  411. .setMIFlags(Flags);
  412. break;
  413. case ARM::tMOVr:
  414. if (MBBI->getOperand(1).getReg() == ARM::SP &&
  415. (Flags & MachineInstr::FrameSetup)) {
  416. unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
  417. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP))
  418. .addImm(Reg)
  419. .setMIFlags(Flags);
  420. } else if (MBBI->getOperand(0).getReg() == ARM::SP &&
  421. (Flags & MachineInstr::FrameDestroy)) {
  422. unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
  423. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP))
  424. .addImm(Reg)
  425. .setMIFlags(Flags);
  426. } else {
  427. report_fatal_error("No SEH Opcode for MOV");
  428. }
  429. break;
  430. case ARM::tBX_RET:
  431. case ARM::TCRETURNri:
  432. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret))
  433. .addImm(/*Wide=*/0)
  434. .setMIFlags(Flags);
  435. break;
  436. case ARM::TCRETURNdi:
  437. MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret))
  438. .addImm(/*Wide=*/1)
  439. .setMIFlags(Flags);
  440. break;
  441. }
  442. return MBB->insertAfter(MBBI, MIB);
  443. }
  444. static MachineBasicBlock::iterator
  445. initMBBRange(MachineBasicBlock &MBB, const MachineBasicBlock::iterator &MBBI) {
  446. if (MBBI == MBB.begin())
  447. return MachineBasicBlock::iterator();
  448. return std::prev(MBBI);
  449. }
  450. static void insertSEHRange(MachineBasicBlock &MBB,
  451. MachineBasicBlock::iterator Start,
  452. const MachineBasicBlock::iterator &End,
  453. const ARMBaseInstrInfo &TII, unsigned MIFlags) {
  454. if (Start.isValid())
  455. Start = std::next(Start);
  456. else
  457. Start = MBB.begin();
  458. for (auto MI = Start; MI != End;) {
  459. auto Next = std::next(MI);
  460. // Check if this instruction already has got a SEH opcode added. In that
  461. // case, don't do this generic mapping.
  462. if (Next != End && isSEHInstruction(*Next)) {
  463. MI = std::next(Next);
  464. while (MI != End && isSEHInstruction(*MI))
  465. ++MI;
  466. continue;
  467. }
  468. insertSEH(MI, TII, MIFlags);
  469. MI = Next;
  470. }
  471. }
  472. static void emitRegPlusImmediate(
  473. bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
  474. const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
  475. unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
  476. ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
  477. if (isARM)
  478. emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
  479. Pred, PredReg, TII, MIFlags);
  480. else
  481. emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
  482. Pred, PredReg, TII, MIFlags);
  483. }
  484. static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
  485. MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
  486. const ARMBaseInstrInfo &TII, int NumBytes,
  487. unsigned MIFlags = MachineInstr::NoFlags,
  488. ARMCC::CondCodes Pred = ARMCC::AL,
  489. unsigned PredReg = 0) {
  490. emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
  491. MIFlags, Pred, PredReg);
  492. }
  493. static int sizeOfSPAdjustment(const MachineInstr &MI) {
  494. int RegSize;
  495. switch (MI.getOpcode()) {
  496. case ARM::VSTMDDB_UPD:
  497. RegSize = 8;
  498. break;
  499. case ARM::STMDB_UPD:
  500. case ARM::t2STMDB_UPD:
  501. RegSize = 4;
  502. break;
  503. case ARM::t2STR_PRE:
  504. case ARM::STR_PRE_IMM:
  505. return 4;
  506. default:
  507. llvm_unreachable("Unknown push or pop like instruction");
  508. }
  509. int count = 0;
  510. // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
  511. // pred) so the list starts at 4.
  512. for (int i = MI.getNumOperands() - 1; i >= 4; --i)
  513. count += RegSize;
  514. return count;
  515. }
  516. static bool WindowsRequiresStackProbe(const MachineFunction &MF,
  517. size_t StackSizeInBytes) {
  518. const MachineFrameInfo &MFI = MF.getFrameInfo();
  519. const Function &F = MF.getFunction();
  520. unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
  521. StackProbeSize =
  522. F.getFnAttributeAsParsedInteger("stack-probe-size", StackProbeSize);
  523. return (StackSizeInBytes >= StackProbeSize) &&
  524. !F.hasFnAttribute("no-stack-arg-probe");
  525. }
  526. namespace {
  527. struct StackAdjustingInsts {
  528. struct InstInfo {
  529. MachineBasicBlock::iterator I;
  530. unsigned SPAdjust;
  531. bool BeforeFPSet;
  532. };
  533. SmallVector<InstInfo, 4> Insts;
  534. void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
  535. bool BeforeFPSet = false) {
  536. InstInfo Info = {I, SPAdjust, BeforeFPSet};
  537. Insts.push_back(Info);
  538. }
  539. void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
  540. auto Info =
  541. llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
  542. assert(Info != Insts.end() && "invalid sp adjusting instruction");
  543. Info->SPAdjust += ExtraBytes;
  544. }
  545. void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
  546. const ARMBaseInstrInfo &TII, bool HasFP) {
  547. MachineFunction &MF = *MBB.getParent();
  548. unsigned CFAOffset = 0;
  549. for (auto &Info : Insts) {
  550. if (HasFP && !Info.BeforeFPSet)
  551. return;
  552. CFAOffset += Info.SPAdjust;
  553. unsigned CFIIndex = MF.addFrameInst(
  554. MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
  555. BuildMI(MBB, std::next(Info.I), dl,
  556. TII.get(TargetOpcode::CFI_INSTRUCTION))
  557. .addCFIIndex(CFIIndex)
  558. .setMIFlags(MachineInstr::FrameSetup);
  559. }
  560. }
  561. };
  562. } // end anonymous namespace
  563. /// Emit an instruction sequence that will align the address in
  564. /// register Reg by zero-ing out the lower bits. For versions of the
  565. /// architecture that support Neon, this must be done in a single
  566. /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
  567. /// single instruction. That function only gets called when optimizing
  568. /// spilling of D registers on a core with the Neon instruction set
  569. /// present.
  570. static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
  571. const TargetInstrInfo &TII,
  572. MachineBasicBlock &MBB,
  573. MachineBasicBlock::iterator MBBI,
  574. const DebugLoc &DL, const unsigned Reg,
  575. const Align Alignment,
  576. const bool MustBeSingleInstruction) {
  577. const ARMSubtarget &AST = MF.getSubtarget<ARMSubtarget>();
  578. const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
  579. const unsigned AlignMask = Alignment.value() - 1U;
  580. const unsigned NrBitsToZero = Log2(Alignment);
  581. assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
  582. if (!AFI->isThumbFunction()) {
  583. // if the BFC instruction is available, use that to zero the lower
  584. // bits:
  585. // bfc Reg, #0, log2(Alignment)
  586. // otherwise use BIC, if the mask to zero the required number of bits
  587. // can be encoded in the bic immediate field
  588. // bic Reg, Reg, Alignment-1
  589. // otherwise, emit
  590. // lsr Reg, Reg, log2(Alignment)
  591. // lsl Reg, Reg, log2(Alignment)
  592. if (CanUseBFC) {
  593. BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
  594. .addReg(Reg, RegState::Kill)
  595. .addImm(~AlignMask)
  596. .add(predOps(ARMCC::AL));
  597. } else if (AlignMask <= 255) {
  598. BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
  599. .addReg(Reg, RegState::Kill)
  600. .addImm(AlignMask)
  601. .add(predOps(ARMCC::AL))
  602. .add(condCodeOp());
  603. } else {
  604. assert(!MustBeSingleInstruction &&
  605. "Shouldn't call emitAligningInstructions demanding a single "
  606. "instruction to be emitted for large stack alignment for a target "
  607. "without BFC.");
  608. BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
  609. .addReg(Reg, RegState::Kill)
  610. .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
  611. .add(predOps(ARMCC::AL))
  612. .add(condCodeOp());
  613. BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
  614. .addReg(Reg, RegState::Kill)
  615. .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
  616. .add(predOps(ARMCC::AL))
  617. .add(condCodeOp());
  618. }
  619. } else {
  620. // Since this is only reached for Thumb-2 targets, the BFC instruction
  621. // should always be available.
  622. assert(CanUseBFC);
  623. BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
  624. .addReg(Reg, RegState::Kill)
  625. .addImm(~AlignMask)
  626. .add(predOps(ARMCC::AL));
  627. }
  628. }
  629. /// We need the offset of the frame pointer relative to other MachineFrameInfo
  630. /// offsets which are encoded relative to SP at function begin.
  631. /// See also emitPrologue() for how the FP is set up.
  632. /// Unfortunately we cannot determine this value in determineCalleeSaves() yet
  633. /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
  634. /// this to produce a conservative estimate that we check in an assert() later.
  635. static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI,
  636. const MachineFunction &MF) {
  637. // For Thumb1, push.w isn't available, so the first push will always push
  638. // r7 and lr onto the stack first.
  639. if (AFI.isThumb1OnlyFunction())
  640. return -AFI.getArgRegsSaveSize() - (2 * 4);
  641. // This is a conservative estimation: Assume the frame pointer being r7 and
  642. // pc("r15") up to r8 getting spilled before (= 8 registers).
  643. int MaxRegBytes = 8 * 4;
  644. if (STI.splitFramePointerPush(MF)) {
  645. // Here, r11 can be stored below all of r4-r15 (3 registers more than
  646. // above), plus d8-d15.
  647. MaxRegBytes = 11 * 4 + 8 * 8;
  648. }
  649. int FPCXTSaveSize =
  650. (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0;
  651. return -FPCXTSaveSize - AFI.getArgRegsSaveSize() - MaxRegBytes;
  652. }
  653. void ARMFrameLowering::emitPrologue(MachineFunction &MF,
  654. MachineBasicBlock &MBB) const {
  655. MachineBasicBlock::iterator MBBI = MBB.begin();
  656. MachineFrameInfo &MFI = MF.getFrameInfo();
  657. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  658. MachineModuleInfo &MMI = MF.getMMI();
  659. MCContext &Context = MMI.getContext();
  660. const TargetMachine &TM = MF.getTarget();
  661. const MCRegisterInfo *MRI = Context.getRegisterInfo();
  662. const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
  663. const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
  664. assert(!AFI->isThumb1OnlyFunction() &&
  665. "This emitPrologue does not support Thumb1!");
  666. bool isARM = !AFI->isThumbFunction();
  667. Align Alignment = STI.getFrameLowering()->getStackAlign();
  668. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
  669. unsigned NumBytes = MFI.getStackSize();
  670. const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
  671. int FPCXTSaveSize = 0;
  672. bool NeedsWinCFI = needsWinCFI(MF);
  673. // Debug location must be unknown since the first debug location is used
  674. // to determine the end of the prologue.
  675. DebugLoc dl;
  676. Register FramePtr = RegInfo->getFrameRegister(MF);
  677. // Determine the sizes of each callee-save spill areas and record which frame
  678. // belongs to which callee-save spill areas.
  679. unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
  680. int FramePtrSpillFI = 0;
  681. int D8SpillFI = 0;
  682. // All calls are tail calls in GHC calling conv, and functions have no
  683. // prologue/epilogue.
  684. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  685. return;
  686. StackAdjustingInsts DefCFAOffsetCandidates;
  687. bool HasFP = hasFP(MF);
  688. if (!AFI->hasStackFrame() &&
  689. (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
  690. if (NumBytes != 0) {
  691. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
  692. MachineInstr::FrameSetup);
  693. DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes, true);
  694. }
  695. if (!NeedsWinCFI)
  696. DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
  697. if (NeedsWinCFI && MBBI != MBB.begin()) {
  698. insertSEHRange(MBB, {}, MBBI, TII, MachineInstr::FrameSetup);
  699. BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_PrologEnd))
  700. .setMIFlag(MachineInstr::FrameSetup);
  701. MF.setHasWinCFI(true);
  702. }
  703. return;
  704. }
  705. // Determine spill area sizes.
  706. if (STI.splitFramePointerPush(MF)) {
  707. for (const CalleeSavedInfo &I : CSI) {
  708. Register Reg = I.getReg();
  709. int FI = I.getFrameIdx();
  710. switch (Reg) {
  711. case ARM::R11:
  712. case ARM::LR:
  713. if (Reg == FramePtr)
  714. FramePtrSpillFI = FI;
  715. GPRCS2Size += 4;
  716. break;
  717. case ARM::R0:
  718. case ARM::R1:
  719. case ARM::R2:
  720. case ARM::R3:
  721. case ARM::R4:
  722. case ARM::R5:
  723. case ARM::R6:
  724. case ARM::R7:
  725. case ARM::R8:
  726. case ARM::R9:
  727. case ARM::R10:
  728. case ARM::R12:
  729. GPRCS1Size += 4;
  730. break;
  731. case ARM::FPCXTNS:
  732. FPCXTSaveSize = 4;
  733. break;
  734. default:
  735. // This is a DPR. Exclude the aligned DPRCS2 spills.
  736. if (Reg == ARM::D8)
  737. D8SpillFI = FI;
  738. if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
  739. DPRCSSize += 8;
  740. }
  741. }
  742. } else {
  743. for (const CalleeSavedInfo &I : CSI) {
  744. Register Reg = I.getReg();
  745. int FI = I.getFrameIdx();
  746. switch (Reg) {
  747. case ARM::R8:
  748. case ARM::R9:
  749. case ARM::R10:
  750. case ARM::R11:
  751. case ARM::R12:
  752. if (STI.splitFramePushPop(MF)) {
  753. GPRCS2Size += 4;
  754. break;
  755. }
  756. [[fallthrough]];
  757. case ARM::R0:
  758. case ARM::R1:
  759. case ARM::R2:
  760. case ARM::R3:
  761. case ARM::R4:
  762. case ARM::R5:
  763. case ARM::R6:
  764. case ARM::R7:
  765. case ARM::LR:
  766. if (Reg == FramePtr)
  767. FramePtrSpillFI = FI;
  768. GPRCS1Size += 4;
  769. break;
  770. case ARM::FPCXTNS:
  771. FPCXTSaveSize = 4;
  772. break;
  773. default:
  774. // This is a DPR. Exclude the aligned DPRCS2 spills.
  775. if (Reg == ARM::D8)
  776. D8SpillFI = FI;
  777. if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
  778. DPRCSSize += 8;
  779. }
  780. }
  781. }
  782. MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
  783. // Move past the PAC computation.
  784. if (AFI->shouldSignReturnAddress())
  785. LastPush = MBBI++;
  786. // Move past FPCXT area.
  787. if (FPCXTSaveSize > 0) {
  788. LastPush = MBBI++;
  789. DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, true);
  790. }
  791. // Allocate the vararg register save area.
  792. if (ArgRegsSaveSize) {
  793. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
  794. MachineInstr::FrameSetup);
  795. LastPush = std::prev(MBBI);
  796. DefCFAOffsetCandidates.addInst(LastPush, ArgRegsSaveSize, true);
  797. }
  798. // Move past area 1.
  799. if (GPRCS1Size > 0) {
  800. GPRCS1Push = LastPush = MBBI++;
  801. DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
  802. }
  803. // Determine starting offsets of spill areas.
  804. unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize;
  805. unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size;
  806. unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
  807. Align DPRAlign = DPRCSSize ? std::min(Align(8), Alignment) : Align(4);
  808. unsigned DPRGapSize = GPRCS1Size + FPCXTSaveSize + ArgRegsSaveSize;
  809. if (!STI.splitFramePointerPush(MF)) {
  810. DPRGapSize += GPRCS2Size;
  811. }
  812. DPRGapSize %= DPRAlign.value();
  813. unsigned DPRCSOffset;
  814. if (STI.splitFramePointerPush(MF)) {
  815. DPRCSOffset = GPRCS1Offset - DPRGapSize - DPRCSSize;
  816. GPRCS2Offset = DPRCSOffset - GPRCS2Size;
  817. } else {
  818. DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
  819. }
  820. int FramePtrOffsetInPush = 0;
  821. if (HasFP) {
  822. int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
  823. assert(getMaxFPOffset(STI, *AFI, MF) <= FPOffset &&
  824. "Max FP estimation is wrong");
  825. FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize + FPCXTSaveSize;
  826. AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
  827. NumBytes);
  828. }
  829. AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
  830. AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
  831. AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
  832. // Move past area 2.
  833. if (GPRCS2Size > 0 && !STI.splitFramePointerPush(MF)) {
  834. GPRCS2Push = LastPush = MBBI++;
  835. DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
  836. }
  837. // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
  838. // .cfi_offset operations will reflect that.
  839. if (DPRGapSize) {
  840. assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
  841. if (LastPush != MBB.end() &&
  842. tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
  843. DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
  844. else {
  845. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
  846. MachineInstr::FrameSetup);
  847. DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
  848. }
  849. }
  850. // Move past area 3.
  851. if (DPRCSSize > 0) {
  852. // Since vpush register list cannot have gaps, there may be multiple vpush
  853. // instructions in the prologue.
  854. while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
  855. DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
  856. LastPush = MBBI++;
  857. }
  858. }
  859. // Move past the aligned DPRCS2 area.
  860. if (AFI->getNumAlignedDPRCS2Regs() > 0) {
  861. MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
  862. // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
  863. // leaves the stack pointer pointing to the DPRCS2 area.
  864. //
  865. // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
  866. NumBytes += MFI.getObjectOffset(D8SpillFI);
  867. } else
  868. NumBytes = DPRCSOffset;
  869. if (GPRCS2Size > 0 && STI.splitFramePointerPush(MF)) {
  870. GPRCS2Push = LastPush = MBBI++;
  871. DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
  872. }
  873. bool NeedsWinCFIStackAlloc = NeedsWinCFI;
  874. if (STI.splitFramePointerPush(MF) && HasFP)
  875. NeedsWinCFIStackAlloc = false;
  876. if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
  877. uint32_t NumWords = NumBytes >> 2;
  878. if (NumWords < 65536) {
  879. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
  880. .addImm(NumWords)
  881. .setMIFlags(MachineInstr::FrameSetup)
  882. .add(predOps(ARMCC::AL));
  883. } else {
  884. // Split into two instructions here, instead of using t2MOVi32imm,
  885. // to allow inserting accurate SEH instructions (including accurate
  886. // instruction size for each of them).
  887. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
  888. .addImm(NumWords & 0xffff)
  889. .setMIFlags(MachineInstr::FrameSetup)
  890. .add(predOps(ARMCC::AL));
  891. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVTi16), ARM::R4)
  892. .addReg(ARM::R4)
  893. .addImm(NumWords >> 16)
  894. .setMIFlags(MachineInstr::FrameSetup)
  895. .add(predOps(ARMCC::AL));
  896. }
  897. switch (TM.getCodeModel()) {
  898. case CodeModel::Tiny:
  899. llvm_unreachable("Tiny code model not available on ARM.");
  900. case CodeModel::Small:
  901. case CodeModel::Medium:
  902. case CodeModel::Kernel:
  903. BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
  904. .add(predOps(ARMCC::AL))
  905. .addExternalSymbol("__chkstk")
  906. .addReg(ARM::R4, RegState::Implicit)
  907. .setMIFlags(MachineInstr::FrameSetup);
  908. break;
  909. case CodeModel::Large:
  910. BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
  911. .addExternalSymbol("__chkstk")
  912. .setMIFlags(MachineInstr::FrameSetup);
  913. BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
  914. .add(predOps(ARMCC::AL))
  915. .addReg(ARM::R12, RegState::Kill)
  916. .addReg(ARM::R4, RegState::Implicit)
  917. .setMIFlags(MachineInstr::FrameSetup);
  918. break;
  919. }
  920. MachineInstrBuilder Instr, SEH;
  921. Instr = BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
  922. .addReg(ARM::SP, RegState::Kill)
  923. .addReg(ARM::R4, RegState::Kill)
  924. .setMIFlags(MachineInstr::FrameSetup)
  925. .add(predOps(ARMCC::AL))
  926. .add(condCodeOp());
  927. if (NeedsWinCFIStackAlloc) {
  928. SEH = BuildMI(MF, dl, TII.get(ARM::SEH_StackAlloc))
  929. .addImm(NumBytes)
  930. .addImm(/*Wide=*/1)
  931. .setMIFlags(MachineInstr::FrameSetup);
  932. MBB.insertAfter(Instr, SEH);
  933. }
  934. NumBytes = 0;
  935. }
  936. if (NumBytes) {
  937. // Adjust SP after all the callee-save spills.
  938. if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
  939. tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
  940. DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
  941. else {
  942. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
  943. MachineInstr::FrameSetup);
  944. DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
  945. }
  946. if (HasFP && isARM)
  947. // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
  948. // Note it's not safe to do this in Thumb2 mode because it would have
  949. // taken two instructions:
  950. // mov sp, r7
  951. // sub sp, #24
  952. // If an interrupt is taken between the two instructions, then sp is in
  953. // an inconsistent state (pointing to the middle of callee-saved area).
  954. // The interrupt handler can end up clobbering the registers.
  955. AFI->setShouldRestoreSPFromFP(true);
  956. }
  957. // Set FP to point to the stack slot that contains the previous FP.
  958. // For iOS, FP is R7, which has now been stored in spill area 1.
  959. // Otherwise, if this is not iOS, all the callee-saved registers go
  960. // into spill area 1, including the FP in R11. In either case, it
  961. // is in area one and the adjustment needs to take place just after
  962. // that push.
  963. // FIXME: The above is not necessary true when PACBTI is enabled.
  964. // AAPCS requires use of R11, and PACBTI gets in the way of regular pushes,
  965. // so FP ends up on area two.
  966. MachineBasicBlock::iterator AfterPush;
  967. if (HasFP) {
  968. AfterPush = std::next(GPRCS1Push);
  969. unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
  970. int FPOffset = PushSize + FramePtrOffsetInPush;
  971. if (STI.splitFramePointerPush(MF)) {
  972. AfterPush = std::next(GPRCS2Push);
  973. emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush, dl, TII,
  974. FramePtr, ARM::SP, 0, MachineInstr::FrameSetup);
  975. } else {
  976. emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush, dl, TII,
  977. FramePtr, ARM::SP, FPOffset,
  978. MachineInstr::FrameSetup);
  979. }
  980. if (!NeedsWinCFI) {
  981. if (FramePtrOffsetInPush + PushSize != 0) {
  982. unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
  983. nullptr, MRI->getDwarfRegNum(FramePtr, true),
  984. FPCXTSaveSize + ArgRegsSaveSize - FramePtrOffsetInPush));
  985. BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  986. .addCFIIndex(CFIIndex)
  987. .setMIFlags(MachineInstr::FrameSetup);
  988. } else {
  989. unsigned CFIIndex =
  990. MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
  991. nullptr, MRI->getDwarfRegNum(FramePtr, true)));
  992. BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  993. .addCFIIndex(CFIIndex)
  994. .setMIFlags(MachineInstr::FrameSetup);
  995. }
  996. }
  997. }
  998. // Emit a SEH opcode indicating the prologue end. The rest of the prologue
  999. // instructions below don't need to be replayed to unwind the stack.
  1000. if (NeedsWinCFI && MBBI != MBB.begin()) {
  1001. MachineBasicBlock::iterator End = MBBI;
  1002. if (HasFP && STI.splitFramePointerPush(MF))
  1003. End = AfterPush;
  1004. insertSEHRange(MBB, {}, End, TII, MachineInstr::FrameSetup);
  1005. BuildMI(MBB, End, dl, TII.get(ARM::SEH_PrologEnd))
  1006. .setMIFlag(MachineInstr::FrameSetup);
  1007. MF.setHasWinCFI(true);
  1008. }
  1009. // Now that the prologue's actual instructions are finalised, we can insert
  1010. // the necessary DWARF cf instructions to describe the situation. Start by
  1011. // recording where each register ended up:
  1012. if (GPRCS1Size > 0 && !NeedsWinCFI) {
  1013. MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
  1014. int CFIIndex;
  1015. for (const auto &Entry : CSI) {
  1016. Register Reg = Entry.getReg();
  1017. int FI = Entry.getFrameIdx();
  1018. switch (Reg) {
  1019. case ARM::R8:
  1020. case ARM::R9:
  1021. case ARM::R10:
  1022. case ARM::R11:
  1023. case ARM::R12:
  1024. if (STI.splitFramePushPop(MF))
  1025. break;
  1026. [[fallthrough]];
  1027. case ARM::R0:
  1028. case ARM::R1:
  1029. case ARM::R2:
  1030. case ARM::R3:
  1031. case ARM::R4:
  1032. case ARM::R5:
  1033. case ARM::R6:
  1034. case ARM::R7:
  1035. case ARM::LR:
  1036. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  1037. nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
  1038. BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1039. .addCFIIndex(CFIIndex)
  1040. .setMIFlags(MachineInstr::FrameSetup);
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. if (GPRCS2Size > 0 && !NeedsWinCFI) {
  1046. MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
  1047. for (const auto &Entry : CSI) {
  1048. Register Reg = Entry.getReg();
  1049. int FI = Entry.getFrameIdx();
  1050. switch (Reg) {
  1051. case ARM::R8:
  1052. case ARM::R9:
  1053. case ARM::R10:
  1054. case ARM::R11:
  1055. case ARM::R12:
  1056. if (STI.splitFramePushPop(MF)) {
  1057. unsigned DwarfReg = MRI->getDwarfRegNum(
  1058. Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg, true);
  1059. unsigned Offset = MFI.getObjectOffset(FI);
  1060. unsigned CFIIndex = MF.addFrameInst(
  1061. MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
  1062. BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1063. .addCFIIndex(CFIIndex)
  1064. .setMIFlags(MachineInstr::FrameSetup);
  1065. }
  1066. break;
  1067. }
  1068. }
  1069. }
  1070. if (DPRCSSize > 0 && !NeedsWinCFI) {
  1071. // Since vpush register list cannot have gaps, there may be multiple vpush
  1072. // instructions in the prologue.
  1073. MachineBasicBlock::iterator Pos = std::next(LastPush);
  1074. for (const auto &Entry : CSI) {
  1075. Register Reg = Entry.getReg();
  1076. int FI = Entry.getFrameIdx();
  1077. if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
  1078. (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
  1079. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  1080. unsigned Offset = MFI.getObjectOffset(FI);
  1081. unsigned CFIIndex = MF.addFrameInst(
  1082. MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
  1083. BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
  1084. .addCFIIndex(CFIIndex)
  1085. .setMIFlags(MachineInstr::FrameSetup);
  1086. }
  1087. }
  1088. }
  1089. // Now we can emit descriptions of where the canonical frame address was
  1090. // throughout the process. If we have a frame pointer, it takes over the job
  1091. // half-way through, so only the first few .cfi_def_cfa_offset instructions
  1092. // actually get emitted.
  1093. if (!NeedsWinCFI)
  1094. DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
  1095. if (STI.isTargetELF() && hasFP(MF))
  1096. MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
  1097. AFI->getFramePtrSpillOffset());
  1098. AFI->setFPCXTSaveAreaSize(FPCXTSaveSize);
  1099. AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
  1100. AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
  1101. AFI->setDPRCalleeSavedGapSize(DPRGapSize);
  1102. AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
  1103. // If we need dynamic stack realignment, do it here. Be paranoid and make
  1104. // sure if we also have VLAs, we have a base pointer for frame access.
  1105. // If aligned NEON registers were spilled, the stack has already been
  1106. // realigned.
  1107. if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) {
  1108. Align MaxAlign = MFI.getMaxAlign();
  1109. assert(!AFI->isThumb1OnlyFunction());
  1110. if (!AFI->isThumbFunction()) {
  1111. emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
  1112. false);
  1113. } else {
  1114. // We cannot use sp as source/dest register here, thus we're using r4 to
  1115. // perform the calculations. We're emitting the following sequence:
  1116. // mov r4, sp
  1117. // -- use emitAligningInstructions to produce best sequence to zero
  1118. // -- out lower bits in r4
  1119. // mov sp, r4
  1120. // FIXME: It will be better just to find spare register here.
  1121. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
  1122. .addReg(ARM::SP, RegState::Kill)
  1123. .add(predOps(ARMCC::AL));
  1124. emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
  1125. false);
  1126. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  1127. .addReg(ARM::R4, RegState::Kill)
  1128. .add(predOps(ARMCC::AL));
  1129. }
  1130. AFI->setShouldRestoreSPFromFP(true);
  1131. }
  1132. // If we need a base pointer, set it up here. It's whatever the value
  1133. // of the stack pointer is at this point. Any variable size objects
  1134. // will be allocated after this, so we can still use the base pointer
  1135. // to reference locals.
  1136. // FIXME: Clarify FrameSetup flags here.
  1137. if (RegInfo->hasBasePointer(MF)) {
  1138. if (isARM)
  1139. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
  1140. .addReg(ARM::SP)
  1141. .add(predOps(ARMCC::AL))
  1142. .add(condCodeOp());
  1143. else
  1144. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
  1145. .addReg(ARM::SP)
  1146. .add(predOps(ARMCC::AL));
  1147. }
  1148. // If the frame has variable sized objects then the epilogue must restore
  1149. // the sp from fp. We can assume there's an FP here since hasFP already
  1150. // checks for hasVarSizedObjects.
  1151. if (MFI.hasVarSizedObjects())
  1152. AFI->setShouldRestoreSPFromFP(true);
  1153. }
  1154. void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
  1155. MachineBasicBlock &MBB) const {
  1156. MachineFrameInfo &MFI = MF.getFrameInfo();
  1157. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1158. const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
  1159. const ARMBaseInstrInfo &TII =
  1160. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  1161. assert(!AFI->isThumb1OnlyFunction() &&
  1162. "This emitEpilogue does not support Thumb1!");
  1163. bool isARM = !AFI->isThumbFunction();
  1164. // Amount of stack space we reserved next to incoming args for either
  1165. // varargs registers or stack arguments in tail calls made by this function.
  1166. unsigned ReservedArgStack = AFI->getArgRegsSaveSize();
  1167. // How much of the stack used by incoming arguments this function is expected
  1168. // to restore in this particular epilogue.
  1169. int IncomingArgStackToRestore = getArgumentStackToRestore(MF, MBB);
  1170. int NumBytes = (int)MFI.getStackSize();
  1171. Register FramePtr = RegInfo->getFrameRegister(MF);
  1172. // All calls are tail calls in GHC calling conv, and functions have no
  1173. // prologue/epilogue.
  1174. if (MF.getFunction().getCallingConv() == CallingConv::GHC)
  1175. return;
  1176. // First put ourselves on the first (from top) terminator instructions.
  1177. MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
  1178. DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
  1179. MachineBasicBlock::iterator RangeStart;
  1180. if (!AFI->hasStackFrame()) {
  1181. if (MF.hasWinCFI()) {
  1182. BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart))
  1183. .setMIFlag(MachineInstr::FrameDestroy);
  1184. RangeStart = initMBBRange(MBB, MBBI);
  1185. }
  1186. if (NumBytes + IncomingArgStackToRestore != 0)
  1187. emitSPUpdate(isARM, MBB, MBBI, dl, TII,
  1188. NumBytes + IncomingArgStackToRestore,
  1189. MachineInstr::FrameDestroy);
  1190. } else {
  1191. // Unwind MBBI to point to first LDR / VLDRD.
  1192. if (MBBI != MBB.begin()) {
  1193. do {
  1194. --MBBI;
  1195. } while (MBBI != MBB.begin() &&
  1196. MBBI->getFlag(MachineInstr::FrameDestroy));
  1197. if (!MBBI->getFlag(MachineInstr::FrameDestroy))
  1198. ++MBBI;
  1199. }
  1200. if (MF.hasWinCFI()) {
  1201. BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart))
  1202. .setMIFlag(MachineInstr::FrameDestroy);
  1203. RangeStart = initMBBRange(MBB, MBBI);
  1204. }
  1205. // Move SP to start of FP callee save spill area.
  1206. NumBytes -= (ReservedArgStack +
  1207. AFI->getFPCXTSaveAreaSize() +
  1208. AFI->getGPRCalleeSavedArea1Size() +
  1209. AFI->getGPRCalleeSavedArea2Size() +
  1210. AFI->getDPRCalleeSavedGapSize() +
  1211. AFI->getDPRCalleeSavedAreaSize());
  1212. // Reset SP based on frame pointer only if the stack frame extends beyond
  1213. // frame pointer stack slot or target is ELF and the function has FP.
  1214. if (AFI->shouldRestoreSPFromFP()) {
  1215. NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
  1216. if (NumBytes) {
  1217. if (isARM)
  1218. emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
  1219. ARMCC::AL, 0, TII,
  1220. MachineInstr::FrameDestroy);
  1221. else {
  1222. // It's not possible to restore SP from FP in a single instruction.
  1223. // For iOS, this looks like:
  1224. // mov sp, r7
  1225. // sub sp, #24
  1226. // This is bad, if an interrupt is taken after the mov, sp is in an
  1227. // inconsistent state.
  1228. // Use the first callee-saved register as a scratch register.
  1229. assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
  1230. "No scratch register to restore SP from FP!");
  1231. emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
  1232. ARMCC::AL, 0, TII, MachineInstr::FrameDestroy);
  1233. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  1234. .addReg(ARM::R4)
  1235. .add(predOps(ARMCC::AL))
  1236. .setMIFlag(MachineInstr::FrameDestroy);
  1237. }
  1238. } else {
  1239. // Thumb2 or ARM.
  1240. if (isARM)
  1241. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
  1242. .addReg(FramePtr)
  1243. .add(predOps(ARMCC::AL))
  1244. .add(condCodeOp())
  1245. .setMIFlag(MachineInstr::FrameDestroy);
  1246. else
  1247. BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  1248. .addReg(FramePtr)
  1249. .add(predOps(ARMCC::AL))
  1250. .setMIFlag(MachineInstr::FrameDestroy);
  1251. }
  1252. } else if (NumBytes &&
  1253. !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
  1254. emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
  1255. MachineInstr::FrameDestroy);
  1256. // Increment past our save areas.
  1257. if (AFI->getGPRCalleeSavedArea2Size() && STI.splitFramePointerPush(MF))
  1258. MBBI++;
  1259. if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
  1260. MBBI++;
  1261. // Since vpop register list cannot have gaps, there may be multiple vpop
  1262. // instructions in the epilogue.
  1263. while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
  1264. MBBI++;
  1265. }
  1266. if (AFI->getDPRCalleeSavedGapSize()) {
  1267. assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
  1268. "unexpected DPR alignment gap");
  1269. emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(),
  1270. MachineInstr::FrameDestroy);
  1271. }
  1272. if (AFI->getGPRCalleeSavedArea2Size() && !STI.splitFramePointerPush(MF))
  1273. MBBI++;
  1274. if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
  1275. if (ReservedArgStack || IncomingArgStackToRestore) {
  1276. assert((int)ReservedArgStack + IncomingArgStackToRestore >= 0 &&
  1277. "attempting to restore negative stack amount");
  1278. emitSPUpdate(isARM, MBB, MBBI, dl, TII,
  1279. ReservedArgStack + IncomingArgStackToRestore,
  1280. MachineInstr::FrameDestroy);
  1281. }
  1282. // Validate PAC, It should have been already popped into R12. For CMSE entry
  1283. // function, the validation instruction is emitted during expansion of the
  1284. // tBXNS_RET, since the validation must use the value of SP at function
  1285. // entry, before saving, resp. after restoring, FPCXTNS.
  1286. if (AFI->shouldSignReturnAddress() && !AFI->isCmseNSEntryFunction())
  1287. BuildMI(MBB, MBBI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2AUT));
  1288. }
  1289. if (MF.hasWinCFI()) {
  1290. insertSEHRange(MBB, RangeStart, MBB.end(), TII, MachineInstr::FrameDestroy);
  1291. BuildMI(MBB, MBB.end(), dl, TII.get(ARM::SEH_EpilogEnd))
  1292. .setMIFlag(MachineInstr::FrameDestroy);
  1293. }
  1294. }
  1295. /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
  1296. /// debug info. It's the same as what we use for resolving the code-gen
  1297. /// references for now. FIXME: This can go wrong when references are
  1298. /// SP-relative and simple call frames aren't used.
  1299. StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF,
  1300. int FI,
  1301. Register &FrameReg) const {
  1302. return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0));
  1303. }
  1304. int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
  1305. int FI, Register &FrameReg,
  1306. int SPAdj) const {
  1307. const MachineFrameInfo &MFI = MF.getFrameInfo();
  1308. const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
  1309. MF.getSubtarget().getRegisterInfo());
  1310. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1311. int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
  1312. int FPOffset = Offset - AFI->getFramePtrSpillOffset();
  1313. bool isFixed = MFI.isFixedObjectIndex(FI);
  1314. FrameReg = ARM::SP;
  1315. Offset += SPAdj;
  1316. // SP can move around if there are allocas. We may also lose track of SP
  1317. // when emergency spilling inside a non-reserved call frame setup.
  1318. bool hasMovingSP = !hasReservedCallFrame(MF);
  1319. // When dynamically realigning the stack, use the frame pointer for
  1320. // parameters, and the stack/base pointer for locals.
  1321. if (RegInfo->hasStackRealignment(MF)) {
  1322. assert(hasFP(MF) && "dynamic stack realignment without a FP!");
  1323. if (isFixed) {
  1324. FrameReg = RegInfo->getFrameRegister(MF);
  1325. Offset = FPOffset;
  1326. } else if (hasMovingSP) {
  1327. assert(RegInfo->hasBasePointer(MF) &&
  1328. "VLAs and dynamic stack alignment, but missing base pointer!");
  1329. FrameReg = RegInfo->getBaseRegister();
  1330. Offset -= SPAdj;
  1331. }
  1332. return Offset;
  1333. }
  1334. // If there is a frame pointer, use it when we can.
  1335. if (hasFP(MF) && AFI->hasStackFrame()) {
  1336. // Use frame pointer to reference fixed objects. Use it for locals if
  1337. // there are VLAs (and thus the SP isn't reliable as a base).
  1338. if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
  1339. FrameReg = RegInfo->getFrameRegister(MF);
  1340. return FPOffset;
  1341. } else if (hasMovingSP) {
  1342. assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
  1343. if (AFI->isThumb2Function()) {
  1344. // Try to use the frame pointer if we can, else use the base pointer
  1345. // since it's available. This is handy for the emergency spill slot, in
  1346. // particular.
  1347. if (FPOffset >= -255 && FPOffset < 0) {
  1348. FrameReg = RegInfo->getFrameRegister(MF);
  1349. return FPOffset;
  1350. }
  1351. }
  1352. } else if (AFI->isThumbFunction()) {
  1353. // Prefer SP to base pointer, if the offset is suitably aligned and in
  1354. // range as the effective range of the immediate offset is bigger when
  1355. // basing off SP.
  1356. // Use add <rd>, sp, #<imm8>
  1357. // ldr <rd>, [sp, #<imm8>]
  1358. if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
  1359. return Offset;
  1360. // In Thumb2 mode, the negative offset is very limited. Try to avoid
  1361. // out of range references. ldr <rt>,[<rn>, #-<imm8>]
  1362. if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
  1363. FrameReg = RegInfo->getFrameRegister(MF);
  1364. return FPOffset;
  1365. }
  1366. } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
  1367. // Otherwise, use SP or FP, whichever is closer to the stack slot.
  1368. FrameReg = RegInfo->getFrameRegister(MF);
  1369. return FPOffset;
  1370. }
  1371. }
  1372. // Use the base pointer if we have one.
  1373. // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
  1374. // That can happen if we forced a base pointer for a large call frame.
  1375. if (RegInfo->hasBasePointer(MF)) {
  1376. FrameReg = RegInfo->getBaseRegister();
  1377. Offset -= SPAdj;
  1378. }
  1379. return Offset;
  1380. }
  1381. void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
  1382. MachineBasicBlock::iterator MI,
  1383. ArrayRef<CalleeSavedInfo> CSI,
  1384. unsigned StmOpc, unsigned StrOpc,
  1385. bool NoGap, bool (*Func)(unsigned, bool),
  1386. unsigned NumAlignedDPRCS2Regs,
  1387. unsigned MIFlags) const {
  1388. MachineFunction &MF = *MBB.getParent();
  1389. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  1390. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  1391. DebugLoc DL;
  1392. using RegAndKill = std::pair<unsigned, bool>;
  1393. SmallVector<RegAndKill, 4> Regs;
  1394. unsigned i = CSI.size();
  1395. while (i != 0) {
  1396. unsigned LastReg = 0;
  1397. for (; i != 0; --i) {
  1398. Register Reg = CSI[i-1].getReg();
  1399. if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
  1400. // D-registers in the aligned area DPRCS2 are NOT spilled here.
  1401. if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
  1402. continue;
  1403. const MachineRegisterInfo &MRI = MF.getRegInfo();
  1404. bool isLiveIn = MRI.isLiveIn(Reg);
  1405. if (!isLiveIn && !MRI.isReserved(Reg))
  1406. MBB.addLiveIn(Reg);
  1407. // If NoGap is true, push consecutive registers and then leave the rest
  1408. // for other instructions. e.g.
  1409. // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
  1410. if (NoGap && LastReg && LastReg != Reg-1)
  1411. break;
  1412. LastReg = Reg;
  1413. // Do not set a kill flag on values that are also marked as live-in. This
  1414. // happens with the @llvm-returnaddress intrinsic and with arguments
  1415. // passed in callee saved registers.
  1416. // Omitting the kill flags is conservatively correct even if the live-in
  1417. // is not used after all.
  1418. Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
  1419. }
  1420. if (Regs.empty())
  1421. continue;
  1422. llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
  1423. return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
  1424. });
  1425. if (Regs.size() > 1 || StrOpc== 0) {
  1426. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
  1427. .addReg(ARM::SP)
  1428. .setMIFlags(MIFlags)
  1429. .add(predOps(ARMCC::AL));
  1430. for (unsigned i = 0, e = Regs.size(); i < e; ++i)
  1431. MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
  1432. } else if (Regs.size() == 1) {
  1433. BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
  1434. .addReg(Regs[0].first, getKillRegState(Regs[0].second))
  1435. .addReg(ARM::SP)
  1436. .setMIFlags(MIFlags)
  1437. .addImm(-4)
  1438. .add(predOps(ARMCC::AL));
  1439. }
  1440. Regs.clear();
  1441. // Put any subsequent vpush instructions before this one: they will refer to
  1442. // higher register numbers so need to be pushed first in order to preserve
  1443. // monotonicity.
  1444. if (MI != MBB.begin())
  1445. --MI;
  1446. }
  1447. }
  1448. void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
  1449. MachineBasicBlock::iterator MI,
  1450. MutableArrayRef<CalleeSavedInfo> CSI,
  1451. unsigned LdmOpc, unsigned LdrOpc,
  1452. bool isVarArg, bool NoGap,
  1453. bool (*Func)(unsigned, bool),
  1454. unsigned NumAlignedDPRCS2Regs) const {
  1455. MachineFunction &MF = *MBB.getParent();
  1456. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  1457. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  1458. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1459. bool hasPAC = AFI->shouldSignReturnAddress();
  1460. DebugLoc DL;
  1461. bool isTailCall = false;
  1462. bool isInterrupt = false;
  1463. bool isTrap = false;
  1464. bool isCmseEntry = false;
  1465. if (MBB.end() != MI) {
  1466. DL = MI->getDebugLoc();
  1467. unsigned RetOpcode = MI->getOpcode();
  1468. isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
  1469. isInterrupt =
  1470. RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
  1471. isTrap =
  1472. RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
  1473. RetOpcode == ARM::tTRAP;
  1474. isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET);
  1475. }
  1476. SmallVector<unsigned, 4> Regs;
  1477. unsigned i = CSI.size();
  1478. while (i != 0) {
  1479. unsigned LastReg = 0;
  1480. bool DeleteRet = false;
  1481. for (; i != 0; --i) {
  1482. CalleeSavedInfo &Info = CSI[i-1];
  1483. Register Reg = Info.getReg();
  1484. if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
  1485. // The aligned reloads from area DPRCS2 are not inserted here.
  1486. if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
  1487. continue;
  1488. if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
  1489. !isCmseEntry && !isTrap && AFI->getArgumentStackToRestore() == 0 &&
  1490. STI.hasV5TOps() && MBB.succ_empty() && !hasPAC &&
  1491. !STI.splitFramePointerPush(MF)) {
  1492. Reg = ARM::PC;
  1493. // Fold the return instruction into the LDM.
  1494. DeleteRet = true;
  1495. LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
  1496. // We 'restore' LR into PC so it is not live out of the return block:
  1497. // Clear Restored bit.
  1498. Info.setRestored(false);
  1499. }
  1500. // If NoGap is true, pop consecutive registers and then leave the rest
  1501. // for other instructions. e.g.
  1502. // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
  1503. if (NoGap && LastReg && LastReg != Reg-1)
  1504. break;
  1505. LastReg = Reg;
  1506. Regs.push_back(Reg);
  1507. }
  1508. if (Regs.empty())
  1509. continue;
  1510. llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
  1511. return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
  1512. });
  1513. if (Regs.size() > 1 || LdrOpc == 0) {
  1514. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
  1515. .addReg(ARM::SP)
  1516. .add(predOps(ARMCC::AL))
  1517. .setMIFlags(MachineInstr::FrameDestroy);
  1518. for (unsigned i = 0, e = Regs.size(); i < e; ++i)
  1519. MIB.addReg(Regs[i], getDefRegState(true));
  1520. if (DeleteRet) {
  1521. if (MI != MBB.end()) {
  1522. MIB.copyImplicitOps(*MI);
  1523. MI->eraseFromParent();
  1524. }
  1525. }
  1526. MI = MIB;
  1527. } else if (Regs.size() == 1) {
  1528. // If we adjusted the reg to PC from LR above, switch it back here. We
  1529. // only do that for LDM.
  1530. if (Regs[0] == ARM::PC)
  1531. Regs[0] = ARM::LR;
  1532. MachineInstrBuilder MIB =
  1533. BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
  1534. .addReg(ARM::SP, RegState::Define)
  1535. .addReg(ARM::SP)
  1536. .setMIFlags(MachineInstr::FrameDestroy);
  1537. // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
  1538. // that refactoring is complete (eventually).
  1539. if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
  1540. MIB.addReg(0);
  1541. MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
  1542. } else
  1543. MIB.addImm(4);
  1544. MIB.add(predOps(ARMCC::AL));
  1545. }
  1546. Regs.clear();
  1547. // Put any subsequent vpop instructions after this one: they will refer to
  1548. // higher register numbers so need to be popped afterwards.
  1549. if (MI != MBB.end())
  1550. ++MI;
  1551. }
  1552. }
  1553. /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
  1554. /// starting from d8. Also insert stack realignment code and leave the stack
  1555. /// pointer pointing to the d8 spill slot.
  1556. static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
  1557. MachineBasicBlock::iterator MI,
  1558. unsigned NumAlignedDPRCS2Regs,
  1559. ArrayRef<CalleeSavedInfo> CSI,
  1560. const TargetRegisterInfo *TRI) {
  1561. MachineFunction &MF = *MBB.getParent();
  1562. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1563. DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
  1564. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  1565. MachineFrameInfo &MFI = MF.getFrameInfo();
  1566. // Mark the D-register spill slots as properly aligned. Since MFI computes
  1567. // stack slot layout backwards, this can actually mean that the d-reg stack
  1568. // slot offsets can be wrong. The offset for d8 will always be correct.
  1569. for (const CalleeSavedInfo &I : CSI) {
  1570. unsigned DNum = I.getReg() - ARM::D8;
  1571. if (DNum > NumAlignedDPRCS2Regs - 1)
  1572. continue;
  1573. int FI = I.getFrameIdx();
  1574. // The even-numbered registers will be 16-byte aligned, the odd-numbered
  1575. // registers will be 8-byte aligned.
  1576. MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16));
  1577. // The stack slot for D8 needs to be maximally aligned because this is
  1578. // actually the point where we align the stack pointer. MachineFrameInfo
  1579. // computes all offsets relative to the incoming stack pointer which is a
  1580. // bit weird when realigning the stack. Any extra padding for this
  1581. // over-alignment is not realized because the code inserted below adjusts
  1582. // the stack pointer by numregs * 8 before aligning the stack pointer.
  1583. if (DNum == 0)
  1584. MFI.setObjectAlignment(FI, MFI.getMaxAlign());
  1585. }
  1586. // Move the stack pointer to the d8 spill slot, and align it at the same
  1587. // time. Leave the stack slot address in the scratch register r4.
  1588. //
  1589. // sub r4, sp, #numregs * 8
  1590. // bic r4, r4, #align - 1
  1591. // mov sp, r4
  1592. //
  1593. bool isThumb = AFI->isThumbFunction();
  1594. assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
  1595. AFI->setShouldRestoreSPFromFP(true);
  1596. // sub r4, sp, #numregs * 8
  1597. // The immediate is <= 64, so it doesn't need any special encoding.
  1598. unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
  1599. BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  1600. .addReg(ARM::SP)
  1601. .addImm(8 * NumAlignedDPRCS2Regs)
  1602. .add(predOps(ARMCC::AL))
  1603. .add(condCodeOp());
  1604. Align MaxAlign = MF.getFrameInfo().getMaxAlign();
  1605. // We must set parameter MustBeSingleInstruction to true, since
  1606. // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
  1607. // stack alignment. Luckily, this can always be done since all ARM
  1608. // architecture versions that support Neon also support the BFC
  1609. // instruction.
  1610. emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
  1611. // mov sp, r4
  1612. // The stack pointer must be adjusted before spilling anything, otherwise
  1613. // the stack slots could be clobbered by an interrupt handler.
  1614. // Leave r4 live, it is used below.
  1615. Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
  1616. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
  1617. .addReg(ARM::R4)
  1618. .add(predOps(ARMCC::AL));
  1619. if (!isThumb)
  1620. MIB.add(condCodeOp());
  1621. // Now spill NumAlignedDPRCS2Regs registers starting from d8.
  1622. // r4 holds the stack slot address.
  1623. unsigned NextReg = ARM::D8;
  1624. // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
  1625. // The writeback is only needed when emitting two vst1.64 instructions.
  1626. if (NumAlignedDPRCS2Regs >= 6) {
  1627. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1628. &ARM::QQPRRegClass);
  1629. MBB.addLiveIn(SupReg);
  1630. BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
  1631. .addReg(ARM::R4, RegState::Kill)
  1632. .addImm(16)
  1633. .addReg(NextReg)
  1634. .addReg(SupReg, RegState::ImplicitKill)
  1635. .add(predOps(ARMCC::AL));
  1636. NextReg += 4;
  1637. NumAlignedDPRCS2Regs -= 4;
  1638. }
  1639. // We won't modify r4 beyond this point. It currently points to the next
  1640. // register to be spilled.
  1641. unsigned R4BaseReg = NextReg;
  1642. // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
  1643. if (NumAlignedDPRCS2Regs >= 4) {
  1644. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1645. &ARM::QQPRRegClass);
  1646. MBB.addLiveIn(SupReg);
  1647. BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
  1648. .addReg(ARM::R4)
  1649. .addImm(16)
  1650. .addReg(NextReg)
  1651. .addReg(SupReg, RegState::ImplicitKill)
  1652. .add(predOps(ARMCC::AL));
  1653. NextReg += 4;
  1654. NumAlignedDPRCS2Regs -= 4;
  1655. }
  1656. // 16-byte aligned vst1.64 with 2 d-regs.
  1657. if (NumAlignedDPRCS2Regs >= 2) {
  1658. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1659. &ARM::QPRRegClass);
  1660. MBB.addLiveIn(SupReg);
  1661. BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
  1662. .addReg(ARM::R4)
  1663. .addImm(16)
  1664. .addReg(SupReg)
  1665. .add(predOps(ARMCC::AL));
  1666. NextReg += 2;
  1667. NumAlignedDPRCS2Regs -= 2;
  1668. }
  1669. // Finally, use a vanilla vstr.64 for the odd last register.
  1670. if (NumAlignedDPRCS2Regs) {
  1671. MBB.addLiveIn(NextReg);
  1672. // vstr.64 uses addrmode5 which has an offset scale of 4.
  1673. BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
  1674. .addReg(NextReg)
  1675. .addReg(ARM::R4)
  1676. .addImm((NextReg - R4BaseReg) * 2)
  1677. .add(predOps(ARMCC::AL));
  1678. }
  1679. // The last spill instruction inserted should kill the scratch register r4.
  1680. std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
  1681. }
  1682. /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
  1683. /// iterator to the following instruction.
  1684. static MachineBasicBlock::iterator
  1685. skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
  1686. unsigned NumAlignedDPRCS2Regs) {
  1687. // sub r4, sp, #numregs * 8
  1688. // bic r4, r4, #align - 1
  1689. // mov sp, r4
  1690. ++MI; ++MI; ++MI;
  1691. assert(MI->mayStore() && "Expecting spill instruction");
  1692. // These switches all fall through.
  1693. switch(NumAlignedDPRCS2Regs) {
  1694. case 7:
  1695. ++MI;
  1696. assert(MI->mayStore() && "Expecting spill instruction");
  1697. [[fallthrough]];
  1698. default:
  1699. ++MI;
  1700. assert(MI->mayStore() && "Expecting spill instruction");
  1701. [[fallthrough]];
  1702. case 1:
  1703. case 2:
  1704. case 4:
  1705. assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
  1706. ++MI;
  1707. }
  1708. return MI;
  1709. }
  1710. /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
  1711. /// starting from d8. These instructions are assumed to execute while the
  1712. /// stack is still aligned, unlike the code inserted by emitPopInst.
  1713. static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
  1714. MachineBasicBlock::iterator MI,
  1715. unsigned NumAlignedDPRCS2Regs,
  1716. ArrayRef<CalleeSavedInfo> CSI,
  1717. const TargetRegisterInfo *TRI) {
  1718. MachineFunction &MF = *MBB.getParent();
  1719. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1720. DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
  1721. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  1722. // Find the frame index assigned to d8.
  1723. int D8SpillFI = 0;
  1724. for (const CalleeSavedInfo &I : CSI)
  1725. if (I.getReg() == ARM::D8) {
  1726. D8SpillFI = I.getFrameIdx();
  1727. break;
  1728. }
  1729. // Materialize the address of the d8 spill slot into the scratch register r4.
  1730. // This can be fairly complicated if the stack frame is large, so just use
  1731. // the normal frame index elimination mechanism to do it. This code runs as
  1732. // the initial part of the epilog where the stack and base pointers haven't
  1733. // been changed yet.
  1734. bool isThumb = AFI->isThumbFunction();
  1735. assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
  1736. unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
  1737. BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  1738. .addFrameIndex(D8SpillFI)
  1739. .addImm(0)
  1740. .add(predOps(ARMCC::AL))
  1741. .add(condCodeOp());
  1742. // Now restore NumAlignedDPRCS2Regs registers starting from d8.
  1743. unsigned NextReg = ARM::D8;
  1744. // 16-byte aligned vld1.64 with 4 d-regs and writeback.
  1745. if (NumAlignedDPRCS2Regs >= 6) {
  1746. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1747. &ARM::QQPRRegClass);
  1748. BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
  1749. .addReg(ARM::R4, RegState::Define)
  1750. .addReg(ARM::R4, RegState::Kill)
  1751. .addImm(16)
  1752. .addReg(SupReg, RegState::ImplicitDefine)
  1753. .add(predOps(ARMCC::AL));
  1754. NextReg += 4;
  1755. NumAlignedDPRCS2Regs -= 4;
  1756. }
  1757. // We won't modify r4 beyond this point. It currently points to the next
  1758. // register to be spilled.
  1759. unsigned R4BaseReg = NextReg;
  1760. // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
  1761. if (NumAlignedDPRCS2Regs >= 4) {
  1762. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1763. &ARM::QQPRRegClass);
  1764. BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
  1765. .addReg(ARM::R4)
  1766. .addImm(16)
  1767. .addReg(SupReg, RegState::ImplicitDefine)
  1768. .add(predOps(ARMCC::AL));
  1769. NextReg += 4;
  1770. NumAlignedDPRCS2Regs -= 4;
  1771. }
  1772. // 16-byte aligned vld1.64 with 2 d-regs.
  1773. if (NumAlignedDPRCS2Regs >= 2) {
  1774. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1775. &ARM::QPRRegClass);
  1776. BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
  1777. .addReg(ARM::R4)
  1778. .addImm(16)
  1779. .add(predOps(ARMCC::AL));
  1780. NextReg += 2;
  1781. NumAlignedDPRCS2Regs -= 2;
  1782. }
  1783. // Finally, use a vanilla vldr.64 for the remaining odd register.
  1784. if (NumAlignedDPRCS2Regs)
  1785. BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
  1786. .addReg(ARM::R4)
  1787. .addImm(2 * (NextReg - R4BaseReg))
  1788. .add(predOps(ARMCC::AL));
  1789. // Last store kills r4.
  1790. std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
  1791. }
  1792. bool ARMFrameLowering::spillCalleeSavedRegisters(
  1793. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  1794. ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  1795. if (CSI.empty())
  1796. return false;
  1797. MachineFunction &MF = *MBB.getParent();
  1798. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1799. unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
  1800. unsigned PushOneOpc = AFI->isThumbFunction() ?
  1801. ARM::t2STR_PRE : ARM::STR_PRE_IMM;
  1802. unsigned FltOpc = ARM::VSTMDDB_UPD;
  1803. unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
  1804. // Compute PAC in R12.
  1805. if (AFI->shouldSignReturnAddress()) {
  1806. BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2PAC))
  1807. .setMIFlags(MachineInstr::FrameSetup);
  1808. }
  1809. // Save the non-secure floating point context.
  1810. if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) {
  1811. return C.getReg() == ARM::FPCXTNS;
  1812. })) {
  1813. BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre),
  1814. ARM::SP)
  1815. .addReg(ARM::SP)
  1816. .addImm(-4)
  1817. .add(predOps(ARMCC::AL));
  1818. }
  1819. if (STI.splitFramePointerPush(MF)) {
  1820. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false,
  1821. &isSplitFPArea1Register, 0, MachineInstr::FrameSetup);
  1822. emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
  1823. NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
  1824. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false,
  1825. &isSplitFPArea2Register, 0, MachineInstr::FrameSetup);
  1826. } else {
  1827. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register,
  1828. 0, MachineInstr::FrameSetup);
  1829. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register,
  1830. 0, MachineInstr::FrameSetup);
  1831. emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
  1832. NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
  1833. }
  1834. // The code above does not insert spill code for the aligned DPRCS2 registers.
  1835. // The stack realignment code will be inserted between the push instructions
  1836. // and these spills.
  1837. if (NumAlignedDPRCS2Regs)
  1838. emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
  1839. return true;
  1840. }
  1841. bool ARMFrameLowering::restoreCalleeSavedRegisters(
  1842. MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
  1843. MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
  1844. if (CSI.empty())
  1845. return false;
  1846. MachineFunction &MF = *MBB.getParent();
  1847. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1848. bool isVarArg = AFI->getArgRegsSaveSize() > 0;
  1849. unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
  1850. // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
  1851. // registers. Do that here instead.
  1852. if (NumAlignedDPRCS2Regs)
  1853. emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
  1854. unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
  1855. unsigned LdrOpc =
  1856. AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
  1857. unsigned FltOpc = ARM::VLDMDIA_UPD;
  1858. if (STI.splitFramePointerPush(MF)) {
  1859. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1860. &isSplitFPArea2Register, 0);
  1861. emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
  1862. NumAlignedDPRCS2Regs);
  1863. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1864. &isSplitFPArea1Register, 0);
  1865. } else {
  1866. emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
  1867. NumAlignedDPRCS2Regs);
  1868. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1869. &isARMArea2Register, 0);
  1870. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1871. &isARMArea1Register, 0);
  1872. }
  1873. return true;
  1874. }
  1875. // FIXME: Make generic?
  1876. static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
  1877. const ARMBaseInstrInfo &TII) {
  1878. unsigned FnSize = 0;
  1879. for (auto &MBB : MF) {
  1880. for (auto &MI : MBB)
  1881. FnSize += TII.getInstSizeInBytes(MI);
  1882. }
  1883. if (MF.getJumpTableInfo())
  1884. for (auto &Table: MF.getJumpTableInfo()->getJumpTables())
  1885. FnSize += Table.MBBs.size() * 4;
  1886. FnSize += MF.getConstantPool()->getConstants().size() * 4;
  1887. return FnSize;
  1888. }
  1889. /// estimateRSStackSizeLimit - Look at each instruction that references stack
  1890. /// frames and return the stack size limit beyond which some of these
  1891. /// instructions will require a scratch register during their expansion later.
  1892. // FIXME: Move to TII?
  1893. static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
  1894. const TargetFrameLowering *TFI,
  1895. bool &HasNonSPFrameIndex) {
  1896. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1897. const ARMBaseInstrInfo &TII =
  1898. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  1899. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  1900. unsigned Limit = (1 << 12) - 1;
  1901. for (auto &MBB : MF) {
  1902. for (auto &MI : MBB) {
  1903. if (MI.isDebugInstr())
  1904. continue;
  1905. for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
  1906. if (!MI.getOperand(i).isFI())
  1907. continue;
  1908. // When using ADDri to get the address of a stack object, 255 is the
  1909. // largest offset guaranteed to fit in the immediate offset.
  1910. if (MI.getOpcode() == ARM::ADDri) {
  1911. Limit = std::min(Limit, (1U << 8) - 1);
  1912. break;
  1913. }
  1914. // t2ADDri will not require an extra register, it can reuse the
  1915. // destination.
  1916. if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
  1917. break;
  1918. const MCInstrDesc &MCID = MI.getDesc();
  1919. const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF);
  1920. if (RegClass && !RegClass->contains(ARM::SP))
  1921. HasNonSPFrameIndex = true;
  1922. // Otherwise check the addressing mode.
  1923. switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
  1924. case ARMII::AddrMode_i12:
  1925. case ARMII::AddrMode2:
  1926. // Default 12 bit limit.
  1927. break;
  1928. case ARMII::AddrMode3:
  1929. case ARMII::AddrModeT2_i8neg:
  1930. Limit = std::min(Limit, (1U << 8) - 1);
  1931. break;
  1932. case ARMII::AddrMode5FP16:
  1933. Limit = std::min(Limit, ((1U << 8) - 1) * 2);
  1934. break;
  1935. case ARMII::AddrMode5:
  1936. case ARMII::AddrModeT2_i8s4:
  1937. case ARMII::AddrModeT2_ldrex:
  1938. Limit = std::min(Limit, ((1U << 8) - 1) * 4);
  1939. break;
  1940. case ARMII::AddrModeT2_i12:
  1941. // i12 supports only positive offset so these will be converted to
  1942. // i8 opcodes. See llvm::rewriteT2FrameIndex.
  1943. if (TFI->hasFP(MF) && AFI->hasStackFrame())
  1944. Limit = std::min(Limit, (1U << 8) - 1);
  1945. break;
  1946. case ARMII::AddrMode4:
  1947. case ARMII::AddrMode6:
  1948. // Addressing modes 4 & 6 (load/store) instructions can't encode an
  1949. // immediate offset for stack references.
  1950. return 0;
  1951. case ARMII::AddrModeT2_i7:
  1952. Limit = std::min(Limit, ((1U << 7) - 1) * 1);
  1953. break;
  1954. case ARMII::AddrModeT2_i7s2:
  1955. Limit = std::min(Limit, ((1U << 7) - 1) * 2);
  1956. break;
  1957. case ARMII::AddrModeT2_i7s4:
  1958. Limit = std::min(Limit, ((1U << 7) - 1) * 4);
  1959. break;
  1960. default:
  1961. llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
  1962. }
  1963. break; // At most one FI per instruction
  1964. }
  1965. }
  1966. }
  1967. return Limit;
  1968. }
  1969. // In functions that realign the stack, it can be an advantage to spill the
  1970. // callee-saved vector registers after realigning the stack. The vst1 and vld1
  1971. // instructions take alignment hints that can improve performance.
  1972. static void
  1973. checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
  1974. MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
  1975. if (!SpillAlignedNEONRegs)
  1976. return;
  1977. // Naked functions don't spill callee-saved registers.
  1978. if (MF.getFunction().hasFnAttribute(Attribute::Naked))
  1979. return;
  1980. // We are planning to use NEON instructions vst1 / vld1.
  1981. if (!MF.getSubtarget<ARMSubtarget>().hasNEON())
  1982. return;
  1983. // Don't bother if the default stack alignment is sufficiently high.
  1984. if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8))
  1985. return;
  1986. // Aligned spills require stack realignment.
  1987. if (!static_cast<const ARMBaseRegisterInfo *>(
  1988. MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
  1989. return;
  1990. // We always spill contiguous d-registers starting from d8. Count how many
  1991. // needs spilling. The register allocator will almost always use the
  1992. // callee-saved registers in order, but it can happen that there are holes in
  1993. // the range. Registers above the hole will be spilled to the standard DPRCS
  1994. // area.
  1995. unsigned NumSpills = 0;
  1996. for (; NumSpills < 8; ++NumSpills)
  1997. if (!SavedRegs.test(ARM::D8 + NumSpills))
  1998. break;
  1999. // Don't do this for just one d-register. It's not worth it.
  2000. if (NumSpills < 2)
  2001. return;
  2002. // Spill the first NumSpills D-registers after realigning the stack.
  2003. MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
  2004. // A scratch register is required for the vst1 / vld1 instructions.
  2005. SavedRegs.set(ARM::R4);
  2006. }
  2007. bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
  2008. // For CMSE entry functions, we want to save the FPCXT_NS immediately
  2009. // upon function entry (resp. restore it immmediately before return)
  2010. if (STI.hasV8_1MMainlineOps() &&
  2011. MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction())
  2012. return false;
  2013. // We are disabling shrinkwrapping for now when PAC is enabled, as
  2014. // shrinkwrapping can cause clobbering of r12 when the PAC code is
  2015. // generated. A follow-up patch will fix this in a more performant manner.
  2016. if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(
  2017. true /* SpillsLR */))
  2018. return false;
  2019. return true;
  2020. }
  2021. static bool requiresAAPCSFrameRecord(const MachineFunction &MF) {
  2022. const auto &Subtarget = MF.getSubtarget<ARMSubtarget>();
  2023. return Subtarget.createAAPCSFrameChainLeaf() ||
  2024. (Subtarget.createAAPCSFrameChain() && MF.getFrameInfo().hasCalls());
  2025. }
  2026. // Thumb1 may require a spill when storing to a frame index through FP, for
  2027. // cases where FP is a high register (R11). This scans the function for cases
  2028. // where this may happen.
  2029. static bool canSpillOnFrameIndexAccess(const MachineFunction &MF,
  2030. const TargetFrameLowering &TFI) {
  2031. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  2032. if (!AFI->isThumb1OnlyFunction())
  2033. return false;
  2034. for (const auto &MBB : MF)
  2035. for (const auto &MI : MBB)
  2036. if (MI.getOpcode() == ARM::tSTRspi || MI.getOpcode() == ARM::tSTRi)
  2037. for (const auto &Op : MI.operands())
  2038. if (Op.isFI()) {
  2039. Register Reg;
  2040. TFI.getFrameIndexReference(MF, Op.getIndex(), Reg);
  2041. if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::SP)
  2042. return true;
  2043. }
  2044. return false;
  2045. }
  2046. void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
  2047. BitVector &SavedRegs,
  2048. RegScavenger *RS) const {
  2049. TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
  2050. // This tells PEI to spill the FP as if it is any other callee-save register
  2051. // to take advantage the eliminateFrameIndex machinery. This also ensures it
  2052. // is spilled in the order specified by getCalleeSavedRegs() to make it easier
  2053. // to combine multiple loads / stores.
  2054. bool CanEliminateFrame = !(requiresAAPCSFrameRecord(MF) && hasFP(MF));
  2055. bool CS1Spilled = false;
  2056. bool LRSpilled = false;
  2057. unsigned NumGPRSpills = 0;
  2058. unsigned NumFPRSpills = 0;
  2059. SmallVector<unsigned, 4> UnspilledCS1GPRs;
  2060. SmallVector<unsigned, 4> UnspilledCS2GPRs;
  2061. const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
  2062. MF.getSubtarget().getRegisterInfo());
  2063. const ARMBaseInstrInfo &TII =
  2064. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  2065. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  2066. MachineFrameInfo &MFI = MF.getFrameInfo();
  2067. MachineRegisterInfo &MRI = MF.getRegInfo();
  2068. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  2069. (void)TRI; // Silence unused warning in non-assert builds.
  2070. Register FramePtr = RegInfo->getFrameRegister(MF);
  2071. // Spill R4 if Thumb2 function requires stack realignment - it will be used as
  2072. // scratch register. Also spill R4 if Thumb2 function has varsized objects,
  2073. // since it's not always possible to restore sp from fp in a single
  2074. // instruction.
  2075. // FIXME: It will be better just to find spare register here.
  2076. if (AFI->isThumb2Function() &&
  2077. (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)))
  2078. SavedRegs.set(ARM::R4);
  2079. // If a stack probe will be emitted, spill R4 and LR, since they are
  2080. // clobbered by the stack probe call.
  2081. // This estimate should be a safe, conservative estimate. The actual
  2082. // stack probe is enabled based on the size of the local objects;
  2083. // this estimate also includes the varargs store size.
  2084. if (STI.isTargetWindows() &&
  2085. WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
  2086. SavedRegs.set(ARM::R4);
  2087. SavedRegs.set(ARM::LR);
  2088. }
  2089. if (AFI->isThumb1OnlyFunction()) {
  2090. // Spill LR if Thumb1 function uses variable length argument lists.
  2091. if (AFI->getArgRegsSaveSize() > 0)
  2092. SavedRegs.set(ARM::LR);
  2093. // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
  2094. // requires stack alignment. We don't know for sure what the stack size
  2095. // will be, but for this, an estimate is good enough. If there anything
  2096. // changes it, it'll be a spill, which implies we've used all the registers
  2097. // and so R4 is already used, so not marking it here will be OK.
  2098. // FIXME: It will be better just to find spare register here.
  2099. if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) ||
  2100. MFI.estimateStackSize(MF) > 508)
  2101. SavedRegs.set(ARM::R4);
  2102. }
  2103. // See if we can spill vector registers to aligned stack.
  2104. checkNumAlignedDPRCS2Regs(MF, SavedRegs);
  2105. // Spill the BasePtr if it's used.
  2106. if (RegInfo->hasBasePointer(MF))
  2107. SavedRegs.set(RegInfo->getBaseRegister());
  2108. // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
  2109. if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
  2110. CanEliminateFrame = false;
  2111. // Don't spill FP if the frame can be eliminated. This is determined
  2112. // by scanning the callee-save registers to see if any is modified.
  2113. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
  2114. for (unsigned i = 0; CSRegs[i]; ++i) {
  2115. unsigned Reg = CSRegs[i];
  2116. bool Spilled = false;
  2117. if (SavedRegs.test(Reg)) {
  2118. Spilled = true;
  2119. CanEliminateFrame = false;
  2120. }
  2121. if (!ARM::GPRRegClass.contains(Reg)) {
  2122. if (Spilled) {
  2123. if (ARM::SPRRegClass.contains(Reg))
  2124. NumFPRSpills++;
  2125. else if (ARM::DPRRegClass.contains(Reg))
  2126. NumFPRSpills += 2;
  2127. else if (ARM::QPRRegClass.contains(Reg))
  2128. NumFPRSpills += 4;
  2129. }
  2130. continue;
  2131. }
  2132. if (Spilled) {
  2133. NumGPRSpills++;
  2134. if (!STI.splitFramePushPop(MF)) {
  2135. if (Reg == ARM::LR)
  2136. LRSpilled = true;
  2137. CS1Spilled = true;
  2138. continue;
  2139. }
  2140. // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
  2141. switch (Reg) {
  2142. case ARM::LR:
  2143. LRSpilled = true;
  2144. [[fallthrough]];
  2145. case ARM::R0: case ARM::R1:
  2146. case ARM::R2: case ARM::R3:
  2147. case ARM::R4: case ARM::R5:
  2148. case ARM::R6: case ARM::R7:
  2149. CS1Spilled = true;
  2150. break;
  2151. default:
  2152. break;
  2153. }
  2154. } else {
  2155. if (!STI.splitFramePushPop(MF)) {
  2156. UnspilledCS1GPRs.push_back(Reg);
  2157. continue;
  2158. }
  2159. switch (Reg) {
  2160. case ARM::R0: case ARM::R1:
  2161. case ARM::R2: case ARM::R3:
  2162. case ARM::R4: case ARM::R5:
  2163. case ARM::R6: case ARM::R7:
  2164. case ARM::LR:
  2165. UnspilledCS1GPRs.push_back(Reg);
  2166. break;
  2167. default:
  2168. UnspilledCS2GPRs.push_back(Reg);
  2169. break;
  2170. }
  2171. }
  2172. }
  2173. bool ForceLRSpill = false;
  2174. if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
  2175. unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII);
  2176. // Force LR to be spilled if the Thumb function size is > 2048. This enables
  2177. // use of BL to implement far jump.
  2178. if (FnSize >= (1 << 11)) {
  2179. CanEliminateFrame = false;
  2180. ForceLRSpill = true;
  2181. }
  2182. }
  2183. // If any of the stack slot references may be out of range of an immediate
  2184. // offset, make sure a register (or a spill slot) is available for the
  2185. // register scavenger. Note that if we're indexing off the frame pointer, the
  2186. // effective stack size is 4 bytes larger since the FP points to the stack
  2187. // slot of the previous FP. Also, if we have variable sized objects in the
  2188. // function, stack slot references will often be negative, and some of
  2189. // our instructions are positive-offset only, so conservatively consider
  2190. // that case to want a spill slot (or register) as well. Similarly, if
  2191. // the function adjusts the stack pointer during execution and the
  2192. // adjustments aren't already part of our stack size estimate, our offset
  2193. // calculations may be off, so be conservative.
  2194. // FIXME: We could add logic to be more precise about negative offsets
  2195. // and which instructions will need a scratch register for them. Is it
  2196. // worth the effort and added fragility?
  2197. unsigned EstimatedStackSize =
  2198. MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
  2199. // Determine biggest (positive) SP offset in MachineFrameInfo.
  2200. int MaxFixedOffset = 0;
  2201. for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
  2202. int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
  2203. MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
  2204. }
  2205. bool HasFP = hasFP(MF);
  2206. if (HasFP) {
  2207. if (AFI->hasStackFrame())
  2208. EstimatedStackSize += 4;
  2209. } else {
  2210. // If FP is not used, SP will be used to access arguments, so count the
  2211. // size of arguments into the estimation.
  2212. EstimatedStackSize += MaxFixedOffset;
  2213. }
  2214. EstimatedStackSize += 16; // For possible paddings.
  2215. unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
  2216. bool HasNonSPFrameIndex = false;
  2217. if (AFI->isThumb1OnlyFunction()) {
  2218. // For Thumb1, don't bother to iterate over the function. The only
  2219. // instruction that requires an emergency spill slot is a store to a
  2220. // frame index.
  2221. //
  2222. // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
  2223. // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
  2224. // a 5-bit unsigned immediate.
  2225. //
  2226. // We could try to check if the function actually contains a tSTRspi
  2227. // that might need the spill slot, but it's not really important.
  2228. // Functions with VLAs or extremely large call frames are rare, and
  2229. // if a function is allocating more than 1KB of stack, an extra 4-byte
  2230. // slot probably isn't relevant.
  2231. //
  2232. // A special case is the scenario where r11 is used as FP, where accesses
  2233. // to a frame index will require its value to be moved into a low reg.
  2234. // This is handled later on, once we are able to determine if we have any
  2235. // fp-relative accesses.
  2236. if (RegInfo->hasBasePointer(MF))
  2237. EstimatedRSStackSizeLimit = (1U << 5) * 4;
  2238. else
  2239. EstimatedRSStackSizeLimit = (1U << 8) * 4;
  2240. EstimatedRSFixedSizeLimit = (1U << 5) * 4;
  2241. } else {
  2242. EstimatedRSStackSizeLimit =
  2243. estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
  2244. EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
  2245. }
  2246. // Final estimate of whether sp or bp-relative accesses might require
  2247. // scavenging.
  2248. bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
  2249. // If the stack pointer moves and we don't have a base pointer, the
  2250. // estimate logic doesn't work. The actual offsets might be larger when
  2251. // we're constructing a call frame, or we might need to use negative
  2252. // offsets from fp.
  2253. bool HasMovingSP = MFI.hasVarSizedObjects() ||
  2254. (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
  2255. bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
  2256. // If we have a frame pointer, we assume arguments will be accessed
  2257. // relative to the frame pointer. Check whether fp-relative accesses to
  2258. // arguments require scavenging.
  2259. //
  2260. // We could do slightly better on Thumb1; in some cases, an sp-relative
  2261. // offset would be legal even though an fp-relative offset is not.
  2262. int MaxFPOffset = getMaxFPOffset(STI, *AFI, MF);
  2263. bool HasLargeArgumentList =
  2264. HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
  2265. bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
  2266. HasLargeArgumentList || HasNonSPFrameIndex;
  2267. LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
  2268. << "; EstimatedStack: " << EstimatedStackSize
  2269. << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
  2270. << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
  2271. if (BigFrameOffsets ||
  2272. !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
  2273. AFI->setHasStackFrame(true);
  2274. if (HasFP) {
  2275. SavedRegs.set(FramePtr);
  2276. // If the frame pointer is required by the ABI, also spill LR so that we
  2277. // emit a complete frame record.
  2278. if ((requiresAAPCSFrameRecord(MF) ||
  2279. MF.getTarget().Options.DisableFramePointerElim(MF)) &&
  2280. !LRSpilled) {
  2281. SavedRegs.set(ARM::LR);
  2282. LRSpilled = true;
  2283. NumGPRSpills++;
  2284. auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
  2285. if (LRPos != UnspilledCS1GPRs.end())
  2286. UnspilledCS1GPRs.erase(LRPos);
  2287. }
  2288. auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
  2289. if (FPPos != UnspilledCS1GPRs.end())
  2290. UnspilledCS1GPRs.erase(FPPos);
  2291. NumGPRSpills++;
  2292. if (FramePtr == ARM::R7)
  2293. CS1Spilled = true;
  2294. }
  2295. // This is true when we inserted a spill for a callee-save GPR which is
  2296. // not otherwise used by the function. This guaranteees it is possible
  2297. // to scavenge a register to hold the address of a stack slot. On Thumb1,
  2298. // the register must be a valid operand to tSTRi, i.e. r4-r7. For other
  2299. // subtargets, this is any GPR, i.e. r4-r11 or lr.
  2300. //
  2301. // If we don't insert a spill, we instead allocate an emergency spill
  2302. // slot, which can be used by scavenging to spill an arbitrary register.
  2303. //
  2304. // We currently don't try to figure out whether any specific instruction
  2305. // requires scavening an additional register.
  2306. bool ExtraCSSpill = false;
  2307. if (AFI->isThumb1OnlyFunction()) {
  2308. // For Thumb1-only targets, we need some low registers when we save and
  2309. // restore the high registers (which aren't allocatable, but could be
  2310. // used by inline assembly) because the push/pop instructions can not
  2311. // access high registers. If necessary, we might need to push more low
  2312. // registers to ensure that there is at least one free that can be used
  2313. // for the saving & restoring, and preferably we should ensure that as
  2314. // many as are needed are available so that fewer push/pop instructions
  2315. // are required.
  2316. // Low registers which are not currently pushed, but could be (r4-r7).
  2317. SmallVector<unsigned, 4> AvailableRegs;
  2318. // Unused argument registers (r0-r3) can be clobbered in the prologue for
  2319. // free.
  2320. int EntryRegDeficit = 0;
  2321. for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
  2322. if (!MF.getRegInfo().isLiveIn(Reg)) {
  2323. --EntryRegDeficit;
  2324. LLVM_DEBUG(dbgs()
  2325. << printReg(Reg, TRI)
  2326. << " is unused argument register, EntryRegDeficit = "
  2327. << EntryRegDeficit << "\n");
  2328. }
  2329. }
  2330. // Unused return registers can be clobbered in the epilogue for free.
  2331. int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
  2332. LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
  2333. << " return regs used, ExitRegDeficit = "
  2334. << ExitRegDeficit << "\n");
  2335. int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
  2336. LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
  2337. // r4-r6 can be used in the prologue if they are pushed by the first push
  2338. // instruction.
  2339. for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
  2340. if (SavedRegs.test(Reg)) {
  2341. --RegDeficit;
  2342. LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
  2343. << " is saved low register, RegDeficit = "
  2344. << RegDeficit << "\n");
  2345. } else {
  2346. AvailableRegs.push_back(Reg);
  2347. LLVM_DEBUG(
  2348. dbgs()
  2349. << printReg(Reg, TRI)
  2350. << " is non-saved low register, adding to AvailableRegs\n");
  2351. }
  2352. }
  2353. // r7 can be used if it is not being used as the frame pointer.
  2354. if (!HasFP || FramePtr != ARM::R7) {
  2355. if (SavedRegs.test(ARM::R7)) {
  2356. --RegDeficit;
  2357. LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
  2358. << RegDeficit << "\n");
  2359. } else {
  2360. AvailableRegs.push_back(ARM::R7);
  2361. LLVM_DEBUG(
  2362. dbgs()
  2363. << "%r7 is non-saved low register, adding to AvailableRegs\n");
  2364. }
  2365. }
  2366. // Each of r8-r11 needs to be copied to a low register, then pushed.
  2367. for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
  2368. if (SavedRegs.test(Reg)) {
  2369. ++RegDeficit;
  2370. LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
  2371. << " is saved high register, RegDeficit = "
  2372. << RegDeficit << "\n");
  2373. }
  2374. }
  2375. // LR can only be used by PUSH, not POP, and can't be used at all if the
  2376. // llvm.returnaddress intrinsic is used. This is only worth doing if we
  2377. // are more limited at function entry than exit.
  2378. if ((EntryRegDeficit > ExitRegDeficit) &&
  2379. !(MF.getRegInfo().isLiveIn(ARM::LR) &&
  2380. MF.getFrameInfo().isReturnAddressTaken())) {
  2381. if (SavedRegs.test(ARM::LR)) {
  2382. --RegDeficit;
  2383. LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
  2384. << RegDeficit << "\n");
  2385. } else {
  2386. AvailableRegs.push_back(ARM::LR);
  2387. LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
  2388. }
  2389. }
  2390. // If there are more high registers that need pushing than low registers
  2391. // available, push some more low registers so that we can use fewer push
  2392. // instructions. This might not reduce RegDeficit all the way to zero,
  2393. // because we can only guarantee that r4-r6 are available, but r8-r11 may
  2394. // need saving.
  2395. LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
  2396. for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
  2397. unsigned Reg = AvailableRegs.pop_back_val();
  2398. LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
  2399. << " to make up reg deficit\n");
  2400. SavedRegs.set(Reg);
  2401. NumGPRSpills++;
  2402. CS1Spilled = true;
  2403. assert(!MRI.isReserved(Reg) && "Should not be reserved");
  2404. if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
  2405. ExtraCSSpill = true;
  2406. UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
  2407. if (Reg == ARM::LR)
  2408. LRSpilled = true;
  2409. }
  2410. LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
  2411. << "\n");
  2412. }
  2413. // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
  2414. // restore LR in that case.
  2415. bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
  2416. // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
  2417. // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
  2418. if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
  2419. SavedRegs.set(ARM::LR);
  2420. NumGPRSpills++;
  2421. SmallVectorImpl<unsigned>::iterator LRPos;
  2422. LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
  2423. if (LRPos != UnspilledCS1GPRs.end())
  2424. UnspilledCS1GPRs.erase(LRPos);
  2425. ForceLRSpill = false;
  2426. if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
  2427. !AFI->isThumb1OnlyFunction())
  2428. ExtraCSSpill = true;
  2429. }
  2430. // If stack and double are 8-byte aligned and we are spilling an odd number
  2431. // of GPRs, spill one extra callee save GPR so we won't have to pad between
  2432. // the integer and double callee save areas.
  2433. LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
  2434. const Align TargetAlign = getStackAlign();
  2435. if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
  2436. if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
  2437. for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
  2438. unsigned Reg = UnspilledCS1GPRs[i];
  2439. // Don't spill high register if the function is thumb. In the case of
  2440. // Windows on ARM, accept R11 (frame pointer)
  2441. if (!AFI->isThumbFunction() ||
  2442. (STI.isTargetWindows() && Reg == ARM::R11) ||
  2443. isARMLowRegister(Reg) ||
  2444. (Reg == ARM::LR && !ExpensiveLRRestore)) {
  2445. SavedRegs.set(Reg);
  2446. LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
  2447. << " to make up alignment\n");
  2448. if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
  2449. !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
  2450. ExtraCSSpill = true;
  2451. break;
  2452. }
  2453. }
  2454. } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
  2455. unsigned Reg = UnspilledCS2GPRs.front();
  2456. SavedRegs.set(Reg);
  2457. LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
  2458. << " to make up alignment\n");
  2459. if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
  2460. ExtraCSSpill = true;
  2461. }
  2462. }
  2463. // Estimate if we might need to scavenge a register at some point in order
  2464. // to materialize a stack offset. If so, either spill one additional
  2465. // callee-saved register or reserve a special spill slot to facilitate
  2466. // register scavenging. Thumb1 needs a spill slot for stack pointer
  2467. // adjustments and for frame index accesses when FP is high register,
  2468. // even when the frame itself is small.
  2469. if (!ExtraCSSpill &&
  2470. (BigFrameOffsets || canSpillOnFrameIndexAccess(MF, *this))) {
  2471. // If any non-reserved CS register isn't spilled, just spill one or two
  2472. // extra. That should take care of it!
  2473. unsigned NumExtras = TargetAlign.value() / 4;
  2474. SmallVector<unsigned, 2> Extras;
  2475. while (NumExtras && !UnspilledCS1GPRs.empty()) {
  2476. unsigned Reg = UnspilledCS1GPRs.pop_back_val();
  2477. if (!MRI.isReserved(Reg) &&
  2478. (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
  2479. Extras.push_back(Reg);
  2480. NumExtras--;
  2481. }
  2482. }
  2483. // For non-Thumb1 functions, also check for hi-reg CS registers
  2484. if (!AFI->isThumb1OnlyFunction()) {
  2485. while (NumExtras && !UnspilledCS2GPRs.empty()) {
  2486. unsigned Reg = UnspilledCS2GPRs.pop_back_val();
  2487. if (!MRI.isReserved(Reg)) {
  2488. Extras.push_back(Reg);
  2489. NumExtras--;
  2490. }
  2491. }
  2492. }
  2493. if (NumExtras == 0) {
  2494. for (unsigned Reg : Extras) {
  2495. SavedRegs.set(Reg);
  2496. if (!MRI.isPhysRegUsed(Reg))
  2497. ExtraCSSpill = true;
  2498. }
  2499. }
  2500. if (!ExtraCSSpill && RS) {
  2501. // Reserve a slot closest to SP or frame pointer.
  2502. LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
  2503. const TargetRegisterClass &RC = ARM::GPRRegClass;
  2504. unsigned Size = TRI->getSpillSize(RC);
  2505. Align Alignment = TRI->getSpillAlign(RC);
  2506. RS->addScavengingFrameIndex(
  2507. MFI.CreateStackObject(Size, Alignment, false));
  2508. }
  2509. }
  2510. }
  2511. if (ForceLRSpill)
  2512. SavedRegs.set(ARM::LR);
  2513. AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
  2514. }
  2515. void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
  2516. BitVector &SavedRegs) const {
  2517. TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
  2518. // If we have the "returned" parameter attribute which guarantees that we
  2519. // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
  2520. // record that fact for IPRA.
  2521. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  2522. if (AFI->getPreservesR0())
  2523. SavedRegs.set(ARM::R0);
  2524. }
  2525. bool ARMFrameLowering::assignCalleeSavedSpillSlots(
  2526. MachineFunction &MF, const TargetRegisterInfo *TRI,
  2527. std::vector<CalleeSavedInfo> &CSI) const {
  2528. // For CMSE entry functions, handle floating-point context as if it was a
  2529. // callee-saved register.
  2530. if (STI.hasV8_1MMainlineOps() &&
  2531. MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) {
  2532. CSI.emplace_back(ARM::FPCXTNS);
  2533. CSI.back().setRestored(false);
  2534. }
  2535. // For functions, which sign their return address, upon function entry, the
  2536. // return address PAC is computed in R12. Treat R12 as a callee-saved register
  2537. // in this case.
  2538. const auto &AFI = *MF.getInfo<ARMFunctionInfo>();
  2539. if (AFI.shouldSignReturnAddress()) {
  2540. // The order of register must match the order we push them, because the
  2541. // PEI assigns frame indices in that order. When compiling for return
  2542. // address sign and authenication, we use split push, therefore the orders
  2543. // we want are:
  2544. // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8
  2545. CSI.insert(find_if(CSI,
  2546. [=](const auto &CS) {
  2547. Register Reg = CS.getReg();
  2548. return Reg == ARM::R10 || Reg == ARM::R11 ||
  2549. Reg == ARM::R8 || Reg == ARM::R9 ||
  2550. ARM::DPRRegClass.contains(Reg);
  2551. }),
  2552. CalleeSavedInfo(ARM::R12));
  2553. }
  2554. return false;
  2555. }
  2556. const TargetFrameLowering::SpillSlot *
  2557. ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
  2558. static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}};
  2559. NumEntries = std::size(FixedSpillOffsets);
  2560. return FixedSpillOffsets;
  2561. }
  2562. MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
  2563. MachineFunction &MF, MachineBasicBlock &MBB,
  2564. MachineBasicBlock::iterator I) const {
  2565. const ARMBaseInstrInfo &TII =
  2566. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  2567. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  2568. bool isARM = !AFI->isThumbFunction();
  2569. DebugLoc dl = I->getDebugLoc();
  2570. unsigned Opc = I->getOpcode();
  2571. bool IsDestroy = Opc == TII.getCallFrameDestroyOpcode();
  2572. unsigned CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
  2573. assert(!AFI->isThumb1OnlyFunction() &&
  2574. "This eliminateCallFramePseudoInstr does not support Thumb1!");
  2575. int PIdx = I->findFirstPredOperandIdx();
  2576. ARMCC::CondCodes Pred = (PIdx == -1)
  2577. ? ARMCC::AL
  2578. : (ARMCC::CondCodes)I->getOperand(PIdx).getImm();
  2579. unsigned PredReg = TII.getFramePred(*I);
  2580. if (!hasReservedCallFrame(MF)) {
  2581. // Bail early if the callee is expected to do the adjustment.
  2582. if (IsDestroy && CalleePopAmount != -1U)
  2583. return MBB.erase(I);
  2584. // If we have alloca, convert as follows:
  2585. // ADJCALLSTACKDOWN -> sub, sp, sp, amount
  2586. // ADJCALLSTACKUP -> add, sp, sp, amount
  2587. unsigned Amount = TII.getFrameSize(*I);
  2588. if (Amount != 0) {
  2589. // We need to keep the stack aligned properly. To do this, we round the
  2590. // amount of space needed for the outgoing arguments up to the next
  2591. // alignment boundary.
  2592. Amount = alignSPAdjust(Amount);
  2593. if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
  2594. emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
  2595. Pred, PredReg);
  2596. } else {
  2597. assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
  2598. emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
  2599. Pred, PredReg);
  2600. }
  2601. }
  2602. } else if (CalleePopAmount != -1U) {
  2603. // If the calling convention demands that the callee pops arguments from the
  2604. // stack, we want to add it back if we have a reserved call frame.
  2605. emitSPUpdate(isARM, MBB, I, dl, TII, -CalleePopAmount,
  2606. MachineInstr::NoFlags, Pred, PredReg);
  2607. }
  2608. return MBB.erase(I);
  2609. }
  2610. /// Get the minimum constant for ARM that is greater than or equal to the
  2611. /// argument. In ARM, constants can have any value that can be produced by
  2612. /// rotating an 8-bit value to the right by an even number of bits within a
  2613. /// 32-bit word.
  2614. static uint32_t alignToARMConstant(uint32_t Value) {
  2615. unsigned Shifted = 0;
  2616. if (Value == 0)
  2617. return 0;
  2618. while (!(Value & 0xC0000000)) {
  2619. Value = Value << 2;
  2620. Shifted += 2;
  2621. }
  2622. bool Carry = (Value & 0x00FFFFFF);
  2623. Value = ((Value & 0xFF000000) >> 24) + Carry;
  2624. if (Value & 0x0000100)
  2625. Value = Value & 0x000001FC;
  2626. if (Shifted > 24)
  2627. Value = Value >> (Shifted - 24);
  2628. else
  2629. Value = Value << (24 - Shifted);
  2630. return Value;
  2631. }
  2632. // The stack limit in the TCB is set to this many bytes above the actual
  2633. // stack limit.
  2634. static const uint64_t kSplitStackAvailable = 256;
  2635. // Adjust the function prologue to enable split stacks. This currently only
  2636. // supports android and linux.
  2637. //
  2638. // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
  2639. // must be well defined in order to allow for consistent implementations of the
  2640. // __morestack helper function. The ABI is also not a normal ABI in that it
  2641. // doesn't follow the normal calling conventions because this allows the
  2642. // prologue of each function to be optimized further.
  2643. //
  2644. // Currently, the ABI looks like (when calling __morestack)
  2645. //
  2646. // * r4 holds the minimum stack size requested for this function call
  2647. // * r5 holds the stack size of the arguments to the function
  2648. // * the beginning of the function is 3 instructions after the call to
  2649. // __morestack
  2650. //
  2651. // Implementations of __morestack should use r4 to allocate a new stack, r5 to
  2652. // place the arguments on to the new stack, and the 3-instruction knowledge to
  2653. // jump directly to the body of the function when working on the new stack.
  2654. //
  2655. // An old (and possibly no longer compatible) implementation of __morestack for
  2656. // ARM can be found at [1].
  2657. //
  2658. // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
  2659. void ARMFrameLowering::adjustForSegmentedStacks(
  2660. MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
  2661. unsigned Opcode;
  2662. unsigned CFIIndex;
  2663. const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
  2664. bool Thumb = ST->isThumb();
  2665. bool Thumb2 = ST->isThumb2();
  2666. // Sadly, this currently doesn't support varargs, platforms other than
  2667. // android/linux. Note that thumb1/thumb2 are support for android/linux.
  2668. if (MF.getFunction().isVarArg())
  2669. report_fatal_error("Segmented stacks do not support vararg functions.");
  2670. if (!ST->isTargetAndroid() && !ST->isTargetLinux())
  2671. report_fatal_error("Segmented stacks not supported on this platform.");
  2672. MachineFrameInfo &MFI = MF.getFrameInfo();
  2673. MachineModuleInfo &MMI = MF.getMMI();
  2674. MCContext &Context = MMI.getContext();
  2675. const MCRegisterInfo *MRI = Context.getRegisterInfo();
  2676. const ARMBaseInstrInfo &TII =
  2677. *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
  2678. ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
  2679. DebugLoc DL;
  2680. if (!MFI.needsSplitStackProlog())
  2681. return;
  2682. uint64_t StackSize = MFI.getStackSize();
  2683. // Use R4 and R5 as scratch registers.
  2684. // We save R4 and R5 before use and restore them before leaving the function.
  2685. unsigned ScratchReg0 = ARM::R4;
  2686. unsigned ScratchReg1 = ARM::R5;
  2687. uint64_t AlignedStackSize;
  2688. MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
  2689. MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
  2690. MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
  2691. MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
  2692. MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
  2693. // Grab everything that reaches PrologueMBB to update there liveness as well.
  2694. SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
  2695. SmallVector<MachineBasicBlock *, 2> WalkList;
  2696. WalkList.push_back(&PrologueMBB);
  2697. do {
  2698. MachineBasicBlock *CurMBB = WalkList.pop_back_val();
  2699. for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
  2700. if (BeforePrologueRegion.insert(PredBB).second)
  2701. WalkList.push_back(PredBB);
  2702. }
  2703. } while (!WalkList.empty());
  2704. // The order in that list is important.
  2705. // The blocks will all be inserted before PrologueMBB using that order.
  2706. // Therefore the block that should appear first in the CFG should appear
  2707. // first in the list.
  2708. MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
  2709. PostStackMBB};
  2710. for (MachineBasicBlock *B : AddedBlocks)
  2711. BeforePrologueRegion.insert(B);
  2712. for (const auto &LI : PrologueMBB.liveins()) {
  2713. for (MachineBasicBlock *PredBB : BeforePrologueRegion)
  2714. PredBB->addLiveIn(LI);
  2715. }
  2716. // Remove the newly added blocks from the list, since we know
  2717. // we do not have to do the following updates for them.
  2718. for (MachineBasicBlock *B : AddedBlocks) {
  2719. BeforePrologueRegion.erase(B);
  2720. MF.insert(PrologueMBB.getIterator(), B);
  2721. }
  2722. for (MachineBasicBlock *MBB : BeforePrologueRegion) {
  2723. // Make sure the LiveIns are still sorted and unique.
  2724. MBB->sortUniqueLiveIns();
  2725. // Replace the edges to PrologueMBB by edges to the sequences
  2726. // we are about to add, but only update for immediate predecessors.
  2727. if (MBB->isSuccessor(&PrologueMBB))
  2728. MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
  2729. }
  2730. // The required stack size that is aligned to ARM constant criterion.
  2731. AlignedStackSize = alignToARMConstant(StackSize);
  2732. // When the frame size is less than 256 we just compare the stack
  2733. // boundary directly to the value of the stack pointer, per gcc.
  2734. bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
  2735. // We will use two of the callee save registers as scratch registers so we
  2736. // need to save those registers onto the stack.
  2737. // We will use SR0 to hold stack limit and SR1 to hold the stack size
  2738. // requested and arguments for __morestack().
  2739. // SR0: Scratch Register #0
  2740. // SR1: Scratch Register #1
  2741. // push {SR0, SR1}
  2742. if (Thumb) {
  2743. BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
  2744. .add(predOps(ARMCC::AL))
  2745. .addReg(ScratchReg0)
  2746. .addReg(ScratchReg1);
  2747. } else {
  2748. BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
  2749. .addReg(ARM::SP, RegState::Define)
  2750. .addReg(ARM::SP)
  2751. .add(predOps(ARMCC::AL))
  2752. .addReg(ScratchReg0)
  2753. .addReg(ScratchReg1);
  2754. }
  2755. // Emit the relevant DWARF information about the change in stack pointer as
  2756. // well as where to find both r4 and r5 (the callee-save registers)
  2757. if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
  2758. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 8));
  2759. BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2760. .addCFIIndex(CFIIndex);
  2761. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  2762. nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
  2763. BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2764. .addCFIIndex(CFIIndex);
  2765. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  2766. nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
  2767. BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2768. .addCFIIndex(CFIIndex);
  2769. }
  2770. // mov SR1, sp
  2771. if (Thumb) {
  2772. BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
  2773. .addReg(ARM::SP)
  2774. .add(predOps(ARMCC::AL));
  2775. } else if (CompareStackPointer) {
  2776. BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
  2777. .addReg(ARM::SP)
  2778. .add(predOps(ARMCC::AL))
  2779. .add(condCodeOp());
  2780. }
  2781. // sub SR1, sp, #StackSize
  2782. if (!CompareStackPointer && Thumb) {
  2783. if (AlignedStackSize < 256) {
  2784. BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
  2785. .add(condCodeOp())
  2786. .addReg(ScratchReg1)
  2787. .addImm(AlignedStackSize)
  2788. .add(predOps(ARMCC::AL));
  2789. } else {
  2790. if (Thumb2) {
  2791. BuildMI(McrMBB, DL, TII.get(ARM::t2MOVi32imm), ScratchReg0)
  2792. .addImm(AlignedStackSize);
  2793. } else {
  2794. auto MBBI = McrMBB->end();
  2795. auto RegInfo = STI.getRegisterInfo();
  2796. RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0,
  2797. AlignedStackSize);
  2798. }
  2799. BuildMI(McrMBB, DL, TII.get(ARM::tSUBrr), ScratchReg1)
  2800. .add(condCodeOp())
  2801. .addReg(ScratchReg1)
  2802. .addReg(ScratchReg0)
  2803. .add(predOps(ARMCC::AL));
  2804. }
  2805. } else if (!CompareStackPointer) {
  2806. if (AlignedStackSize < 256) {
  2807. BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
  2808. .addReg(ARM::SP)
  2809. .addImm(AlignedStackSize)
  2810. .add(predOps(ARMCC::AL))
  2811. .add(condCodeOp());
  2812. } else {
  2813. auto MBBI = McrMBB->end();
  2814. auto RegInfo = STI.getRegisterInfo();
  2815. RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0,
  2816. AlignedStackSize);
  2817. BuildMI(McrMBB, DL, TII.get(ARM::SUBrr), ScratchReg1)
  2818. .addReg(ARM::SP)
  2819. .addReg(ScratchReg0)
  2820. .add(predOps(ARMCC::AL))
  2821. .add(condCodeOp());
  2822. }
  2823. }
  2824. if (Thumb && ST->isThumb1Only()) {
  2825. unsigned PCLabelId = ARMFI->createPICLabelUId();
  2826. ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
  2827. MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
  2828. MachineConstantPool *MCP = MF.getConstantPool();
  2829. unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4));
  2830. // ldr SR0, [pc, offset(STACK_LIMIT)]
  2831. BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
  2832. .addConstantPoolIndex(CPI)
  2833. .add(predOps(ARMCC::AL));
  2834. // ldr SR0, [SR0]
  2835. BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
  2836. .addReg(ScratchReg0)
  2837. .addImm(0)
  2838. .add(predOps(ARMCC::AL));
  2839. } else {
  2840. // Get TLS base address from the coprocessor
  2841. // mrc p15, #0, SR0, c13, c0, #3
  2842. BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
  2843. ScratchReg0)
  2844. .addImm(15)
  2845. .addImm(0)
  2846. .addImm(13)
  2847. .addImm(0)
  2848. .addImm(3)
  2849. .add(predOps(ARMCC::AL));
  2850. // Use the last tls slot on android and a private field of the TCP on linux.
  2851. assert(ST->isTargetAndroid() || ST->isTargetLinux());
  2852. unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
  2853. // Get the stack limit from the right offset
  2854. // ldr SR0, [sr0, #4 * TlsOffset]
  2855. BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
  2856. ScratchReg0)
  2857. .addReg(ScratchReg0)
  2858. .addImm(4 * TlsOffset)
  2859. .add(predOps(ARMCC::AL));
  2860. }
  2861. // Compare stack limit with stack size requested.
  2862. // cmp SR0, SR1
  2863. Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
  2864. BuildMI(GetMBB, DL, TII.get(Opcode))
  2865. .addReg(ScratchReg0)
  2866. .addReg(ScratchReg1)
  2867. .add(predOps(ARMCC::AL));
  2868. // This jump is taken if StackLimit < SP - stack required.
  2869. Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
  2870. BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
  2871. .addImm(ARMCC::LO)
  2872. .addReg(ARM::CPSR);
  2873. // Calling __morestack(StackSize, Size of stack arguments).
  2874. // __morestack knows that the stack size requested is in SR0(r4)
  2875. // and amount size of stack arguments is in SR1(r5).
  2876. // Pass first argument for the __morestack by Scratch Register #0.
  2877. // The amount size of stack required
  2878. if (Thumb) {
  2879. if (AlignedStackSize < 256) {
  2880. BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
  2881. .add(condCodeOp())
  2882. .addImm(AlignedStackSize)
  2883. .add(predOps(ARMCC::AL));
  2884. } else {
  2885. if (Thumb2) {
  2886. BuildMI(AllocMBB, DL, TII.get(ARM::t2MOVi32imm), ScratchReg0)
  2887. .addImm(AlignedStackSize);
  2888. } else {
  2889. auto MBBI = AllocMBB->end();
  2890. auto RegInfo = STI.getRegisterInfo();
  2891. RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0,
  2892. AlignedStackSize);
  2893. }
  2894. }
  2895. } else {
  2896. if (AlignedStackSize < 256) {
  2897. BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
  2898. .addImm(AlignedStackSize)
  2899. .add(predOps(ARMCC::AL))
  2900. .add(condCodeOp());
  2901. } else {
  2902. auto MBBI = AllocMBB->end();
  2903. auto RegInfo = STI.getRegisterInfo();
  2904. RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0,
  2905. AlignedStackSize);
  2906. }
  2907. }
  2908. // Pass second argument for the __morestack by Scratch Register #1.
  2909. // The amount size of stack consumed to save function arguments.
  2910. if (Thumb) {
  2911. if (ARMFI->getArgumentStackSize() < 256) {
  2912. BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
  2913. .add(condCodeOp())
  2914. .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
  2915. .add(predOps(ARMCC::AL));
  2916. } else {
  2917. if (Thumb2) {
  2918. BuildMI(AllocMBB, DL, TII.get(ARM::t2MOVi32imm), ScratchReg1)
  2919. .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()));
  2920. } else {
  2921. auto MBBI = AllocMBB->end();
  2922. auto RegInfo = STI.getRegisterInfo();
  2923. RegInfo->emitLoadConstPool(
  2924. *AllocMBB, MBBI, DL, ScratchReg1, 0,
  2925. alignToARMConstant(ARMFI->getArgumentStackSize()));
  2926. }
  2927. }
  2928. } else {
  2929. if (alignToARMConstant(ARMFI->getArgumentStackSize()) < 256) {
  2930. BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
  2931. .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
  2932. .add(predOps(ARMCC::AL))
  2933. .add(condCodeOp());
  2934. } else {
  2935. auto MBBI = AllocMBB->end();
  2936. auto RegInfo = STI.getRegisterInfo();
  2937. RegInfo->emitLoadConstPool(
  2938. *AllocMBB, MBBI, DL, ScratchReg1, 0,
  2939. alignToARMConstant(ARMFI->getArgumentStackSize()));
  2940. }
  2941. }
  2942. // push {lr} - Save return address of this function.
  2943. if (Thumb) {
  2944. BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
  2945. .add(predOps(ARMCC::AL))
  2946. .addReg(ARM::LR);
  2947. } else {
  2948. BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
  2949. .addReg(ARM::SP, RegState::Define)
  2950. .addReg(ARM::SP)
  2951. .add(predOps(ARMCC::AL))
  2952. .addReg(ARM::LR);
  2953. }
  2954. // Emit the DWARF info about the change in stack as well as where to find the
  2955. // previous link register
  2956. if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
  2957. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 12));
  2958. BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2959. .addCFIIndex(CFIIndex);
  2960. CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
  2961. nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
  2962. BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  2963. .addCFIIndex(CFIIndex);
  2964. }
  2965. // Call __morestack().
  2966. if (Thumb) {
  2967. BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
  2968. .add(predOps(ARMCC::AL))
  2969. .addExternalSymbol("__morestack");
  2970. } else {
  2971. BuildMI(AllocMBB, DL, TII.get(ARM::BL))
  2972. .addExternalSymbol("__morestack");
  2973. }
  2974. // pop {lr} - Restore return address of this original function.
  2975. if (Thumb) {
  2976. if (ST->isThumb1Only()) {
  2977. BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
  2978. .add(predOps(ARMCC::AL))
  2979. .addReg(ScratchReg0);
  2980. BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
  2981. .addReg(ScratchReg0)
  2982. .add(predOps(ARMCC::AL));
  2983. } else {
  2984. BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
  2985. .addReg(ARM::LR, RegState::Define)
  2986. .addReg(ARM::SP, RegState::Define)
  2987. .addReg(ARM::SP)
  2988. .addImm(4)
  2989. .add(predOps(ARMCC::AL));
  2990. }
  2991. } else {
  2992. BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
  2993. .addReg(ARM::SP, RegState::Define)
  2994. .addReg(ARM::SP)
  2995. .add(predOps(ARMCC::AL))
  2996. .addReg(ARM::LR);
  2997. }
  2998. // Restore SR0 and SR1 in case of __morestack() was called.
  2999. // __morestack() will skip PostStackMBB block so we need to restore
  3000. // scratch registers from here.
  3001. // pop {SR0, SR1}
  3002. if (Thumb) {
  3003. BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
  3004. .add(predOps(ARMCC::AL))
  3005. .addReg(ScratchReg0)
  3006. .addReg(ScratchReg1);
  3007. } else {
  3008. BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
  3009. .addReg(ARM::SP, RegState::Define)
  3010. .addReg(ARM::SP)
  3011. .add(predOps(ARMCC::AL))
  3012. .addReg(ScratchReg0)
  3013. .addReg(ScratchReg1);
  3014. }
  3015. // Update the CFA offset now that we've popped
  3016. if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
  3017. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
  3018. BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  3019. .addCFIIndex(CFIIndex);
  3020. }
  3021. // Return from this function.
  3022. BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
  3023. // Restore SR0 and SR1 in case of __morestack() was not called.
  3024. // pop {SR0, SR1}
  3025. if (Thumb) {
  3026. BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
  3027. .add(predOps(ARMCC::AL))
  3028. .addReg(ScratchReg0)
  3029. .addReg(ScratchReg1);
  3030. } else {
  3031. BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
  3032. .addReg(ARM::SP, RegState::Define)
  3033. .addReg(ARM::SP)
  3034. .add(predOps(ARMCC::AL))
  3035. .addReg(ScratchReg0)
  3036. .addReg(ScratchReg1);
  3037. }
  3038. // Update the CFA offset now that we've popped
  3039. if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
  3040. CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
  3041. BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  3042. .addCFIIndex(CFIIndex);
  3043. // Tell debuggers that r4 and r5 are now the same as they were in the
  3044. // previous function, that they're the "Same Value".
  3045. CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
  3046. nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
  3047. BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  3048. .addCFIIndex(CFIIndex);
  3049. CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
  3050. nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
  3051. BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
  3052. .addCFIIndex(CFIIndex);
  3053. }
  3054. // Organizing MBB lists
  3055. PostStackMBB->addSuccessor(&PrologueMBB);
  3056. AllocMBB->addSuccessor(PostStackMBB);
  3057. GetMBB->addSuccessor(PostStackMBB);
  3058. GetMBB->addSuccessor(AllocMBB);
  3059. McrMBB->addSuccessor(GetMBB);
  3060. PrevStackMBB->addSuccessor(McrMBB);
  3061. #ifdef EXPENSIVE_CHECKS
  3062. MF.verify();
  3063. #endif
  3064. }