ARMFrameLowering.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains the ARM implementation of TargetFrameLowering class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "ARMFrameLowering.h"
  14. #include "ARMBaseInstrInfo.h"
  15. #include "ARMBaseRegisterInfo.h"
  16. #include "ARMMachineFunctionInfo.h"
  17. #include "MCTargetDesc/ARMAddressingModes.h"
  18. #include "llvm/CodeGen/MachineFrameInfo.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineInstrBuilder.h"
  21. #include "llvm/CodeGen/MachineModuleInfo.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/RegisterScavenging.h"
  24. #include "llvm/IR/CallingConv.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/MC/MCContext.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Target/TargetOptions.h"
  29. using namespace llvm;
  30. static cl::opt<bool>
  31. SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
  32. cl::desc("Align ARM NEON spills in prolog and epilog"));
  33. static MachineBasicBlock::iterator
  34. skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
  35. unsigned NumAlignedDPRCS2Regs);
  36. /// hasFP - Return true if the specified function should have a dedicated frame
  37. /// pointer register. This is true if the function has variable sized allocas
  38. /// or if frame pointer elimination is disabled.
  39. bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
  40. const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
  41. // iOS requires FP not to be clobbered for backtracing purpose.
  42. if (STI.isTargetIOS())
  43. return true;
  44. const MachineFrameInfo *MFI = MF.getFrameInfo();
  45. // Always eliminate non-leaf frame pointers.
  46. return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
  47. MFI->hasCalls()) ||
  48. RegInfo->needsStackRealignment(MF) ||
  49. MFI->hasVarSizedObjects() ||
  50. MFI->isFrameAddressTaken());
  51. }
  52. /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
  53. /// not required, we reserve argument space for call sites in the function
  54. /// immediately on entry to the current function. This eliminates the need for
  55. /// add/sub sp brackets around call sites. Returns true if the call frame is
  56. /// included as part of the stack frame.
  57. bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
  58. const MachineFrameInfo *FFI = MF.getFrameInfo();
  59. unsigned CFSize = FFI->getMaxCallFrameSize();
  60. // It's not always a good idea to include the call frame as part of the
  61. // stack frame. ARM (especially Thumb) has small immediate offset to
  62. // address the stack frame. So a large call frame can cause poor codegen
  63. // and may even makes it impossible to scavenge a register.
  64. if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
  65. return false;
  66. return !MF.getFrameInfo()->hasVarSizedObjects();
  67. }
  68. /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
  69. /// call frame pseudos can be simplified. Unlike most targets, having a FP
  70. /// is not sufficient here since we still may reference some objects via SP
  71. /// even when FP is available in Thumb2 mode.
  72. bool
  73. ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
  74. return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
  75. }
  76. static bool isCSRestore(MachineInstr *MI,
  77. const ARMBaseInstrInfo &TII,
  78. const uint16_t *CSRegs) {
  79. // Integer spill area is handled with "pop".
  80. if (isPopOpcode(MI->getOpcode())) {
  81. // The first two operands are predicates. The last two are
  82. // imp-def and imp-use of SP. Check everything in between.
  83. for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
  84. if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
  85. return false;
  86. return true;
  87. }
  88. if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
  89. MI->getOpcode() == ARM::LDR_POST_REG ||
  90. MI->getOpcode() == ARM::t2LDR_POST) &&
  91. isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
  92. MI->getOperand(1).getReg() == ARM::SP)
  93. return true;
  94. return false;
  95. }
  96. static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
  97. MachineBasicBlock::iterator &MBBI, DebugLoc dl,
  98. const ARMBaseInstrInfo &TII, unsigned DestReg,
  99. unsigned SrcReg, int NumBytes,
  100. unsigned MIFlags = MachineInstr::NoFlags,
  101. ARMCC::CondCodes Pred = ARMCC::AL,
  102. unsigned PredReg = 0) {
  103. if (isARM)
  104. emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
  105. Pred, PredReg, TII, MIFlags);
  106. else
  107. emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
  108. Pred, PredReg, TII, MIFlags);
  109. }
  110. static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
  111. MachineBasicBlock::iterator &MBBI, DebugLoc dl,
  112. const ARMBaseInstrInfo &TII, int NumBytes,
  113. unsigned MIFlags = MachineInstr::NoFlags,
  114. ARMCC::CondCodes Pred = ARMCC::AL,
  115. unsigned PredReg = 0) {
  116. emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
  117. MIFlags, Pred, PredReg);
  118. }
  119. static int sizeOfSPAdjustment(const MachineInstr *MI) {
  120. assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
  121. int count = 0;
  122. // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
  123. // pred) so the list starts at 4.
  124. for (int i = MI->getNumOperands() - 1; i >= 4; --i)
  125. count += 8;
  126. return count;
  127. }
  128. void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
  129. MachineBasicBlock &MBB = MF.front();
  130. MachineBasicBlock::iterator MBBI = MBB.begin();
  131. MachineFrameInfo *MFI = MF.getFrameInfo();
  132. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  133. MachineModuleInfo &MMI = MF.getMMI();
  134. MCContext &Context = MMI.getContext();
  135. const MCRegisterInfo *MRI = Context.getRegisterInfo();
  136. const ARMBaseRegisterInfo *RegInfo =
  137. static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
  138. const ARMBaseInstrInfo &TII =
  139. *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
  140. assert(!AFI->isThumb1OnlyFunction() &&
  141. "This emitPrologue does not support Thumb1!");
  142. bool isARM = !AFI->isThumbFunction();
  143. unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
  144. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
  145. unsigned NumBytes = MFI->getStackSize();
  146. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  147. DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
  148. unsigned FramePtr = RegInfo->getFrameRegister(MF);
  149. int CFAOffset = 0;
  150. // Determine the sizes of each callee-save spill areas and record which frame
  151. // belongs to which callee-save spill areas.
  152. unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
  153. int FramePtrSpillFI = 0;
  154. int D8SpillFI = 0;
  155. // All calls are tail calls in GHC calling conv, and functions have no
  156. // prologue/epilogue.
  157. if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
  158. return;
  159. // Allocate the vararg register save area. This is not counted in NumBytes.
  160. if (ArgRegsSaveSize) {
  161. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
  162. MachineInstr::FrameSetup);
  163. MCSymbol *SPLabel = Context.CreateTempSymbol();
  164. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  165. .addSym(SPLabel);
  166. CFAOffset -= ArgRegsSaveSize;
  167. MMI.addFrameInst(
  168. MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
  169. }
  170. if (!AFI->hasStackFrame()) {
  171. if (NumBytes != 0) {
  172. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
  173. MachineInstr::FrameSetup);
  174. MCSymbol *SPLabel = Context.CreateTempSymbol();
  175. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  176. .addSym(SPLabel);
  177. CFAOffset -= NumBytes;
  178. MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(SPLabel,
  179. CFAOffset));
  180. }
  181. return;
  182. }
  183. // Determine spill area sizes.
  184. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  185. unsigned Reg = CSI[i].getReg();
  186. int FI = CSI[i].getFrameIdx();
  187. switch (Reg) {
  188. case ARM::R8:
  189. case ARM::R9:
  190. case ARM::R10:
  191. case ARM::R11:
  192. case ARM::R12:
  193. if (STI.isTargetMachO()) {
  194. GPRCS2Size += 4;
  195. break;
  196. }
  197. // fallthrough
  198. case ARM::R0:
  199. case ARM::R1:
  200. case ARM::R2:
  201. case ARM::R3:
  202. case ARM::R4:
  203. case ARM::R5:
  204. case ARM::R6:
  205. case ARM::R7:
  206. case ARM::LR:
  207. if (Reg == FramePtr)
  208. FramePtrSpillFI = FI;
  209. GPRCS1Size += 4;
  210. break;
  211. default:
  212. // This is a DPR. Exclude the aligned DPRCS2 spills.
  213. if (Reg == ARM::D8)
  214. D8SpillFI = FI;
  215. if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
  216. DPRCSSize += 8;
  217. }
  218. }
  219. // Move past area 1.
  220. MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
  221. DPRCSPush;
  222. if (GPRCS1Size > 0)
  223. GPRCS1Push = LastPush = MBBI++;
  224. // Determine starting offsets of spill areas.
  225. bool HasFP = hasFP(MF);
  226. unsigned DPRCSOffset = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
  227. unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
  228. unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
  229. int FramePtrOffsetInPush = 0;
  230. if (HasFP) {
  231. FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI) + GPRCS1Size;
  232. AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
  233. NumBytes);
  234. }
  235. AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
  236. AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
  237. AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
  238. // Move past area 2.
  239. if (GPRCS2Size > 0)
  240. GPRCS2Push = LastPush = MBBI++;
  241. // Move past area 3.
  242. if (DPRCSSize > 0) {
  243. DPRCSPush = MBBI;
  244. // Since vpush register list cannot have gaps, there may be multiple vpush
  245. // instructions in the prologue.
  246. while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
  247. LastPush = MBBI++;
  248. }
  249. // Move past the aligned DPRCS2 area.
  250. if (AFI->getNumAlignedDPRCS2Regs() > 0) {
  251. MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
  252. // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
  253. // leaves the stack pointer pointing to the DPRCS2 area.
  254. //
  255. // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
  256. NumBytes += MFI->getObjectOffset(D8SpillFI);
  257. } else
  258. NumBytes = DPRCSOffset;
  259. unsigned adjustedGPRCS1Size = GPRCS1Size;
  260. if (NumBytes) {
  261. // Adjust SP after all the callee-save spills.
  262. if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
  263. if (LastPush == GPRCS1Push) {
  264. FramePtrOffsetInPush += NumBytes;
  265. adjustedGPRCS1Size += NumBytes;
  266. NumBytes = 0;
  267. }
  268. } else
  269. emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
  270. MachineInstr::FrameSetup);
  271. if (HasFP && isARM)
  272. // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
  273. // Note it's not safe to do this in Thumb2 mode because it would have
  274. // taken two instructions:
  275. // mov sp, r7
  276. // sub sp, #24
  277. // If an interrupt is taken between the two instructions, then sp is in
  278. // an inconsistent state (pointing to the middle of callee-saved area).
  279. // The interrupt handler can end up clobbering the registers.
  280. AFI->setShouldRestoreSPFromFP(true);
  281. }
  282. if (adjustedGPRCS1Size > 0) {
  283. MCSymbol *SPLabel = Context.CreateTempSymbol();
  284. BuildMI(MBB, ++GPRCS1Push, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  285. .addSym(SPLabel);
  286. CFAOffset -= adjustedGPRCS1Size;
  287. MMI.addFrameInst(
  288. MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
  289. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  290. E = CSI.end(); I != E; ++I) {
  291. unsigned Reg = I->getReg();
  292. int FI = I->getFrameIdx();
  293. switch (Reg) {
  294. case ARM::R8:
  295. case ARM::R9:
  296. case ARM::R10:
  297. case ARM::R11:
  298. case ARM::R12:
  299. if (STI.isTargetMachO())
  300. break;
  301. // fallthrough
  302. case ARM::R0:
  303. case ARM::R1:
  304. case ARM::R2:
  305. case ARM::R3:
  306. case ARM::R4:
  307. case ARM::R5:
  308. case ARM::R6:
  309. case ARM::R7:
  310. case ARM::LR:
  311. MMI.addFrameInst(MCCFIInstruction::createOffset(SPLabel,
  312. MRI->getDwarfRegNum(Reg, true),
  313. MFI->getObjectOffset(FI) - ArgRegsSaveSize));
  314. break;
  315. }
  316. }
  317. }
  318. // Set FP to point to the stack slot that contains the previous FP.
  319. // For iOS, FP is R7, which has now been stored in spill area 1.
  320. // Otherwise, if this is not iOS, all the callee-saved registers go
  321. // into spill area 1, including the FP in R11. In either case, it
  322. // is in area one and the adjustment needs to take place just after
  323. // that push.
  324. if (HasFP) {
  325. emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
  326. FramePtr, ARM::SP, FramePtrOffsetInPush,
  327. MachineInstr::FrameSetup);
  328. MCSymbol *SPLabel = Context.CreateTempSymbol();
  329. BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  330. .addSym(SPLabel);
  331. if (FramePtrOffsetInPush) {
  332. CFAOffset += FramePtrOffsetInPush;
  333. MMI.addFrameInst(
  334. MCCFIInstruction::createDefCfa(SPLabel,
  335. MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
  336. } else
  337. MMI.addFrameInst(
  338. MCCFIInstruction::createDefCfaRegister(SPLabel,
  339. MRI->getDwarfRegNum(FramePtr, true)));
  340. }
  341. if (GPRCS2Size > 0) {
  342. MCSymbol *SPLabel = Context.CreateTempSymbol();
  343. BuildMI(MBB, ++GPRCS2Push, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  344. .addSym(SPLabel);
  345. if (!HasFP) {
  346. CFAOffset -= GPRCS2Size;
  347. MMI.addFrameInst(
  348. MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
  349. }
  350. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  351. E = CSI.end(); I != E; ++I) {
  352. unsigned Reg = I->getReg();
  353. int FI = I->getFrameIdx();
  354. switch (Reg) {
  355. case ARM::R8:
  356. case ARM::R9:
  357. case ARM::R10:
  358. case ARM::R11:
  359. case ARM::R12:
  360. if (STI.isTargetMachO()) {
  361. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  362. unsigned Offset = MFI->getObjectOffset(FI) - ArgRegsSaveSize;
  363. MMI.addFrameInst(
  364. MCCFIInstruction::createOffset(SPLabel, DwarfReg, Offset));
  365. }
  366. break;
  367. }
  368. }
  369. }
  370. if (DPRCSSize > 0) {
  371. // Since vpush register list cannot have gaps, there may be multiple vpush
  372. // instructions in the prologue.
  373. MCSymbol *SPLabel = NULL;
  374. do {
  375. MachineBasicBlock::iterator Push = DPRCSPush++;
  376. if (!HasFP) {
  377. SPLabel = Context.CreateTempSymbol();
  378. BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  379. .addSym(SPLabel);
  380. CFAOffset -= sizeOfSPAdjustment(Push);;
  381. MMI.addFrameInst(
  382. MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
  383. }
  384. } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
  385. if (!SPLabel) {
  386. SPLabel = Context.CreateTempSymbol();
  387. BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  388. .addSym(SPLabel);
  389. }
  390. for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
  391. E = CSI.end(); I != E; ++I) {
  392. unsigned Reg = I->getReg();
  393. int FI = I->getFrameIdx();
  394. if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
  395. (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
  396. unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
  397. unsigned Offset = MFI->getObjectOffset(FI);
  398. MMI.addFrameInst(MCCFIInstruction::createOffset(SPLabel, DwarfReg,
  399. Offset));
  400. }
  401. }
  402. }
  403. if (NumBytes) {
  404. if (!HasFP) {
  405. MCSymbol *SPLabel = Context.CreateTempSymbol();
  406. BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::PROLOG_LABEL))
  407. .addSym(SPLabel);
  408. CFAOffset -= NumBytes;
  409. MMI.addFrameInst(
  410. MCCFIInstruction::createDefCfaOffset(SPLabel, CFAOffset));
  411. }
  412. }
  413. if (STI.isTargetELF() && hasFP(MF))
  414. MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
  415. AFI->getFramePtrSpillOffset());
  416. AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
  417. AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
  418. AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
  419. // If we need dynamic stack realignment, do it here. Be paranoid and make
  420. // sure if we also have VLAs, we have a base pointer for frame access.
  421. // If aligned NEON registers were spilled, the stack has already been
  422. // realigned.
  423. if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
  424. unsigned MaxAlign = MFI->getMaxAlignment();
  425. assert (!AFI->isThumb1OnlyFunction());
  426. if (!AFI->isThumbFunction()) {
  427. // Emit bic sp, sp, MaxAlign
  428. AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
  429. TII.get(ARM::BICri), ARM::SP)
  430. .addReg(ARM::SP, RegState::Kill)
  431. .addImm(MaxAlign-1)));
  432. } else {
  433. // We cannot use sp as source/dest register here, thus we're emitting the
  434. // following sequence:
  435. // mov r4, sp
  436. // bic r4, r4, MaxAlign
  437. // mov sp, r4
  438. // FIXME: It will be better just to find spare register here.
  439. AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
  440. .addReg(ARM::SP, RegState::Kill));
  441. AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
  442. TII.get(ARM::t2BICri), ARM::R4)
  443. .addReg(ARM::R4, RegState::Kill)
  444. .addImm(MaxAlign-1)));
  445. AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
  446. .addReg(ARM::R4, RegState::Kill));
  447. }
  448. AFI->setShouldRestoreSPFromFP(true);
  449. }
  450. // If we need a base pointer, set it up here. It's whatever the value
  451. // of the stack pointer is at this point. Any variable size objects
  452. // will be allocated after this, so we can still use the base pointer
  453. // to reference locals.
  454. // FIXME: Clarify FrameSetup flags here.
  455. if (RegInfo->hasBasePointer(MF)) {
  456. if (isARM)
  457. BuildMI(MBB, MBBI, dl,
  458. TII.get(ARM::MOVr), RegInfo->getBaseRegister())
  459. .addReg(ARM::SP)
  460. .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
  461. else
  462. AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
  463. RegInfo->getBaseRegister())
  464. .addReg(ARM::SP));
  465. }
  466. // If the frame has variable sized objects then the epilogue must restore
  467. // the sp from fp. We can assume there's an FP here since hasFP already
  468. // checks for hasVarSizedObjects.
  469. if (MFI->hasVarSizedObjects())
  470. AFI->setShouldRestoreSPFromFP(true);
  471. }
  472. void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
  473. MachineBasicBlock &MBB) const {
  474. MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
  475. assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
  476. unsigned RetOpcode = MBBI->getOpcode();
  477. DebugLoc dl = MBBI->getDebugLoc();
  478. MachineFrameInfo *MFI = MF.getFrameInfo();
  479. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  480. const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
  481. const ARMBaseInstrInfo &TII =
  482. *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
  483. assert(!AFI->isThumb1OnlyFunction() &&
  484. "This emitEpilogue does not support Thumb1!");
  485. bool isARM = !AFI->isThumbFunction();
  486. unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
  487. unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
  488. int NumBytes = (int)MFI->getStackSize();
  489. unsigned FramePtr = RegInfo->getFrameRegister(MF);
  490. // All calls are tail calls in GHC calling conv, and functions have no
  491. // prologue/epilogue.
  492. if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
  493. return;
  494. if (!AFI->hasStackFrame()) {
  495. if (NumBytes != 0)
  496. emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
  497. } else {
  498. // Unwind MBBI to point to first LDR / VLDRD.
  499. const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
  500. if (MBBI != MBB.begin()) {
  501. do {
  502. --MBBI;
  503. } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
  504. if (!isCSRestore(MBBI, TII, CSRegs))
  505. ++MBBI;
  506. }
  507. // Move SP to start of FP callee save spill area.
  508. NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
  509. AFI->getGPRCalleeSavedArea2Size() +
  510. AFI->getDPRCalleeSavedAreaSize());
  511. // Reset SP based on frame pointer only if the stack frame extends beyond
  512. // frame pointer stack slot or target is ELF and the function has FP.
  513. if (AFI->shouldRestoreSPFromFP()) {
  514. NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
  515. if (NumBytes) {
  516. if (isARM)
  517. emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
  518. ARMCC::AL, 0, TII);
  519. else {
  520. // It's not possible to restore SP from FP in a single instruction.
  521. // For iOS, this looks like:
  522. // mov sp, r7
  523. // sub sp, #24
  524. // This is bad, if an interrupt is taken after the mov, sp is in an
  525. // inconsistent state.
  526. // Use the first callee-saved register as a scratch register.
  527. assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
  528. "No scratch register to restore SP from FP!");
  529. emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
  530. ARMCC::AL, 0, TII);
  531. AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
  532. ARM::SP)
  533. .addReg(ARM::R4));
  534. }
  535. } else {
  536. // Thumb2 or ARM.
  537. if (isARM)
  538. BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
  539. .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
  540. else
  541. AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
  542. ARM::SP)
  543. .addReg(FramePtr));
  544. }
  545. } else if (NumBytes &&
  546. !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
  547. emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
  548. // Increment past our save areas.
  549. if (AFI->getDPRCalleeSavedAreaSize()) {
  550. MBBI++;
  551. // Since vpop register list cannot have gaps, there may be multiple vpop
  552. // instructions in the epilogue.
  553. while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
  554. MBBI++;
  555. }
  556. if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
  557. if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
  558. }
  559. if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
  560. // Tail call return: adjust the stack pointer and jump to callee.
  561. MBBI = MBB.getLastNonDebugInstr();
  562. MachineOperand &JumpTarget = MBBI->getOperand(0);
  563. // Jump to label or value in register.
  564. if (RetOpcode == ARM::TCRETURNdi) {
  565. unsigned TCOpcode = STI.isThumb() ?
  566. (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
  567. ARM::TAILJMPd;
  568. MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
  569. if (JumpTarget.isGlobal())
  570. MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
  571. JumpTarget.getTargetFlags());
  572. else {
  573. assert(JumpTarget.isSymbol());
  574. MIB.addExternalSymbol(JumpTarget.getSymbolName(),
  575. JumpTarget.getTargetFlags());
  576. }
  577. // Add the default predicate in Thumb mode.
  578. if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
  579. } else if (RetOpcode == ARM::TCRETURNri) {
  580. BuildMI(MBB, MBBI, dl,
  581. TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
  582. addReg(JumpTarget.getReg(), RegState::Kill);
  583. }
  584. MachineInstr *NewMI = std::prev(MBBI);
  585. for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
  586. NewMI->addOperand(MBBI->getOperand(i));
  587. // Delete the pseudo instruction TCRETURN.
  588. MBB.erase(MBBI);
  589. MBBI = NewMI;
  590. }
  591. if (ArgRegsSaveSize)
  592. emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
  593. }
  594. /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
  595. /// debug info. It's the same as what we use for resolving the code-gen
  596. /// references for now. FIXME: This can go wrong when references are
  597. /// SP-relative and simple call frames aren't used.
  598. int
  599. ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
  600. unsigned &FrameReg) const {
  601. return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
  602. }
  603. int
  604. ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
  605. int FI, unsigned &FrameReg,
  606. int SPAdj) const {
  607. const MachineFrameInfo *MFI = MF.getFrameInfo();
  608. const ARMBaseRegisterInfo *RegInfo =
  609. static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
  610. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  611. int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
  612. int FPOffset = Offset - AFI->getFramePtrSpillOffset();
  613. bool isFixed = MFI->isFixedObjectIndex(FI);
  614. FrameReg = ARM::SP;
  615. Offset += SPAdj;
  616. // SP can move around if there are allocas. We may also lose track of SP
  617. // when emergency spilling inside a non-reserved call frame setup.
  618. bool hasMovingSP = !hasReservedCallFrame(MF);
  619. // When dynamically realigning the stack, use the frame pointer for
  620. // parameters, and the stack/base pointer for locals.
  621. if (RegInfo->needsStackRealignment(MF)) {
  622. assert (hasFP(MF) && "dynamic stack realignment without a FP!");
  623. if (isFixed) {
  624. FrameReg = RegInfo->getFrameRegister(MF);
  625. Offset = FPOffset;
  626. } else if (hasMovingSP) {
  627. assert(RegInfo->hasBasePointer(MF) &&
  628. "VLAs and dynamic stack alignment, but missing base pointer!");
  629. FrameReg = RegInfo->getBaseRegister();
  630. }
  631. return Offset;
  632. }
  633. // If there is a frame pointer, use it when we can.
  634. if (hasFP(MF) && AFI->hasStackFrame()) {
  635. // Use frame pointer to reference fixed objects. Use it for locals if
  636. // there are VLAs (and thus the SP isn't reliable as a base).
  637. if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
  638. FrameReg = RegInfo->getFrameRegister(MF);
  639. return FPOffset;
  640. } else if (hasMovingSP) {
  641. assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
  642. if (AFI->isThumb2Function()) {
  643. // Try to use the frame pointer if we can, else use the base pointer
  644. // since it's available. This is handy for the emergency spill slot, in
  645. // particular.
  646. if (FPOffset >= -255 && FPOffset < 0) {
  647. FrameReg = RegInfo->getFrameRegister(MF);
  648. return FPOffset;
  649. }
  650. }
  651. } else if (AFI->isThumb2Function()) {
  652. // Use add <rd>, sp, #<imm8>
  653. // ldr <rd>, [sp, #<imm8>]
  654. // if at all possible to save space.
  655. if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
  656. return Offset;
  657. // In Thumb2 mode, the negative offset is very limited. Try to avoid
  658. // out of range references. ldr <rt>,[<rn>, #-<imm8>]
  659. if (FPOffset >= -255 && FPOffset < 0) {
  660. FrameReg = RegInfo->getFrameRegister(MF);
  661. return FPOffset;
  662. }
  663. } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
  664. // Otherwise, use SP or FP, whichever is closer to the stack slot.
  665. FrameReg = RegInfo->getFrameRegister(MF);
  666. return FPOffset;
  667. }
  668. }
  669. // Use the base pointer if we have one.
  670. if (RegInfo->hasBasePointer(MF))
  671. FrameReg = RegInfo->getBaseRegister();
  672. return Offset;
  673. }
  674. int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
  675. int FI) const {
  676. unsigned FrameReg;
  677. return getFrameIndexReference(MF, FI, FrameReg);
  678. }
  679. void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
  680. MachineBasicBlock::iterator MI,
  681. const std::vector<CalleeSavedInfo> &CSI,
  682. unsigned StmOpc, unsigned StrOpc,
  683. bool NoGap,
  684. bool(*Func)(unsigned, bool),
  685. unsigned NumAlignedDPRCS2Regs,
  686. unsigned MIFlags) const {
  687. MachineFunction &MF = *MBB.getParent();
  688. const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
  689. DebugLoc DL;
  690. if (MI != MBB.end()) DL = MI->getDebugLoc();
  691. SmallVector<std::pair<unsigned,bool>, 4> Regs;
  692. unsigned i = CSI.size();
  693. while (i != 0) {
  694. unsigned LastReg = 0;
  695. for (; i != 0; --i) {
  696. unsigned Reg = CSI[i-1].getReg();
  697. if (!(Func)(Reg, STI.isTargetMachO())) continue;
  698. // D-registers in the aligned area DPRCS2 are NOT spilled here.
  699. if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
  700. continue;
  701. // Add the callee-saved register as live-in unless it's LR and
  702. // @llvm.returnaddress is called. If LR is returned for
  703. // @llvm.returnaddress then it's already added to the function and
  704. // entry block live-in sets.
  705. bool isKill = true;
  706. if (Reg == ARM::LR) {
  707. if (MF.getFrameInfo()->isReturnAddressTaken() &&
  708. MF.getRegInfo().isLiveIn(Reg))
  709. isKill = false;
  710. }
  711. if (isKill)
  712. MBB.addLiveIn(Reg);
  713. // If NoGap is true, push consecutive registers and then leave the rest
  714. // for other instructions. e.g.
  715. // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
  716. if (NoGap && LastReg && LastReg != Reg-1)
  717. break;
  718. LastReg = Reg;
  719. Regs.push_back(std::make_pair(Reg, isKill));
  720. }
  721. if (Regs.empty())
  722. continue;
  723. if (Regs.size() > 1 || StrOpc== 0) {
  724. MachineInstrBuilder MIB =
  725. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
  726. .addReg(ARM::SP).setMIFlags(MIFlags));
  727. for (unsigned i = 0, e = Regs.size(); i < e; ++i)
  728. MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
  729. } else if (Regs.size() == 1) {
  730. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
  731. ARM::SP)
  732. .addReg(Regs[0].first, getKillRegState(Regs[0].second))
  733. .addReg(ARM::SP).setMIFlags(MIFlags)
  734. .addImm(-4);
  735. AddDefaultPred(MIB);
  736. }
  737. Regs.clear();
  738. }
  739. }
  740. void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
  741. MachineBasicBlock::iterator MI,
  742. const std::vector<CalleeSavedInfo> &CSI,
  743. unsigned LdmOpc, unsigned LdrOpc,
  744. bool isVarArg, bool NoGap,
  745. bool(*Func)(unsigned, bool),
  746. unsigned NumAlignedDPRCS2Regs) const {
  747. MachineFunction &MF = *MBB.getParent();
  748. const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
  749. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  750. DebugLoc DL = MI->getDebugLoc();
  751. unsigned RetOpcode = MI->getOpcode();
  752. bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
  753. RetOpcode == ARM::TCRETURNri);
  754. bool isInterrupt =
  755. RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
  756. SmallVector<unsigned, 4> Regs;
  757. unsigned i = CSI.size();
  758. while (i != 0) {
  759. unsigned LastReg = 0;
  760. bool DeleteRet = false;
  761. for (; i != 0; --i) {
  762. unsigned Reg = CSI[i-1].getReg();
  763. if (!(Func)(Reg, STI.isTargetMachO())) continue;
  764. // The aligned reloads from area DPRCS2 are not inserted here.
  765. if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
  766. continue;
  767. if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
  768. STI.hasV5TOps()) {
  769. Reg = ARM::PC;
  770. LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
  771. // Fold the return instruction into the LDM.
  772. DeleteRet = true;
  773. }
  774. // If NoGap is true, pop consecutive registers and then leave the rest
  775. // for other instructions. e.g.
  776. // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
  777. if (NoGap && LastReg && LastReg != Reg-1)
  778. break;
  779. LastReg = Reg;
  780. Regs.push_back(Reg);
  781. }
  782. if (Regs.empty())
  783. continue;
  784. if (Regs.size() > 1 || LdrOpc == 0) {
  785. MachineInstrBuilder MIB =
  786. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
  787. .addReg(ARM::SP));
  788. for (unsigned i = 0, e = Regs.size(); i < e; ++i)
  789. MIB.addReg(Regs[i], getDefRegState(true));
  790. if (DeleteRet) {
  791. MIB.copyImplicitOps(&*MI);
  792. MI->eraseFromParent();
  793. }
  794. MI = MIB;
  795. } else if (Regs.size() == 1) {
  796. // If we adjusted the reg to PC from LR above, switch it back here. We
  797. // only do that for LDM.
  798. if (Regs[0] == ARM::PC)
  799. Regs[0] = ARM::LR;
  800. MachineInstrBuilder MIB =
  801. BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
  802. .addReg(ARM::SP, RegState::Define)
  803. .addReg(ARM::SP);
  804. // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
  805. // that refactoring is complete (eventually).
  806. if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
  807. MIB.addReg(0);
  808. MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
  809. } else
  810. MIB.addImm(4);
  811. AddDefaultPred(MIB);
  812. }
  813. Regs.clear();
  814. }
  815. }
  816. /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
  817. /// starting from d8. Also insert stack realignment code and leave the stack
  818. /// pointer pointing to the d8 spill slot.
  819. static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
  820. MachineBasicBlock::iterator MI,
  821. unsigned NumAlignedDPRCS2Regs,
  822. const std::vector<CalleeSavedInfo> &CSI,
  823. const TargetRegisterInfo *TRI) {
  824. MachineFunction &MF = *MBB.getParent();
  825. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  826. DebugLoc DL = MI->getDebugLoc();
  827. const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
  828. MachineFrameInfo &MFI = *MF.getFrameInfo();
  829. // Mark the D-register spill slots as properly aligned. Since MFI computes
  830. // stack slot layout backwards, this can actually mean that the d-reg stack
  831. // slot offsets can be wrong. The offset for d8 will always be correct.
  832. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  833. unsigned DNum = CSI[i].getReg() - ARM::D8;
  834. if (DNum >= 8)
  835. continue;
  836. int FI = CSI[i].getFrameIdx();
  837. // The even-numbered registers will be 16-byte aligned, the odd-numbered
  838. // registers will be 8-byte aligned.
  839. MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
  840. // The stack slot for D8 needs to be maximally aligned because this is
  841. // actually the point where we align the stack pointer. MachineFrameInfo
  842. // computes all offsets relative to the incoming stack pointer which is a
  843. // bit weird when realigning the stack. Any extra padding for this
  844. // over-alignment is not realized because the code inserted below adjusts
  845. // the stack pointer by numregs * 8 before aligning the stack pointer.
  846. if (DNum == 0)
  847. MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
  848. }
  849. // Move the stack pointer to the d8 spill slot, and align it at the same
  850. // time. Leave the stack slot address in the scratch register r4.
  851. //
  852. // sub r4, sp, #numregs * 8
  853. // bic r4, r4, #align - 1
  854. // mov sp, r4
  855. //
  856. bool isThumb = AFI->isThumbFunction();
  857. assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
  858. AFI->setShouldRestoreSPFromFP(true);
  859. // sub r4, sp, #numregs * 8
  860. // The immediate is <= 64, so it doesn't need any special encoding.
  861. unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
  862. AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  863. .addReg(ARM::SP)
  864. .addImm(8 * NumAlignedDPRCS2Regs)));
  865. // bic r4, r4, #align-1
  866. Opc = isThumb ? ARM::t2BICri : ARM::BICri;
  867. unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
  868. AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  869. .addReg(ARM::R4, RegState::Kill)
  870. .addImm(MaxAlign - 1)));
  871. // mov sp, r4
  872. // The stack pointer must be adjusted before spilling anything, otherwise
  873. // the stack slots could be clobbered by an interrupt handler.
  874. // Leave r4 live, it is used below.
  875. Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
  876. MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
  877. .addReg(ARM::R4);
  878. MIB = AddDefaultPred(MIB);
  879. if (!isThumb)
  880. AddDefaultCC(MIB);
  881. // Now spill NumAlignedDPRCS2Regs registers starting from d8.
  882. // r4 holds the stack slot address.
  883. unsigned NextReg = ARM::D8;
  884. // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
  885. // The writeback is only needed when emitting two vst1.64 instructions.
  886. if (NumAlignedDPRCS2Regs >= 6) {
  887. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  888. &ARM::QQPRRegClass);
  889. MBB.addLiveIn(SupReg);
  890. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
  891. ARM::R4)
  892. .addReg(ARM::R4, RegState::Kill).addImm(16)
  893. .addReg(NextReg)
  894. .addReg(SupReg, RegState::ImplicitKill));
  895. NextReg += 4;
  896. NumAlignedDPRCS2Regs -= 4;
  897. }
  898. // We won't modify r4 beyond this point. It currently points to the next
  899. // register to be spilled.
  900. unsigned R4BaseReg = NextReg;
  901. // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
  902. if (NumAlignedDPRCS2Regs >= 4) {
  903. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  904. &ARM::QQPRRegClass);
  905. MBB.addLiveIn(SupReg);
  906. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
  907. .addReg(ARM::R4).addImm(16).addReg(NextReg)
  908. .addReg(SupReg, RegState::ImplicitKill));
  909. NextReg += 4;
  910. NumAlignedDPRCS2Regs -= 4;
  911. }
  912. // 16-byte aligned vst1.64 with 2 d-regs.
  913. if (NumAlignedDPRCS2Regs >= 2) {
  914. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  915. &ARM::QPRRegClass);
  916. MBB.addLiveIn(SupReg);
  917. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
  918. .addReg(ARM::R4).addImm(16).addReg(SupReg));
  919. NextReg += 2;
  920. NumAlignedDPRCS2Regs -= 2;
  921. }
  922. // Finally, use a vanilla vstr.64 for the odd last register.
  923. if (NumAlignedDPRCS2Regs) {
  924. MBB.addLiveIn(NextReg);
  925. // vstr.64 uses addrmode5 which has an offset scale of 4.
  926. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
  927. .addReg(NextReg)
  928. .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
  929. }
  930. // The last spill instruction inserted should kill the scratch register r4.
  931. std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
  932. }
  933. /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
  934. /// iterator to the following instruction.
  935. static MachineBasicBlock::iterator
  936. skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
  937. unsigned NumAlignedDPRCS2Regs) {
  938. // sub r4, sp, #numregs * 8
  939. // bic r4, r4, #align - 1
  940. // mov sp, r4
  941. ++MI; ++MI; ++MI;
  942. assert(MI->mayStore() && "Expecting spill instruction");
  943. // These switches all fall through.
  944. switch(NumAlignedDPRCS2Regs) {
  945. case 7:
  946. ++MI;
  947. assert(MI->mayStore() && "Expecting spill instruction");
  948. default:
  949. ++MI;
  950. assert(MI->mayStore() && "Expecting spill instruction");
  951. case 1:
  952. case 2:
  953. case 4:
  954. assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
  955. ++MI;
  956. }
  957. return MI;
  958. }
  959. /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
  960. /// starting from d8. These instructions are assumed to execute while the
  961. /// stack is still aligned, unlike the code inserted by emitPopInst.
  962. static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
  963. MachineBasicBlock::iterator MI,
  964. unsigned NumAlignedDPRCS2Regs,
  965. const std::vector<CalleeSavedInfo> &CSI,
  966. const TargetRegisterInfo *TRI) {
  967. MachineFunction &MF = *MBB.getParent();
  968. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  969. DebugLoc DL = MI->getDebugLoc();
  970. const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
  971. // Find the frame index assigned to d8.
  972. int D8SpillFI = 0;
  973. for (unsigned i = 0, e = CSI.size(); i != e; ++i)
  974. if (CSI[i].getReg() == ARM::D8) {
  975. D8SpillFI = CSI[i].getFrameIdx();
  976. break;
  977. }
  978. // Materialize the address of the d8 spill slot into the scratch register r4.
  979. // This can be fairly complicated if the stack frame is large, so just use
  980. // the normal frame index elimination mechanism to do it. This code runs as
  981. // the initial part of the epilog where the stack and base pointers haven't
  982. // been changed yet.
  983. bool isThumb = AFI->isThumbFunction();
  984. assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
  985. unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
  986. AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
  987. .addFrameIndex(D8SpillFI).addImm(0)));
  988. // Now restore NumAlignedDPRCS2Regs registers starting from d8.
  989. unsigned NextReg = ARM::D8;
  990. // 16-byte aligned vld1.64 with 4 d-regs and writeback.
  991. if (NumAlignedDPRCS2Regs >= 6) {
  992. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  993. &ARM::QQPRRegClass);
  994. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
  995. .addReg(ARM::R4, RegState::Define)
  996. .addReg(ARM::R4, RegState::Kill).addImm(16)
  997. .addReg(SupReg, RegState::ImplicitDefine));
  998. NextReg += 4;
  999. NumAlignedDPRCS2Regs -= 4;
  1000. }
  1001. // We won't modify r4 beyond this point. It currently points to the next
  1002. // register to be spilled.
  1003. unsigned R4BaseReg = NextReg;
  1004. // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
  1005. if (NumAlignedDPRCS2Regs >= 4) {
  1006. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1007. &ARM::QQPRRegClass);
  1008. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
  1009. .addReg(ARM::R4).addImm(16)
  1010. .addReg(SupReg, RegState::ImplicitDefine));
  1011. NextReg += 4;
  1012. NumAlignedDPRCS2Regs -= 4;
  1013. }
  1014. // 16-byte aligned vld1.64 with 2 d-regs.
  1015. if (NumAlignedDPRCS2Regs >= 2) {
  1016. unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
  1017. &ARM::QPRRegClass);
  1018. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
  1019. .addReg(ARM::R4).addImm(16));
  1020. NextReg += 2;
  1021. NumAlignedDPRCS2Regs -= 2;
  1022. }
  1023. // Finally, use a vanilla vldr.64 for the remaining odd register.
  1024. if (NumAlignedDPRCS2Regs)
  1025. AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
  1026. .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
  1027. // Last store kills r4.
  1028. std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
  1029. }
  1030. bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
  1031. MachineBasicBlock::iterator MI,
  1032. const std::vector<CalleeSavedInfo> &CSI,
  1033. const TargetRegisterInfo *TRI) const {
  1034. if (CSI.empty())
  1035. return false;
  1036. MachineFunction &MF = *MBB.getParent();
  1037. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1038. unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
  1039. unsigned PushOneOpc = AFI->isThumbFunction() ?
  1040. ARM::t2STR_PRE : ARM::STR_PRE_IMM;
  1041. unsigned FltOpc = ARM::VSTMDDB_UPD;
  1042. unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
  1043. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
  1044. MachineInstr::FrameSetup);
  1045. emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
  1046. MachineInstr::FrameSetup);
  1047. emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
  1048. NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
  1049. // The code above does not insert spill code for the aligned DPRCS2 registers.
  1050. // The stack realignment code will be inserted between the push instructions
  1051. // and these spills.
  1052. if (NumAlignedDPRCS2Regs)
  1053. emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
  1054. return true;
  1055. }
  1056. bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
  1057. MachineBasicBlock::iterator MI,
  1058. const std::vector<CalleeSavedInfo> &CSI,
  1059. const TargetRegisterInfo *TRI) const {
  1060. if (CSI.empty())
  1061. return false;
  1062. MachineFunction &MF = *MBB.getParent();
  1063. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1064. bool isVarArg = AFI->getArgRegsSaveSize() > 0;
  1065. unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
  1066. // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
  1067. // registers. Do that here instead.
  1068. if (NumAlignedDPRCS2Regs)
  1069. emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
  1070. unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
  1071. unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
  1072. unsigned FltOpc = ARM::VLDMDIA_UPD;
  1073. emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
  1074. NumAlignedDPRCS2Regs);
  1075. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1076. &isARMArea2Register, 0);
  1077. emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
  1078. &isARMArea1Register, 0);
  1079. return true;
  1080. }
  1081. // FIXME: Make generic?
  1082. static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
  1083. const ARMBaseInstrInfo &TII) {
  1084. unsigned FnSize = 0;
  1085. for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
  1086. MBBI != E; ++MBBI) {
  1087. const MachineBasicBlock &MBB = *MBBI;
  1088. for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
  1089. I != E; ++I)
  1090. FnSize += TII.GetInstSizeInBytes(I);
  1091. }
  1092. return FnSize;
  1093. }
  1094. /// estimateRSStackSizeLimit - Look at each instruction that references stack
  1095. /// frames and return the stack size limit beyond which some of these
  1096. /// instructions will require a scratch register during their expansion later.
  1097. // FIXME: Move to TII?
  1098. static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
  1099. const TargetFrameLowering *TFI) {
  1100. const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1101. unsigned Limit = (1 << 12) - 1;
  1102. for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
  1103. for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
  1104. I != E; ++I) {
  1105. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  1106. if (!I->getOperand(i).isFI()) continue;
  1107. // When using ADDri to get the address of a stack object, 255 is the
  1108. // largest offset guaranteed to fit in the immediate offset.
  1109. if (I->getOpcode() == ARM::ADDri) {
  1110. Limit = std::min(Limit, (1U << 8) - 1);
  1111. break;
  1112. }
  1113. // Otherwise check the addressing mode.
  1114. switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
  1115. case ARMII::AddrMode3:
  1116. case ARMII::AddrModeT2_i8:
  1117. Limit = std::min(Limit, (1U << 8) - 1);
  1118. break;
  1119. case ARMII::AddrMode5:
  1120. case ARMII::AddrModeT2_i8s4:
  1121. Limit = std::min(Limit, ((1U << 8) - 1) * 4);
  1122. break;
  1123. case ARMII::AddrModeT2_i12:
  1124. // i12 supports only positive offset so these will be converted to
  1125. // i8 opcodes. See llvm::rewriteT2FrameIndex.
  1126. if (TFI->hasFP(MF) && AFI->hasStackFrame())
  1127. Limit = std::min(Limit, (1U << 8) - 1);
  1128. break;
  1129. case ARMII::AddrMode4:
  1130. case ARMII::AddrMode6:
  1131. // Addressing modes 4 & 6 (load/store) instructions can't encode an
  1132. // immediate offset for stack references.
  1133. return 0;
  1134. default:
  1135. break;
  1136. }
  1137. break; // At most one FI per instruction
  1138. }
  1139. }
  1140. }
  1141. return Limit;
  1142. }
  1143. // In functions that realign the stack, it can be an advantage to spill the
  1144. // callee-saved vector registers after realigning the stack. The vst1 and vld1
  1145. // instructions take alignment hints that can improve performance.
  1146. //
  1147. static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
  1148. MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
  1149. if (!SpillAlignedNEONRegs)
  1150. return;
  1151. // Naked functions don't spill callee-saved registers.
  1152. if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  1153. Attribute::Naked))
  1154. return;
  1155. // We are planning to use NEON instructions vst1 / vld1.
  1156. if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
  1157. return;
  1158. // Don't bother if the default stack alignment is sufficiently high.
  1159. if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
  1160. return;
  1161. // Aligned spills require stack realignment.
  1162. const ARMBaseRegisterInfo *RegInfo =
  1163. static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
  1164. if (!RegInfo->canRealignStack(MF))
  1165. return;
  1166. // We always spill contiguous d-registers starting from d8. Count how many
  1167. // needs spilling. The register allocator will almost always use the
  1168. // callee-saved registers in order, but it can happen that there are holes in
  1169. // the range. Registers above the hole will be spilled to the standard DPRCS
  1170. // area.
  1171. MachineRegisterInfo &MRI = MF.getRegInfo();
  1172. unsigned NumSpills = 0;
  1173. for (; NumSpills < 8; ++NumSpills)
  1174. if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
  1175. break;
  1176. // Don't do this for just one d-register. It's not worth it.
  1177. if (NumSpills < 2)
  1178. return;
  1179. // Spill the first NumSpills D-registers after realigning the stack.
  1180. MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
  1181. // A scratch register is required for the vst1 / vld1 instructions.
  1182. MF.getRegInfo().setPhysRegUsed(ARM::R4);
  1183. }
  1184. void
  1185. ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
  1186. RegScavenger *RS) const {
  1187. // This tells PEI to spill the FP as if it is any other callee-save register
  1188. // to take advantage the eliminateFrameIndex machinery. This also ensures it
  1189. // is spilled in the order specified by getCalleeSavedRegs() to make it easier
  1190. // to combine multiple loads / stores.
  1191. bool CanEliminateFrame = true;
  1192. bool CS1Spilled = false;
  1193. bool LRSpilled = false;
  1194. unsigned NumGPRSpills = 0;
  1195. SmallVector<unsigned, 4> UnspilledCS1GPRs;
  1196. SmallVector<unsigned, 4> UnspilledCS2GPRs;
  1197. const ARMBaseRegisterInfo *RegInfo =
  1198. static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
  1199. const ARMBaseInstrInfo &TII =
  1200. *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
  1201. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1202. MachineFrameInfo *MFI = MF.getFrameInfo();
  1203. MachineRegisterInfo &MRI = MF.getRegInfo();
  1204. unsigned FramePtr = RegInfo->getFrameRegister(MF);
  1205. // Spill R4 if Thumb2 function requires stack realignment - it will be used as
  1206. // scratch register. Also spill R4 if Thumb2 function has varsized objects,
  1207. // since it's not always possible to restore sp from fp in a single
  1208. // instruction.
  1209. // FIXME: It will be better just to find spare register here.
  1210. if (AFI->isThumb2Function() &&
  1211. (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
  1212. MRI.setPhysRegUsed(ARM::R4);
  1213. if (AFI->isThumb1OnlyFunction()) {
  1214. // Spill LR if Thumb1 function uses variable length argument lists.
  1215. if (AFI->getArgRegsSaveSize() > 0)
  1216. MRI.setPhysRegUsed(ARM::LR);
  1217. // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
  1218. // for sure what the stack size will be, but for this, an estimate is good
  1219. // enough. If there anything changes it, it'll be a spill, which implies
  1220. // we've used all the registers and so R4 is already used, so not marking
  1221. // it here will be OK.
  1222. // FIXME: It will be better just to find spare register here.
  1223. unsigned StackSize = MFI->estimateStackSize(MF);
  1224. if (MFI->hasVarSizedObjects() || StackSize > 508)
  1225. MRI.setPhysRegUsed(ARM::R4);
  1226. }
  1227. // See if we can spill vector registers to aligned stack.
  1228. checkNumAlignedDPRCS2Regs(MF);
  1229. // Spill the BasePtr if it's used.
  1230. if (RegInfo->hasBasePointer(MF))
  1231. MRI.setPhysRegUsed(RegInfo->getBaseRegister());
  1232. // Don't spill FP if the frame can be eliminated. This is determined
  1233. // by scanning the callee-save registers to see if any is used.
  1234. const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
  1235. for (unsigned i = 0; CSRegs[i]; ++i) {
  1236. unsigned Reg = CSRegs[i];
  1237. bool Spilled = false;
  1238. if (MRI.isPhysRegUsed(Reg)) {
  1239. Spilled = true;
  1240. CanEliminateFrame = false;
  1241. }
  1242. if (!ARM::GPRRegClass.contains(Reg))
  1243. continue;
  1244. if (Spilled) {
  1245. NumGPRSpills++;
  1246. if (!STI.isTargetMachO()) {
  1247. if (Reg == ARM::LR)
  1248. LRSpilled = true;
  1249. CS1Spilled = true;
  1250. continue;
  1251. }
  1252. // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
  1253. switch (Reg) {
  1254. case ARM::LR:
  1255. LRSpilled = true;
  1256. // Fallthrough
  1257. case ARM::R0: case ARM::R1:
  1258. case ARM::R2: case ARM::R3:
  1259. case ARM::R4: case ARM::R5:
  1260. case ARM::R6: case ARM::R7:
  1261. CS1Spilled = true;
  1262. break;
  1263. default:
  1264. break;
  1265. }
  1266. } else {
  1267. if (!STI.isTargetMachO()) {
  1268. UnspilledCS1GPRs.push_back(Reg);
  1269. continue;
  1270. }
  1271. switch (Reg) {
  1272. case ARM::R0: case ARM::R1:
  1273. case ARM::R2: case ARM::R3:
  1274. case ARM::R4: case ARM::R5:
  1275. case ARM::R6: case ARM::R7:
  1276. case ARM::LR:
  1277. UnspilledCS1GPRs.push_back(Reg);
  1278. break;
  1279. default:
  1280. UnspilledCS2GPRs.push_back(Reg);
  1281. break;
  1282. }
  1283. }
  1284. }
  1285. bool ForceLRSpill = false;
  1286. if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
  1287. unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
  1288. // Force LR to be spilled if the Thumb function size is > 2048. This enables
  1289. // use of BL to implement far jump. If it turns out that it's not needed
  1290. // then the branch fix up path will undo it.
  1291. if (FnSize >= (1 << 11)) {
  1292. CanEliminateFrame = false;
  1293. ForceLRSpill = true;
  1294. }
  1295. }
  1296. // If any of the stack slot references may be out of range of an immediate
  1297. // offset, make sure a register (or a spill slot) is available for the
  1298. // register scavenger. Note that if we're indexing off the frame pointer, the
  1299. // effective stack size is 4 bytes larger since the FP points to the stack
  1300. // slot of the previous FP. Also, if we have variable sized objects in the
  1301. // function, stack slot references will often be negative, and some of
  1302. // our instructions are positive-offset only, so conservatively consider
  1303. // that case to want a spill slot (or register) as well. Similarly, if
  1304. // the function adjusts the stack pointer during execution and the
  1305. // adjustments aren't already part of our stack size estimate, our offset
  1306. // calculations may be off, so be conservative.
  1307. // FIXME: We could add logic to be more precise about negative offsets
  1308. // and which instructions will need a scratch register for them. Is it
  1309. // worth the effort and added fragility?
  1310. bool BigStack =
  1311. (RS &&
  1312. (MFI->estimateStackSize(MF) +
  1313. ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
  1314. estimateRSStackSizeLimit(MF, this)))
  1315. || MFI->hasVarSizedObjects()
  1316. || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
  1317. bool ExtraCSSpill = false;
  1318. if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
  1319. AFI->setHasStackFrame(true);
  1320. // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
  1321. // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
  1322. if (!LRSpilled && CS1Spilled) {
  1323. MRI.setPhysRegUsed(ARM::LR);
  1324. NumGPRSpills++;
  1325. SmallVectorImpl<unsigned>::iterator LRPos;
  1326. LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
  1327. (unsigned)ARM::LR);
  1328. if (LRPos != UnspilledCS1GPRs.end())
  1329. UnspilledCS1GPRs.erase(LRPos);
  1330. ForceLRSpill = false;
  1331. ExtraCSSpill = true;
  1332. }
  1333. if (hasFP(MF)) {
  1334. MRI.setPhysRegUsed(FramePtr);
  1335. NumGPRSpills++;
  1336. }
  1337. // If stack and double are 8-byte aligned and we are spilling an odd number
  1338. // of GPRs, spill one extra callee save GPR so we won't have to pad between
  1339. // the integer and double callee save areas.
  1340. unsigned TargetAlign = getStackAlignment();
  1341. if (TargetAlign == 8 && (NumGPRSpills & 1)) {
  1342. if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
  1343. for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
  1344. unsigned Reg = UnspilledCS1GPRs[i];
  1345. // Don't spill high register if the function is thumb1
  1346. if (!AFI->isThumb1OnlyFunction() ||
  1347. isARMLowRegister(Reg) || Reg == ARM::LR) {
  1348. MRI.setPhysRegUsed(Reg);
  1349. if (!MRI.isReserved(Reg))
  1350. ExtraCSSpill = true;
  1351. break;
  1352. }
  1353. }
  1354. } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
  1355. unsigned Reg = UnspilledCS2GPRs.front();
  1356. MRI.setPhysRegUsed(Reg);
  1357. if (!MRI.isReserved(Reg))
  1358. ExtraCSSpill = true;
  1359. }
  1360. }
  1361. // Estimate if we might need to scavenge a register at some point in order
  1362. // to materialize a stack offset. If so, either spill one additional
  1363. // callee-saved register or reserve a special spill slot to facilitate
  1364. // register scavenging. Thumb1 needs a spill slot for stack pointer
  1365. // adjustments also, even when the frame itself is small.
  1366. if (BigStack && !ExtraCSSpill) {
  1367. // If any non-reserved CS register isn't spilled, just spill one or two
  1368. // extra. That should take care of it!
  1369. unsigned NumExtras = TargetAlign / 4;
  1370. SmallVector<unsigned, 2> Extras;
  1371. while (NumExtras && !UnspilledCS1GPRs.empty()) {
  1372. unsigned Reg = UnspilledCS1GPRs.back();
  1373. UnspilledCS1GPRs.pop_back();
  1374. if (!MRI.isReserved(Reg) &&
  1375. (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
  1376. Reg == ARM::LR)) {
  1377. Extras.push_back(Reg);
  1378. NumExtras--;
  1379. }
  1380. }
  1381. // For non-Thumb1 functions, also check for hi-reg CS registers
  1382. if (!AFI->isThumb1OnlyFunction()) {
  1383. while (NumExtras && !UnspilledCS2GPRs.empty()) {
  1384. unsigned Reg = UnspilledCS2GPRs.back();
  1385. UnspilledCS2GPRs.pop_back();
  1386. if (!MRI.isReserved(Reg)) {
  1387. Extras.push_back(Reg);
  1388. NumExtras--;
  1389. }
  1390. }
  1391. }
  1392. if (Extras.size() && NumExtras == 0) {
  1393. for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
  1394. MRI.setPhysRegUsed(Extras[i]);
  1395. }
  1396. } else if (!AFI->isThumb1OnlyFunction()) {
  1397. // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
  1398. // closest to SP or frame pointer.
  1399. const TargetRegisterClass *RC = &ARM::GPRRegClass;
  1400. RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
  1401. RC->getAlignment(),
  1402. false));
  1403. }
  1404. }
  1405. }
  1406. if (ForceLRSpill) {
  1407. MRI.setPhysRegUsed(ARM::LR);
  1408. AFI->setLRIsSpilledForFarJump(true);
  1409. }
  1410. }
  1411. void ARMFrameLowering::
  1412. eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
  1413. MachineBasicBlock::iterator I) const {
  1414. const ARMBaseInstrInfo &TII =
  1415. *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
  1416. if (!hasReservedCallFrame(MF)) {
  1417. // If we have alloca, convert as follows:
  1418. // ADJCALLSTACKDOWN -> sub, sp, sp, amount
  1419. // ADJCALLSTACKUP -> add, sp, sp, amount
  1420. MachineInstr *Old = I;
  1421. DebugLoc dl = Old->getDebugLoc();
  1422. unsigned Amount = Old->getOperand(0).getImm();
  1423. if (Amount != 0) {
  1424. // We need to keep the stack aligned properly. To do this, we round the
  1425. // amount of space needed for the outgoing arguments up to the next
  1426. // alignment boundary.
  1427. unsigned Align = getStackAlignment();
  1428. Amount = (Amount+Align-1)/Align*Align;
  1429. ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
  1430. assert(!AFI->isThumb1OnlyFunction() &&
  1431. "This eliminateCallFramePseudoInstr does not support Thumb1!");
  1432. bool isARM = !AFI->isThumbFunction();
  1433. // Replace the pseudo instruction with a new instruction...
  1434. unsigned Opc = Old->getOpcode();
  1435. int PIdx = Old->findFirstPredOperandIdx();
  1436. ARMCC::CondCodes Pred = (PIdx == -1)
  1437. ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
  1438. if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
  1439. // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
  1440. unsigned PredReg = Old->getOperand(2).getReg();
  1441. emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
  1442. Pred, PredReg);
  1443. } else {
  1444. // Note: PredReg is operand 3 for ADJCALLSTACKUP.
  1445. unsigned PredReg = Old->getOperand(3).getReg();
  1446. assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
  1447. emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
  1448. Pred, PredReg);
  1449. }
  1450. }
  1451. }
  1452. MBB.erase(I);
  1453. }