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