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