ARMFrameLowering.cpp 111 KB

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