Replace PROLOG_LABEL with a new CFI_INSTRUCTION.
[oota-llvm.git] / lib / Target / AArch64 / AArch64FrameLowering.cpp
1 //===- AArch64FrameLowering.cpp - AArch64 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 AArch64 implementation of TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64.h"
15 #include "AArch64FrameLowering.h"
16 #include "AArch64InstrInfo.h"
17 #include "AArch64MachineFunctionInfo.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/MC/MachineLocation.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29
30 using namespace llvm;
31
32 void AArch64FrameLowering::splitSPAdjustments(uint64_t Total,
33                                               uint64_t &Initial,
34                                               uint64_t &Residual) const {
35   // 0x1f0 here is a pessimistic (i.e. realistic) boundary: x-register LDP
36   // instructions have a 7-bit signed immediate scaled by 8, giving a reach of
37   // 0x1f8, but stack adjustment should always be a multiple of 16.
38   if (Total <= 0x1f0) {
39     Initial = Total;
40     Residual = 0;
41   } else {
42     Initial = 0x1f0;
43     Residual = Total - Initial;
44   }
45 }
46
47 void AArch64FrameLowering::emitPrologue(MachineFunction &MF) const {
48   AArch64MachineFunctionInfo *FuncInfo =
49     MF.getInfo<AArch64MachineFunctionInfo>();
50   MachineBasicBlock &MBB = MF.front();
51   MachineBasicBlock::iterator MBBI = MBB.begin();
52   MachineFrameInfo *MFI = MF.getFrameInfo();
53   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
54   DebugLoc DL = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
55
56   MachineModuleInfo &MMI = MF.getMMI();
57   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
58   bool NeedsFrameMoves = MMI.hasDebugInfo()
59     || MF.getFunction()->needsUnwindTableEntry();
60
61   uint64_t NumInitialBytes, NumResidualBytes;
62
63   // Currently we expect the stack to be laid out by
64   //     sub sp, sp, #initial
65   //     stp x29, x30, [sp, #offset]
66   //     ...
67   //     str xxx, [sp, #offset]
68   //     sub sp, sp, #rest (possibly via extra instructions).
69   if (MFI->getCalleeSavedInfo().size()) {
70     // If there are callee-saved registers, we want to store them efficiently as
71     // a block, and virtual base assignment happens too early to do it for us so
72     // we adjust the stack in two phases: first just for callee-saved fiddling,
73     // then to allocate the rest of the frame.
74     splitSPAdjustments(MFI->getStackSize(), NumInitialBytes, NumResidualBytes);
75   } else {
76     // If there aren't any callee-saved registers, two-phase adjustment is
77     // inefficient. It's more efficient to adjust with NumInitialBytes too
78     // because when we're in a "callee pops argument space" situation, that pop
79     // must be tacked onto Initial for correctness.
80     NumInitialBytes = MFI->getStackSize();
81     NumResidualBytes = 0;
82   }
83
84   // Tell everyone else how much adjustment we're expecting them to use. In
85   // particular if an adjustment is required for a tail call the epilogue could
86   // have a different view of things.
87   FuncInfo->setInitialStackAdjust(NumInitialBytes);
88
89   emitSPUpdate(MBB, MBBI, DL, TII, AArch64::X16, -NumInitialBytes,
90                MachineInstr::FrameSetup);
91
92   if (NeedsFrameMoves && NumInitialBytes) {
93     // We emit this update even if the CFA is set from a frame pointer later so
94     // that the CFA is valid in the interim.
95     MachineLocation Dst(MachineLocation::VirtualFP);
96     unsigned Reg = MRI->getDwarfRegNum(AArch64::XSP, true);
97     unsigned CFIIndex = MMI.addFrameInst(
98         MCCFIInstruction::createDefCfa(nullptr, Reg, -NumInitialBytes));
99     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
100         .addCFIIndex(CFIIndex);
101   }
102
103   // Otherwise we need to set the frame pointer and/or add a second stack
104   // adjustment.
105
106   bool FPNeedsSetting = hasFP(MF);
107   for (; MBBI != MBB.end(); ++MBBI) {
108     // Note that this search makes strong assumptions about the operation used
109     // to store the frame-pointer: it must be "STP x29, x30, ...". This could
110     // change in future, but until then there's no point in implementing
111     // untestable more generic cases.
112     if (FPNeedsSetting && MBBI->getOpcode() == AArch64::LSPair64_STR
113                        && MBBI->getOperand(0).getReg() == AArch64::X29) {
114       int64_t X29FrameIdx = MBBI->getOperand(2).getIndex();
115       FuncInfo->setFramePointerOffset(MFI->getObjectOffset(X29FrameIdx));
116
117       ++MBBI;
118       emitRegUpdate(MBB, MBBI, DL, TII, AArch64::X29, AArch64::XSP,
119                     AArch64::X29,
120                     NumInitialBytes + MFI->getObjectOffset(X29FrameIdx),
121                     MachineInstr::FrameSetup);
122
123       // The offset adjustment used when emitting debugging locations relative
124       // to whatever frame base is set. AArch64 uses the default frame base (FP
125       // or SP) and this adjusts the calculations to be correct.
126       MFI->setOffsetAdjustment(- MFI->getObjectOffset(X29FrameIdx)
127                                - MFI->getStackSize());
128
129       if (NeedsFrameMoves) {
130         unsigned Reg = MRI->getDwarfRegNum(AArch64::X29, true);
131         unsigned Offset = MFI->getObjectOffset(X29FrameIdx);
132         unsigned CFIIndex = MMI.addFrameInst(
133             MCCFIInstruction::createDefCfa(nullptr, Reg, Offset));
134         BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
135             .addCFIIndex(CFIIndex);
136       }
137
138       FPNeedsSetting = false;
139     }
140
141     if (!MBBI->getFlag(MachineInstr::FrameSetup))
142       break;
143   }
144
145   assert(!FPNeedsSetting && "Frame pointer couldn't be set");
146
147   emitSPUpdate(MBB, MBBI, DL, TII, AArch64::X16, -NumResidualBytes,
148                MachineInstr::FrameSetup);
149
150   // Now we emit the rest of the frame setup information, if necessary: we've
151   // already noted the FP and initial SP moves so we're left with the prologue's
152   // final SP update and callee-saved register locations.
153   if (!NeedsFrameMoves)
154     return;
155
156   // The rest of the stack adjustment
157   if (!hasFP(MF) && NumResidualBytes) {
158     MachineLocation Dst(MachineLocation::VirtualFP);
159     unsigned Reg = MRI->getDwarfRegNum(AArch64::XSP, true);
160     unsigned Offset = NumResidualBytes + NumInitialBytes;
161     unsigned CFIIndex =
162         MMI.addFrameInst(MCCFIInstruction::createDefCfa(nullptr, Reg, -Offset));
163     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
164         .addCFIIndex(CFIIndex);
165   }
166
167   // And any callee-saved registers (it's fine to leave them to the end here,
168   // because the old values are still valid at this point.
169   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
170   if (CSI.size()) {
171     for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
172            E = CSI.end(); I != E; ++I) {
173       unsigned Offset = MFI->getObjectOffset(I->getFrameIdx());
174       unsigned Reg = MRI->getDwarfRegNum(I->getReg(), true);
175       unsigned CFIIndex = MMI.addFrameInst(
176           MCCFIInstruction::createOffset(nullptr, Reg, Offset));
177       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
178           .addCFIIndex(CFIIndex);
179     }
180   }
181 }
182
183 void
184 AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
185                                    MachineBasicBlock &MBB) const {
186   AArch64MachineFunctionInfo *FuncInfo =
187     MF.getInfo<AArch64MachineFunctionInfo>();
188
189   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
190   DebugLoc DL = MBBI->getDebugLoc();
191   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
192   MachineFrameInfo &MFI = *MF.getFrameInfo();
193   unsigned RetOpcode = MBBI->getOpcode();
194
195   // Initial and residual are named for consitency with the prologue. Note that
196   // in the epilogue, the residual adjustment is executed first.
197   uint64_t NumInitialBytes = FuncInfo->getInitialStackAdjust();
198   uint64_t NumResidualBytes = MFI.getStackSize() - NumInitialBytes;
199   uint64_t ArgumentPopSize = 0;
200   if (RetOpcode == AArch64::TC_RETURNdi ||
201       RetOpcode == AArch64::TC_RETURNxi) {
202     MachineOperand &JumpTarget = MBBI->getOperand(0);
203     MachineOperand &StackAdjust = MBBI->getOperand(1);
204
205     MachineInstrBuilder MIB;
206     if (RetOpcode == AArch64::TC_RETURNdi) {
207       MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::TAIL_Bimm));
208       if (JumpTarget.isGlobal()) {
209         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
210                              JumpTarget.getTargetFlags());
211       } else {
212         assert(JumpTarget.isSymbol() && "unexpected tail call destination");
213         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
214                               JumpTarget.getTargetFlags());
215       }
216     } else {
217       assert(RetOpcode == AArch64::TC_RETURNxi && JumpTarget.isReg()
218              && "Unexpected tail call");
219
220       MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::TAIL_BRx));
221       MIB.addReg(JumpTarget.getReg(), RegState::Kill);
222     }
223
224     // Add the extra operands onto the new tail call instruction even though
225     // they're not used directly (so that liveness is tracked properly etc).
226     for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
227         MIB->addOperand(MBBI->getOperand(i));
228
229
230     // Delete the pseudo instruction TC_RETURN.
231     MachineInstr *NewMI = std::prev(MBBI);
232     MBB.erase(MBBI);
233     MBBI = NewMI;
234
235     // For a tail-call in a callee-pops-arguments environment, some or all of
236     // the stack may actually be in use for the call's arguments, this is
237     // calculated during LowerCall and consumed here...
238     ArgumentPopSize = StackAdjust.getImm();
239   } else {
240     // ... otherwise the amount to pop is *all* of the argument space,
241     // conveniently stored in the MachineFunctionInfo by
242     // LowerFormalArguments. This will, of course, be zero for the C calling
243     // convention.
244     ArgumentPopSize = FuncInfo->getArgumentStackToRestore();
245   }
246
247   assert(NumInitialBytes % 16 == 0 && NumResidualBytes % 16 == 0
248          && "refusing to adjust stack by misaligned amt");
249
250   // We may need to address callee-saved registers differently, so find out the
251   // bound on the frame indices.
252   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
253   int MinCSFI = 0;
254   int MaxCSFI = -1;
255
256   if (CSI.size()) {
257     MinCSFI = CSI[0].getFrameIdx();
258     MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
259   }
260
261   // The "residual" stack update comes first from this direction and guarantees
262   // that SP is NumInitialBytes below its value on function entry, either by a
263   // direct update or restoring it from the frame pointer.
264   if (NumInitialBytes + ArgumentPopSize != 0) {
265     emitSPUpdate(MBB, MBBI, DL, TII, AArch64::X16,
266                  NumInitialBytes + ArgumentPopSize);
267     --MBBI;
268   }
269
270
271   // MBBI now points to the instruction just past the last callee-saved
272   // restoration (either RET/B if NumInitialBytes == 0, or the "ADD sp, sp"
273   // otherwise).
274
275   // Now we need to find out where to put the bulk of the stack adjustment
276   MachineBasicBlock::iterator FirstEpilogue = MBBI;
277   while (MBBI != MBB.begin()) {
278     --MBBI;
279
280     unsigned FrameOp;
281     for (FrameOp = 0; FrameOp < MBBI->getNumOperands(); ++FrameOp) {
282       if (MBBI->getOperand(FrameOp).isFI())
283         break;
284     }
285
286     // If this instruction doesn't have a frame index we've reached the end of
287     // the callee-save restoration.
288     if (FrameOp == MBBI->getNumOperands())
289       break;
290
291     // Likewise if it *is* a local reference, but not to a callee-saved object.
292     int FrameIdx = MBBI->getOperand(FrameOp).getIndex();
293     if (FrameIdx < MinCSFI || FrameIdx > MaxCSFI)
294       break;
295
296     FirstEpilogue = MBBI;
297   }
298
299   if (MF.getFrameInfo()->hasVarSizedObjects()) {
300     int64_t StaticFrameBase;
301     StaticFrameBase = -(NumInitialBytes + FuncInfo->getFramePointerOffset());
302     emitRegUpdate(MBB, FirstEpilogue, DL, TII,
303                   AArch64::XSP, AArch64::X29, AArch64::NoRegister,
304                   StaticFrameBase);
305   } else {
306     emitSPUpdate(MBB, FirstEpilogue, DL,TII, AArch64::X16, NumResidualBytes);
307   }
308 }
309
310 int64_t
311 AArch64FrameLowering::resolveFrameIndexReference(MachineFunction &MF,
312                                                  int FrameIndex,
313                                                  unsigned &FrameReg,
314                                                  int SPAdj,
315                                                  bool IsCalleeSaveOp) const {
316   AArch64MachineFunctionInfo *FuncInfo =
317     MF.getInfo<AArch64MachineFunctionInfo>();
318   MachineFrameInfo *MFI = MF.getFrameInfo();
319
320   int64_t TopOfFrameOffset = MFI->getObjectOffset(FrameIndex);
321
322   assert(!(IsCalleeSaveOp && FuncInfo->getInitialStackAdjust() == 0)
323          && "callee-saved register in unexpected place");
324
325   // If the frame for this function is particularly large, we adjust the stack
326   // in two phases which means the callee-save related operations see a
327   // different (intermediate) stack size.
328   int64_t FrameRegPos;
329   if (IsCalleeSaveOp) {
330     FrameReg = AArch64::XSP;
331     FrameRegPos = -static_cast<int64_t>(FuncInfo->getInitialStackAdjust());
332   } else if (useFPForAddressing(MF)) {
333     // Have to use the frame pointer since we have no idea where SP is.
334     FrameReg = AArch64::X29;
335     FrameRegPos = FuncInfo->getFramePointerOffset();
336   } else {
337     FrameReg = AArch64::XSP;
338     FrameRegPos = -static_cast<int64_t>(MFI->getStackSize()) + SPAdj;
339   }
340
341   return TopOfFrameOffset - FrameRegPos;
342 }
343
344 void
345 AArch64FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
346                                                        RegScavenger *RS) const {
347   const AArch64RegisterInfo *RegInfo =
348     static_cast<const AArch64RegisterInfo *>(MF.getTarget().getRegisterInfo());
349   MachineFrameInfo *MFI = MF.getFrameInfo();
350   const AArch64InstrInfo &TII =
351     *static_cast<const AArch64InstrInfo *>(MF.getTarget().getInstrInfo());
352
353   if (hasFP(MF)) {
354     MF.getRegInfo().setPhysRegUsed(AArch64::X29);
355     MF.getRegInfo().setPhysRegUsed(AArch64::X30);
356   }
357
358   // If addressing of local variables is going to be more complicated than
359   // shoving a base register and an offset into the instruction then we may well
360   // need to scavenge registers. We should either specifically add an
361   // callee-save register for this purpose or allocate an extra spill slot.
362   bool BigStack =
363     MFI->estimateStackSize(MF) >= TII.estimateRSStackLimit(MF)
364     || MFI->hasVarSizedObjects() // Access will be from X29: messes things up
365     || (MFI->adjustsStack() && !hasReservedCallFrame(MF));
366
367   if (!BigStack)
368     return;
369
370   // We certainly need some slack space for the scavenger, preferably an extra
371   // register.
372   const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs();
373   uint16_t ExtraReg = AArch64::NoRegister;
374
375   for (unsigned i = 0; CSRegs[i]; ++i) {
376     if (AArch64::GPR64RegClass.contains(CSRegs[i]) &&
377         !MF.getRegInfo().isPhysRegUsed(CSRegs[i])) {
378       ExtraReg = CSRegs[i];
379       break;
380     }
381   }
382
383   if (ExtraReg != 0) {
384     MF.getRegInfo().setPhysRegUsed(ExtraReg);
385   } else {
386     assert(RS && "Expect register scavenger to be available");
387
388     // Create a stack slot for scavenging purposes. PrologEpilogInserter
389     // helpfully places it near either SP or FP for us to avoid
390     // infinitely-regression during scavenging.
391     const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
392     RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
393                                                        RC->getAlignment(),
394                                                        false));
395   }
396 }
397
398 bool AArch64FrameLowering::determinePrologueDeath(MachineBasicBlock &MBB,
399                                                   unsigned Reg) const {
400   // If @llvm.returnaddress is called then it will refer to X30 by some means;
401   // the prologue store does not kill the register.
402   if (Reg == AArch64::X30) {
403     if (MBB.getParent()->getFrameInfo()->isReturnAddressTaken()
404         && MBB.getParent()->getRegInfo().isLiveIn(Reg))
405     return false;
406   }
407
408   // In all other cases, physical registers are dead after they've been saved
409   // but live at the beginning of the prologue block.
410   MBB.addLiveIn(Reg);
411   return true;
412 }
413
414 void
415 AArch64FrameLowering::emitFrameMemOps(bool isPrologue, MachineBasicBlock &MBB,
416                                       MachineBasicBlock::iterator MBBI,
417                                       const std::vector<CalleeSavedInfo> &CSI,
418                                       const TargetRegisterInfo *TRI,
419                                       const LoadStoreMethod PossClasses[],
420                                       unsigned NumClasses) const {
421   DebugLoc DL = MBB.findDebugLoc(MBBI);
422   MachineFunction &MF = *MBB.getParent();
423   MachineFrameInfo &MFI = *MF.getFrameInfo();
424   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
425
426   // A certain amount of implicit contract is present here. The actual stack
427   // offsets haven't been allocated officially yet, so for strictly correct code
428   // we rely on the fact that the elements of CSI are allocated in order
429   // starting at SP, purely as dictated by size and alignment. In practice since
430   // this function handles the only accesses to those slots it's not quite so
431   // important.
432   //
433   // We have also ordered the Callee-saved register list in AArch64CallingConv
434   // so that the above scheme puts registers in order: in particular we want
435   // &X30 to be &X29+8 for an ABI-correct frame record (PCS 5.2.2)
436   for (unsigned i = 0, e = CSI.size(); i < e; ++i) {
437     unsigned Reg = CSI[i].getReg();
438
439     // First we need to find out which register class the register belongs to so
440     // that we can use the correct load/store instrucitons.
441     unsigned ClassIdx;
442     for (ClassIdx = 0; ClassIdx < NumClasses; ++ClassIdx) {
443       if (PossClasses[ClassIdx].RegClass->contains(Reg))
444         break;
445     }
446     assert(ClassIdx != NumClasses
447            && "Asked to store register in unexpected class");
448     const TargetRegisterClass &TheClass = *PossClasses[ClassIdx].RegClass;
449
450     // Now we need to decide whether it's possible to emit a paired instruction:
451     // for this we want the next register to be in the same class.
452     MachineInstrBuilder NewMI;
453     bool Pair = false;
454     if (i + 1 < CSI.size() && TheClass.contains(CSI[i+1].getReg())) {
455       Pair = true;
456       unsigned StLow = 0, StHigh = 0;
457       if (isPrologue) {
458         // Most of these registers will be live-in to the MBB and killed by our
459         // store, though there are exceptions (see determinePrologueDeath).
460         StLow = getKillRegState(determinePrologueDeath(MBB, CSI[i+1].getReg()));
461         StHigh = getKillRegState(determinePrologueDeath(MBB, CSI[i].getReg()));
462       } else {
463         StLow = RegState::Define;
464         StHigh = RegState::Define;
465       }
466
467       NewMI = BuildMI(MBB, MBBI, DL, TII.get(PossClasses[ClassIdx].PairOpcode))
468                 .addReg(CSI[i+1].getReg(), StLow)
469                 .addReg(CSI[i].getReg(), StHigh);
470
471       // If it's a paired op, we've consumed two registers
472       ++i;
473     } else {
474       unsigned State;
475       if (isPrologue) {
476         State = getKillRegState(determinePrologueDeath(MBB, CSI[i].getReg()));
477       } else {
478         State = RegState::Define;
479       }
480
481       NewMI = BuildMI(MBB, MBBI, DL,
482                       TII.get(PossClasses[ClassIdx].SingleOpcode))
483                 .addReg(CSI[i].getReg(), State);
484     }
485
486     // Note that the FrameIdx refers to the second register in a pair: it will
487     // be allocated the smaller numeric address and so is the one an LDP/STP
488     // address must use.
489     int FrameIdx = CSI[i].getFrameIdx();
490     MachineMemOperand::MemOperandFlags Flags;
491     Flags = isPrologue ? MachineMemOperand::MOStore : MachineMemOperand::MOLoad;
492     MachineMemOperand *MMO =
493       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
494                              Flags,
495                              Pair ? TheClass.getSize() * 2 : TheClass.getSize(),
496                              MFI.getObjectAlignment(FrameIdx));
497
498     NewMI.addFrameIndex(FrameIdx)
499       .addImm(0)                  // address-register offset
500       .addMemOperand(MMO);
501
502     if (isPrologue)
503       NewMI.setMIFlags(MachineInstr::FrameSetup);
504
505     // For aesthetic reasons, during an epilogue we want to emit complementary
506     // operations to the prologue, but in the opposite order. So we still
507     // iterate through the CalleeSavedInfo list in order, but we put the
508     // instructions successively earlier in the MBB.
509     if (!isPrologue)
510       --MBBI;
511   }
512 }
513
514 bool
515 AArch64FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
516                                         MachineBasicBlock::iterator MBBI,
517                                         const std::vector<CalleeSavedInfo> &CSI,
518                                         const TargetRegisterInfo *TRI) const {
519   if (CSI.empty())
520     return false;
521
522   static const LoadStoreMethod PossibleClasses[] = {
523     {&AArch64::GPR64RegClass, AArch64::LSPair64_STR, AArch64::LS64_STR},
524     {&AArch64::FPR64RegClass, AArch64::LSFPPair64_STR, AArch64::LSFP64_STR},
525   };
526   const unsigned NumClasses = llvm::array_lengthof(PossibleClasses);
527
528   emitFrameMemOps(/* isPrologue = */ true, MBB, MBBI, CSI, TRI,
529                   PossibleClasses, NumClasses);
530
531   return true;
532 }
533
534 bool
535 AArch64FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
536                                         MachineBasicBlock::iterator MBBI,
537                                         const std::vector<CalleeSavedInfo> &CSI,
538                                         const TargetRegisterInfo *TRI) const {
539
540   if (CSI.empty())
541     return false;
542
543   static const LoadStoreMethod PossibleClasses[] = {
544     {&AArch64::GPR64RegClass, AArch64::LSPair64_LDR, AArch64::LS64_LDR},
545     {&AArch64::FPR64RegClass, AArch64::LSFPPair64_LDR, AArch64::LSFP64_LDR},
546   };
547   const unsigned NumClasses = llvm::array_lengthof(PossibleClasses);
548
549   emitFrameMemOps(/* isPrologue = */ false, MBB, MBBI, CSI, TRI,
550                   PossibleClasses, NumClasses);
551
552   return true;
553 }
554
555 bool
556 AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
557   const MachineFrameInfo *MFI = MF.getFrameInfo();
558   const TargetRegisterInfo *RI = MF.getTarget().getRegisterInfo();
559
560   // This is a decision of ABI compliance. The AArch64 PCS gives various options
561   // for conformance, and even at the most stringent level more or less permits
562   // elimination for leaf functions because there's no loss of functionality
563   // (for debugging etc)..
564   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->hasCalls())
565     return true;
566
567   // The following are hard-limits: incorrect code will be generated if we try
568   // to omit the frame.
569   return (RI->needsStackRealignment(MF) ||
570           MFI->hasVarSizedObjects() ||
571           MFI->isFrameAddressTaken());
572 }
573
574 bool
575 AArch64FrameLowering::useFPForAddressing(const MachineFunction &MF) const {
576   return MF.getFrameInfo()->hasVarSizedObjects();
577 }
578
579 bool
580 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
581   const MachineFrameInfo *MFI = MF.getFrameInfo();
582
583   // Of the various reasons for having a frame pointer, it's actually only
584   // variable-sized objects that prevent reservation of a call frame.
585   return !(hasFP(MF) && MFI->hasVarSizedObjects());
586 }
587
588 void
589 AArch64FrameLowering::eliminateCallFramePseudoInstr(
590                                 MachineFunction &MF,
591                                 MachineBasicBlock &MBB,
592                                 MachineBasicBlock::iterator MI) const {
593   const AArch64InstrInfo &TII =
594     *static_cast<const AArch64InstrInfo *>(MF.getTarget().getInstrInfo());
595   DebugLoc dl = MI->getDebugLoc();
596   int Opcode = MI->getOpcode();
597   bool IsDestroy = Opcode == TII.getCallFrameDestroyOpcode();
598   uint64_t CalleePopAmount = IsDestroy ? MI->getOperand(1).getImm() : 0;
599
600   if (!hasReservedCallFrame(MF)) {
601     unsigned Align = getStackAlignment();
602
603     int64_t Amount = MI->getOperand(0).getImm();
604     Amount = RoundUpToAlignment(Amount, Align);
605     if (!IsDestroy) Amount = -Amount;
606
607     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
608     // doesn't have to pop anything), then the first operand will be zero too so
609     // this adjustment is a no-op.
610     if (CalleePopAmount == 0) {
611       // FIXME: in-function stack adjustment for calls is limited to 12-bits
612       // because there's no guaranteed temporary register available. Mostly call
613       // frames will be allocated at the start of a function so this is OK, but
614       // it is a limitation that needs dealing with.
615       assert(Amount > -0xfff && Amount < 0xfff && "call frame too large");
616       emitSPUpdate(MBB, MI, dl, TII, AArch64::NoRegister, Amount);
617     }
618   } else if (CalleePopAmount != 0) {
619     // If the calling convention demands that the callee pops arguments from the
620     // stack, we want to add it back if we have a reserved call frame.
621     assert(CalleePopAmount < 0xfff && "call frame too large");
622     emitSPUpdate(MBB, MI, dl, TII, AArch64::NoRegister, -CalleePopAmount);
623   }
624
625   MBB.erase(MI);
626 }