3f63d049c34ed109fb8007a1103ef8bac6a2e294
[oota-llvm.git] / lib / Target / AArch64 / AArch64FrameLowering.cpp
1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
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 // On AArch64, stack frames are structured as follows:
13 //
14 // The stack grows downward.
15 //
16 // All of the individual frame areas on the frame below are optional, i.e. it's
17 // possible to create a function so that the particular area isn't present
18 // in the frame.
19 //
20 // At function entry, the "frame" looks as follows:
21 //
22 // |                                   | Higher address
23 // |-----------------------------------|
24 // |                                   |
25 // | arguments passed on the stack     |
26 // |                                   |
27 // |-----------------------------------| <- sp
28 // |                                   | Lower address
29 //
30 //
31 // After the prologue has run, the frame has the following general structure.
32 // Note that this doesn't depict the case where a red-zone is used. Also,
33 // technically the last frame area (VLAs) doesn't get created until in the
34 // main function body, after the prologue is run. However, it's depicted here
35 // for completeness.
36 //
37 // |                                   | Higher address
38 // |-----------------------------------|
39 // |                                   |
40 // | arguments passed on the stack     |
41 // |                                   |
42 // |-----------------------------------|
43 // |                                   |
44 // | prev_fp, prev_lr                  |
45 // | (a.k.a. "frame record")           |
46 // |-----------------------------------| <- fp(=x29)
47 // |                                   |
48 // | other callee-saved registers      |
49 // |                                   |
50 // |-----------------------------------|
51 // |.empty.space.to.make.part.below....|
52 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
53 // |.the.standard.16-byte.alignment....|  compile time; if present)
54 // |-----------------------------------|
55 // |                                   |
56 // | local variables of fixed size     |
57 // | including spill slots             |
58 // |-----------------------------------| <- bp(not defined by ABI,
59 // |.variable-sized.local.variables....|       LLVM chooses X19)
60 // |.(VLAs)............................| (size of this area is unknown at
61 // |...................................|  compile time)
62 // |-----------------------------------| <- sp
63 // |                                   | Lower address
64 //
65 //
66 // To access the data in a frame, at-compile time, a constant offset must be
67 // computable from one of the pointers (fp, bp, sp) to access it. The size
68 // of the areas with a dotted background cannot be computed at compile-time
69 // if they are present, making it required to have all three of fp, bp and
70 // sp to be set up to be able to access all contents in the frame areas,
71 // assuming all of the frame areas are non-empty.
72 //
73 // For most functions, some of the frame areas are empty. For those functions,
74 // it may not be necessary to set up fp or bp:
75 // * A base pointer is definitely needed when there are both VLAs and local
76 //   variables with more-than-default alignment requirements.
77 // * A frame pointer is definitely needed when there are local variables with
78 //   more-than-default alignment requirements.
79 //
80 // In some cases when a base pointer is not strictly needed, it is generated
81 // anyway when offsets from the frame pointer to access local variables become
82 // so large that the offset can't be encoded in the immediate fields of loads
83 // or stores.
84 //
85 // FIXME: also explain the redzone concept.
86 // FIXME: also explain the concept of reserved call frames.
87 //
88 //===----------------------------------------------------------------------===//
89
90 #include "AArch64FrameLowering.h"
91 #include "AArch64InstrInfo.h"
92 #include "AArch64MachineFunctionInfo.h"
93 #include "AArch64Subtarget.h"
94 #include "AArch64TargetMachine.h"
95 #include "llvm/ADT/Statistic.h"
96 #include "llvm/CodeGen/MachineFrameInfo.h"
97 #include "llvm/CodeGen/MachineFunction.h"
98 #include "llvm/CodeGen/MachineInstrBuilder.h"
99 #include "llvm/CodeGen/MachineModuleInfo.h"
100 #include "llvm/CodeGen/MachineRegisterInfo.h"
101 #include "llvm/CodeGen/RegisterScavenging.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/Function.h"
104 #include "llvm/Support/CommandLine.h"
105 #include "llvm/Support/Debug.h"
106 #include "llvm/Support/raw_ostream.h"
107
108 using namespace llvm;
109
110 #define DEBUG_TYPE "frame-info"
111
112 static cl::opt<bool> EnableRedZone("aarch64-redzone",
113                                    cl::desc("enable use of redzone on AArch64"),
114                                    cl::init(false), cl::Hidden);
115
116 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone");
117
118 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const {
119   if (!EnableRedZone)
120     return false;
121   // Don't use the red zone if the function explicitly asks us not to.
122   // This is typically used for kernel code.
123   if (MF.getFunction()->hasFnAttribute(Attribute::NoRedZone))
124     return false;
125
126   const MachineFrameInfo *MFI = MF.getFrameInfo();
127   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
128   unsigned NumBytes = AFI->getLocalStackSize();
129
130   // Note: currently hasFP() is always true for hasCalls(), but that's an
131   // implementation detail of the current code, not a strict requirement,
132   // so stay safe here and check both.
133   if (MFI->hasCalls() || hasFP(MF) || NumBytes > 128)
134     return false;
135   return true;
136 }
137
138 /// hasFP - Return true if the specified function should have a dedicated frame
139 /// pointer register.
140 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const {
141   const MachineFrameInfo *MFI = MF.getFrameInfo();
142   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
143   return (MFI->hasCalls() || MFI->hasVarSizedObjects() ||
144           MFI->isFrameAddressTaken() || MFI->hasStackMap() ||
145           MFI->hasPatchPoint() || RegInfo->needsStackRealignment(MF));
146 }
147
148 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
149 /// not required, we reserve argument space for call sites in the function
150 /// immediately on entry to the current function.  This eliminates the need for
151 /// add/sub sp brackets around call sites.  Returns true if the call frame is
152 /// included as part of the stack frame.
153 bool
154 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
155   return !MF.getFrameInfo()->hasVarSizedObjects();
156 }
157
158 void AArch64FrameLowering::eliminateCallFramePseudoInstr(
159     MachineFunction &MF, MachineBasicBlock &MBB,
160     MachineBasicBlock::iterator I) const {
161   const AArch64InstrInfo *TII =
162       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
163   DebugLoc DL = I->getDebugLoc();
164   unsigned Opc = I->getOpcode();
165   bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
166   uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
167
168   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
169   if (!TFI->hasReservedCallFrame(MF)) {
170     unsigned Align = getStackAlignment();
171
172     int64_t Amount = I->getOperand(0).getImm();
173     Amount = RoundUpToAlignment(Amount, Align);
174     if (!IsDestroy)
175       Amount = -Amount;
176
177     // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
178     // doesn't have to pop anything), then the first operand will be zero too so
179     // this adjustment is a no-op.
180     if (CalleePopAmount == 0) {
181       // FIXME: in-function stack adjustment for calls is limited to 24-bits
182       // because there's no guaranteed temporary register available.
183       //
184       // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
185       // 1) For offset <= 12-bit, we use LSL #0
186       // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
187       // LSL #0, and the other uses LSL #12.
188       //
189       // Mostly call frames will be allocated at the start of a function so
190       // this is OK, but it is a limitation that needs dealing with.
191       assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
192       emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII);
193     }
194   } else if (CalleePopAmount != 0) {
195     // If the calling convention demands that the callee pops arguments from the
196     // stack, we want to add it back if we have a reserved call frame.
197     assert(CalleePopAmount < 0xffffff && "call frame too large");
198     emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount,
199                     TII);
200   }
201   MBB.erase(I);
202 }
203
204 void AArch64FrameLowering::emitCalleeSavedFrameMoves(
205     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
206     unsigned FramePtr) const {
207   MachineFunction &MF = *MBB.getParent();
208   MachineFrameInfo *MFI = MF.getFrameInfo();
209   MachineModuleInfo &MMI = MF.getMMI();
210   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
211   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
212   DebugLoc DL = MBB.findDebugLoc(MBBI);
213
214   // Add callee saved registers to move list.
215   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
216   if (CSI.empty())
217     return;
218
219   const DataLayout &TD = MF.getDataLayout();
220   bool HasFP = hasFP(MF);
221
222   // Calculate amount of bytes used for return address storing.
223   int stackGrowth = -TD.getPointerSize(0);
224
225   // Calculate offsets.
226   int64_t saveAreaOffset = (HasFP ? 2 : 1) * stackGrowth;
227   unsigned TotalSkipped = 0;
228   for (const auto &Info : CSI) {
229     unsigned Reg = Info.getReg();
230     int64_t Offset = MFI->getObjectOffset(Info.getFrameIdx()) -
231                      getOffsetOfLocalArea() + saveAreaOffset;
232
233     // Don't output a new CFI directive if we're re-saving the frame pointer or
234     // link register. This happens when the PrologEpilogInserter has inserted an
235     // extra "STP" of the frame pointer and link register -- the "emitPrologue"
236     // method automatically generates the directives when frame pointers are
237     // used. If we generate CFI directives for the extra "STP"s, the linker will
238     // lose track of the correct values for the frame pointer and link register.
239     if (HasFP && (FramePtr == Reg || Reg == AArch64::LR)) {
240       TotalSkipped += stackGrowth;
241       continue;
242     }
243
244     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
245     unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
246         nullptr, DwarfReg, Offset - TotalSkipped));
247     BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
248         .addCFIIndex(CFIIndex)
249         .setMIFlags(MachineInstr::FrameSetup);
250   }
251 }
252
253 /// Get FPOffset by analyzing the first instruction.
254 static int getFPOffsetInPrologue(MachineInstr *MBBI) {
255   // First instruction must a) allocate the stack  and b) have an immediate
256   // that is a multiple of -2.
257   assert(((MBBI->getOpcode() == AArch64::STPXpre ||
258            MBBI->getOpcode() == AArch64::STPDpre) &&
259           MBBI->getOperand(3).getReg() == AArch64::SP &&
260           MBBI->getOperand(4).getImm() < 0 &&
261           (MBBI->getOperand(4).getImm() & 1) == 0));
262
263   // Frame pointer is fp = sp - 16. Since the  STPXpre subtracts the space
264   // required for the callee saved register area we get the frame pointer
265   // by addding that offset - 16 = -getImm()*8 - 2*8 = -(getImm() + 2) * 8.
266   int FPOffset = -(MBBI->getOperand(4).getImm() + 2) * 8;
267   assert(FPOffset >= 0 && "Bad Framepointer Offset");
268   return FPOffset;
269 }
270
271 static bool isCSSave(MachineInstr *MBBI) {
272   return MBBI->getOpcode() == AArch64::STPXi ||
273          MBBI->getOpcode() == AArch64::STPDi ||
274          MBBI->getOpcode() == AArch64::STPXpre ||
275          MBBI->getOpcode() == AArch64::STPDpre;
276 }
277
278 bool AArch64FrameLowering::canUseAsPrologue(
279     const MachineBasicBlock &MBB) const {
280   const MachineFunction *MF = MBB.getParent();
281   const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
282   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
283
284   // Don't need a scratch register if we're not going to re-align the stack.
285   // Otherwise, we may need a scratch register to be available and we do not
286   // support that for now.
287   return !RegInfo->needsStackRealignment(*MF);
288 }
289
290 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
291                                         MachineBasicBlock &MBB) const {
292   MachineBasicBlock::iterator MBBI = MBB.begin();
293   const MachineFrameInfo *MFI = MF.getFrameInfo();
294   const Function *Fn = MF.getFunction();
295   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
296   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
297   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
298   MachineModuleInfo &MMI = MF.getMMI();
299   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
300   bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
301   bool HasFP = hasFP(MF);
302
303   // Debug location must be unknown since the first debug location is used
304   // to determine the end of the prologue.
305   DebugLoc DL;
306
307   // All calls are tail calls in GHC calling conv, and functions have no
308   // prologue/epilogue.
309   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
310     return;
311
312   int NumBytes = (int)MFI->getStackSize();
313   if (!AFI->hasStackFrame()) {
314     assert(!HasFP && "unexpected function without stack frame but with FP");
315
316     // All of the stack allocation is for locals.
317     AFI->setLocalStackSize(NumBytes);
318
319     // Label used to tie together the PROLOG_LABEL and the MachineMoves.
320     MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
321
322     // REDZONE: If the stack size is less than 128 bytes, we don't need
323     // to actually allocate.
324     if (NumBytes && !canUseRedZone(MF)) {
325       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
326                       MachineInstr::FrameSetup);
327
328       // Encode the stack size of the leaf function.
329       unsigned CFIIndex = MMI.addFrameInst(
330           MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
331       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
332           .addCFIIndex(CFIIndex)
333           .setMIFlags(MachineInstr::FrameSetup);
334     } else if (NumBytes) {
335       ++NumRedZoneFunctions;
336     }
337
338     return;
339   }
340
341   // Only set up FP if we actually need to.
342   int FPOffset = 0;
343   if (HasFP)
344     FPOffset = getFPOffsetInPrologue(MBBI);
345
346   // Move past the saves of the callee-saved registers.
347   while (isCSSave(MBBI)) {
348     ++MBBI;
349     NumBytes -= 16;
350   }
351   assert(NumBytes >= 0 && "Negative stack allocation size!?");
352   if (HasFP) {
353     // Issue    sub fp, sp, FPOffset or
354     //          mov fp,sp          when FPOffset is zero.
355     // Note: All stores of callee-saved registers are marked as "FrameSetup".
356     // This code marks the instruction(s) that set the FP also.
357     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
358                     MachineInstr::FrameSetup);
359   }
360
361   // All of the remaining stack allocations are for locals.
362   AFI->setLocalStackSize(NumBytes);
363
364   // Allocate space for the rest of the frame.
365
366   const unsigned Alignment = MFI->getMaxAlignment();
367   const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
368   unsigned scratchSPReg = AArch64::SP;
369   if (NumBytes && NeedsRealignment) {
370     // Use the first callee-saved register as a scratch register.
371     scratchSPReg = AArch64::X9;
372   }
373
374   // If we're a leaf function, try using the red zone.
375   if (NumBytes && !canUseRedZone(MF))
376     // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
377     // the correct value here, as NumBytes also includes padding bytes,
378     // which shouldn't be counted here.
379     emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
380                     MachineInstr::FrameSetup);
381
382   if (NumBytes && NeedsRealignment) {
383     const unsigned NrBitsToZero = countTrailingZeros(Alignment);
384     assert(NrBitsToZero > 1);
385     assert(scratchSPReg != AArch64::SP);
386
387     // SUB X9, SP, NumBytes
388     //   -- X9 is temporary register, so shouldn't contain any live data here,
389     //   -- free to use. This is already produced by emitFrameOffset above.
390     // AND SP, X9, 0b11111...0000
391     // The logical immediates have a non-trivial encoding. The following
392     // formula computes the encoded immediate with all ones but
393     // NrBitsToZero zero bits as least significant bits.
394     uint32_t andMaskEncoded =
395         (1                   <<12) // = N
396       | ((64-NrBitsToZero)   << 6) // immr
397       | ((64-NrBitsToZero-1) << 0) // imms
398       ;
399     BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
400       .addReg(scratchSPReg, RegState::Kill)
401       .addImm(andMaskEncoded);
402   }
403
404   // If we need a base pointer, set it up here. It's whatever the value of the
405   // stack pointer is at this point. Any variable size objects will be allocated
406   // after this, so we can still use the base pointer to reference locals.
407   //
408   // FIXME: Clarify FrameSetup flags here.
409   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
410   // needed.
411   if (RegInfo->hasBasePointer(MF)) {
412     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
413                      false);
414   }
415
416   if (needsFrameMoves) {
417     const DataLayout &TD = MF.getDataLayout();
418     const int StackGrowth = -TD.getPointerSize(0);
419     unsigned FramePtr = RegInfo->getFrameRegister(MF);
420     // An example of the prologue:
421     //
422     //     .globl __foo
423     //     .align 2
424     //  __foo:
425     // Ltmp0:
426     //     .cfi_startproc
427     //     .cfi_personality 155, ___gxx_personality_v0
428     // Leh_func_begin:
429     //     .cfi_lsda 16, Lexception33
430     //
431     //     stp  xa,bx, [sp, -#offset]!
432     //     ...
433     //     stp  x28, x27, [sp, #offset-32]
434     //     stp  fp, lr, [sp, #offset-16]
435     //     add  fp, sp, #offset - 16
436     //     sub  sp, sp, #1360
437     //
438     // The Stack:
439     //       +-------------------------------------------+
440     // 10000 | ........ | ........ | ........ | ........ |
441     // 10004 | ........ | ........ | ........ | ........ |
442     //       +-------------------------------------------+
443     // 10008 | ........ | ........ | ........ | ........ |
444     // 1000c | ........ | ........ | ........ | ........ |
445     //       +===========================================+
446     // 10010 |                X28 Register               |
447     // 10014 |                X28 Register               |
448     //       +-------------------------------------------+
449     // 10018 |                X27 Register               |
450     // 1001c |                X27 Register               |
451     //       +===========================================+
452     // 10020 |                Frame Pointer              |
453     // 10024 |                Frame Pointer              |
454     //       +-------------------------------------------+
455     // 10028 |                Link Register              |
456     // 1002c |                Link Register              |
457     //       +===========================================+
458     // 10030 | ........ | ........ | ........ | ........ |
459     // 10034 | ........ | ........ | ........ | ........ |
460     //       +-------------------------------------------+
461     // 10038 | ........ | ........ | ........ | ........ |
462     // 1003c | ........ | ........ | ........ | ........ |
463     //       +-------------------------------------------+
464     //
465     //     [sp] = 10030        ::    >>initial value<<
466     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
467     //     fp = sp == 10020    ::  mov fp, sp
468     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
469     //     sp == 10010         ::    >>final value<<
470     //
471     // The frame pointer (w29) points to address 10020. If we use an offset of
472     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
473     // for w27, and -32 for w28:
474     //
475     //  Ltmp1:
476     //     .cfi_def_cfa w29, 16
477     //  Ltmp2:
478     //     .cfi_offset w30, -8
479     //  Ltmp3:
480     //     .cfi_offset w29, -16
481     //  Ltmp4:
482     //     .cfi_offset w27, -24
483     //  Ltmp5:
484     //     .cfi_offset w28, -32
485
486     if (HasFP) {
487       // Define the current CFA rule to use the provided FP.
488       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
489       unsigned CFIIndex = MMI.addFrameInst(
490           MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
491       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
492           .addCFIIndex(CFIIndex)
493           .setMIFlags(MachineInstr::FrameSetup);
494
495       // Record the location of the stored LR
496       unsigned LR = RegInfo->getDwarfRegNum(AArch64::LR, true);
497       CFIIndex = MMI.addFrameInst(
498           MCCFIInstruction::createOffset(nullptr, LR, StackGrowth));
499       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
500           .addCFIIndex(CFIIndex)
501           .setMIFlags(MachineInstr::FrameSetup);
502
503       // Record the location of the stored FP
504       CFIIndex = MMI.addFrameInst(
505           MCCFIInstruction::createOffset(nullptr, Reg, 2 * StackGrowth));
506       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
507           .addCFIIndex(CFIIndex)
508           .setMIFlags(MachineInstr::FrameSetup);
509     } else {
510       // Encode the stack size of the leaf function.
511       unsigned CFIIndex = MMI.addFrameInst(
512           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
513       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
514           .addCFIIndex(CFIIndex)
515           .setMIFlags(MachineInstr::FrameSetup);
516     }
517
518     // Now emit the moves for whatever callee saved regs we have.
519     emitCalleeSavedFrameMoves(MBB, MBBI, FramePtr);
520   }
521 }
522
523 static bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) {
524   for (unsigned i = 0; CSRegs[i]; ++i)
525     if (Reg == CSRegs[i])
526       return true;
527   return false;
528 }
529
530 /// Checks whether the given instruction restores callee save registers
531 /// and if so returns how many.
532 static unsigned getNumCSRestores(MachineInstr &MI, const MCPhysReg *CSRegs) {
533   unsigned RtIdx = 0;
534   switch (MI.getOpcode()) {
535   case AArch64::LDPXpost:
536   case AArch64::LDPDpost:
537     RtIdx = 1;
538     // FALLTHROUGH
539   case AArch64::LDPXi:
540   case AArch64::LDPDi:
541     if (!isCalleeSavedRegister(MI.getOperand(RtIdx).getReg(), CSRegs) ||
542         !isCalleeSavedRegister(MI.getOperand(RtIdx + 1).getReg(), CSRegs) ||
543         MI.getOperand(RtIdx + 2).getReg() != AArch64::SP)
544       return 0;
545     return 2;
546   }
547   return 0;
548 }
549
550 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
551                                         MachineBasicBlock &MBB) const {
552   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
553   MachineFrameInfo *MFI = MF.getFrameInfo();
554   const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
555   const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
556   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
557   DebugLoc DL;
558   bool IsTailCallReturn = false;
559   if (MBB.end() != MBBI) {
560     DL = MBBI->getDebugLoc();
561     unsigned RetOpcode = MBBI->getOpcode();
562     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
563       RetOpcode == AArch64::TCRETURNri;
564   }
565   int NumBytes = MFI->getStackSize();
566   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
567
568   // All calls are tail calls in GHC calling conv, and functions have no
569   // prologue/epilogue.
570   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
571     return;
572
573   // Initial and residual are named for consistency with the prologue. Note that
574   // in the epilogue, the residual adjustment is executed first.
575   uint64_t ArgumentPopSize = 0;
576   if (IsTailCallReturn) {
577     MachineOperand &StackAdjust = MBBI->getOperand(1);
578
579     // For a tail-call in a callee-pops-arguments environment, some or all of
580     // the stack may actually be in use for the call's arguments, this is
581     // calculated during LowerCall and consumed here...
582     ArgumentPopSize = StackAdjust.getImm();
583   } else {
584     // ... otherwise the amount to pop is *all* of the argument space,
585     // conveniently stored in the MachineFunctionInfo by
586     // LowerFormalArguments. This will, of course, be zero for the C calling
587     // convention.
588     ArgumentPopSize = AFI->getArgumentStackToRestore();
589   }
590
591   // The stack frame should be like below,
592   //
593   //      ----------------------                     ---
594   //      |                    |                      |
595   //      | BytesInStackArgArea|              CalleeArgStackSize
596   //      | (NumReusableBytes) |                (of tail call)
597   //      |                    |                     ---
598   //      |                    |                      |
599   //      ---------------------|        ---           |
600   //      |                    |         |            |
601   //      |   CalleeSavedReg   |         |            |
602   //      | (NumRestores * 8)  |         |            |
603   //      |                    |         |            |
604   //      ---------------------|         |         NumBytes
605   //      |                    |     StackSize  (StackAdjustUp)
606   //      |   LocalStackSize   |         |            |
607   //      | (covering callee   |         |            |
608   //      |       args)        |         |            |
609   //      |                    |         |            |
610   //      ----------------------        ---          ---
611   //
612   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
613   //             = StackSize + ArgumentPopSize
614   //
615   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
616   // it as the 2nd argument of AArch64ISD::TC_RETURN.
617   NumBytes += ArgumentPopSize;
618
619   unsigned NumRestores = 0;
620   // Move past the restores of the callee-saved registers.
621   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
622   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
623   MachineBasicBlock::iterator Begin = MBB.begin();
624   while (LastPopI != Begin) {
625     --LastPopI;
626     unsigned Restores = getNumCSRestores(*LastPopI, CSRegs);
627     NumRestores += Restores;
628     if (Restores == 0) {
629       ++LastPopI;
630       break;
631     }
632   }
633   NumBytes -= NumRestores * 8;
634   assert(NumBytes >= 0 && "Negative stack allocation size!?");
635
636   if (!hasFP(MF)) {
637     // If this was a redzone leaf function, we don't need to restore the
638     // stack pointer.
639     if (!canUseRedZone(MF))
640       emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes,
641                       TII);
642     return;
643   }
644
645   // Restore the original stack pointer.
646   // FIXME: Rather than doing the math here, we should instead just use
647   // non-post-indexed loads for the restores if we aren't actually going to
648   // be able to save any instructions.
649   if (NumBytes || MFI->hasVarSizedObjects())
650     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
651                     -(NumRestores - 2) * 8, TII, MachineInstr::NoFlags);
652 }
653
654 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
655 /// debug info.  It's the same as what we use for resolving the code-gen
656 /// references for now.  FIXME: This can go wrong when references are
657 /// SP-relative and simple call frames aren't used.
658 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
659                                                  int FI,
660                                                  unsigned &FrameReg) const {
661   return resolveFrameIndexReference(MF, FI, FrameReg);
662 }
663
664 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
665                                                      int FI, unsigned &FrameReg,
666                                                      bool PreferFP) const {
667   const MachineFrameInfo *MFI = MF.getFrameInfo();
668   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
669       MF.getSubtarget().getRegisterInfo());
670   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
671   int FPOffset = MFI->getObjectOffset(FI) + 16;
672   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
673   bool isFixed = MFI->isFixedObjectIndex(FI);
674
675   // Use frame pointer to reference fixed objects. Use it for locals if
676   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
677   // reliable as a base). Make sure useFPForScavengingIndex() does the
678   // right thing for the emergency spill slot.
679   bool UseFP = false;
680   if (AFI->hasStackFrame()) {
681     // Note: Keeping the following as multiple 'if' statements rather than
682     // merging to a single expression for readability.
683     //
684     // Argument access should always use the FP.
685     if (isFixed) {
686       UseFP = hasFP(MF);
687     } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
688                !RegInfo->needsStackRealignment(MF)) {
689       // Use SP or FP, whichever gives us the best chance of the offset
690       // being in range for direct access. If the FPOffset is positive,
691       // that'll always be best, as the SP will be even further away.
692       // If the FPOffset is negative, we have to keep in mind that the
693       // available offset range for negative offsets is smaller than for
694       // positive ones. If we have variable sized objects, we're stuck with
695       // using the FP regardless, though, as the SP offset is unknown
696       // and we don't have a base pointer available. If an offset is
697       // available via the FP and the SP, use whichever is closest.
698       if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
699           (FPOffset >= -256 && Offset > -FPOffset))
700         UseFP = true;
701     }
702   }
703
704   assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
705          "In the presence of dynamic stack pointer realignment, "
706          "non-argument objects cannot be accessed through the frame pointer");
707
708   if (UseFP) {
709     FrameReg = RegInfo->getFrameRegister(MF);
710     return FPOffset;
711   }
712
713   // Use the base pointer if we have one.
714   if (RegInfo->hasBasePointer(MF))
715     FrameReg = RegInfo->getBaseRegister();
716   else {
717     FrameReg = AArch64::SP;
718     // If we're using the red zone for this function, the SP won't actually
719     // be adjusted, so the offsets will be negative. They're also all
720     // within range of the signed 9-bit immediate instructions.
721     if (canUseRedZone(MF))
722       Offset -= AFI->getLocalStackSize();
723   }
724
725   return Offset;
726 }
727
728 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
729   if (Reg != AArch64::LR)
730     return getKillRegState(true);
731
732   // LR maybe referred to later by an @llvm.returnaddress intrinsic.
733   bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR);
734   bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
735   return getKillRegState(LRKill);
736 }
737
738 bool AArch64FrameLowering::spillCalleeSavedRegisters(
739     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
740     const std::vector<CalleeSavedInfo> &CSI,
741     const TargetRegisterInfo *TRI) const {
742   MachineFunction &MF = *MBB.getParent();
743   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
744   unsigned Count = CSI.size();
745   DebugLoc DL;
746   assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
747
748   for (unsigned i = 0; i < Count; i += 2) {
749     unsigned idx = Count - i - 2;
750     unsigned Reg1 = CSI[idx].getReg();
751     unsigned Reg2 = CSI[idx + 1].getReg();
752     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
753     // list to come in sorted by frame index so that we can issue the store
754     // pair instructions directly. Assert if we see anything otherwise.
755     //
756     // The order of the registers in the list is controlled by
757     // getCalleeSavedRegs(), so they will always be in-order, as well.
758     assert(CSI[idx].getFrameIdx() + 1 == CSI[idx + 1].getFrameIdx() &&
759            "Out of order callee saved regs!");
760     unsigned StrOpc;
761     assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
762     assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
763     // Issue sequence of non-sp increment and pi sp spills for cs regs. The
764     // first spill is a pre-increment that allocates the stack.
765     // For example:
766     //    stp     x22, x21, [sp, #-48]!   // addImm(-6)
767     //    stp     x20, x19, [sp, #16]    // addImm(+2)
768     //    stp     fp, lr, [sp, #32]      // addImm(+4)
769     // Rationale: This sequence saves uop updates compared to a sequence of
770     // pre-increment spills like stp xi,xj,[sp,#-16]!
771     // Note: Similar rational and sequence for restores in epilog.
772     if (AArch64::GPR64RegClass.contains(Reg1)) {
773       assert(AArch64::GPR64RegClass.contains(Reg2) &&
774              "Expected GPR64 callee-saved register pair!");
775       // For first spill use pre-increment store.
776       if (i == 0)
777         StrOpc = AArch64::STPXpre;
778       else
779         StrOpc = AArch64::STPXi;
780     } else if (AArch64::FPR64RegClass.contains(Reg1)) {
781       assert(AArch64::FPR64RegClass.contains(Reg2) &&
782              "Expected FPR64 callee-saved register pair!");
783       // For first spill use pre-increment store.
784       if (i == 0)
785         StrOpc = AArch64::STPDpre;
786       else
787         StrOpc = AArch64::STPDi;
788     } else
789       llvm_unreachable("Unexpected callee saved register!");
790     DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1) << ", "
791                  << TRI->getName(Reg2) << ") -> fi#(" << CSI[idx].getFrameIdx()
792                  << ", " << CSI[idx + 1].getFrameIdx() << ")\n");
793     // Compute offset: i = 0 => offset = -Count;
794     //                 i = 2 => offset = -(Count - 2) + Count = 2 = i; etc.
795     const int Offset = (i == 0) ? -Count : i;
796     assert((Offset >= -64 && Offset <= 63) &&
797            "Offset out of bounds for STP immediate");
798     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
799     if (StrOpc == AArch64::STPDpre || StrOpc == AArch64::STPXpre)
800       MIB.addReg(AArch64::SP, RegState::Define);
801
802     MBB.addLiveIn(Reg1);
803     MBB.addLiveIn(Reg2);
804     MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
805         .addReg(Reg1, getPrologueDeath(MF, Reg1))
806         .addReg(AArch64::SP)
807         .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
808         .setMIFlag(MachineInstr::FrameSetup);
809   }
810   return true;
811 }
812
813 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
814     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
815     const std::vector<CalleeSavedInfo> &CSI,
816     const TargetRegisterInfo *TRI) const {
817   MachineFunction &MF = *MBB.getParent();
818   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
819   unsigned Count = CSI.size();
820   DebugLoc DL;
821   assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
822
823   if (MI != MBB.end())
824     DL = MI->getDebugLoc();
825
826   for (unsigned i = 0; i < Count; i += 2) {
827     unsigned Reg1 = CSI[i].getReg();
828     unsigned Reg2 = CSI[i + 1].getReg();
829     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
830     // list to come in sorted by frame index so that we can issue the store
831     // pair instructions directly. Assert if we see anything otherwise.
832     assert(CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx() &&
833            "Out of order callee saved regs!");
834     // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
835     // the last load is sp-pi post-increment and de-allocates the stack:
836     // For example:
837     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
838     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
839     //    ldp     x22, x21, [sp], #48     // addImm(+6)
840     // Note: see comment in spillCalleeSavedRegisters()
841     unsigned LdrOpc;
842
843     assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
844     assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
845     if (AArch64::GPR64RegClass.contains(Reg1)) {
846       assert(AArch64::GPR64RegClass.contains(Reg2) &&
847              "Expected GPR64 callee-saved register pair!");
848       if (i == Count - 2)
849         LdrOpc = AArch64::LDPXpost;
850       else
851         LdrOpc = AArch64::LDPXi;
852     } else if (AArch64::FPR64RegClass.contains(Reg1)) {
853       assert(AArch64::FPR64RegClass.contains(Reg2) &&
854              "Expected FPR64 callee-saved register pair!");
855       if (i == Count - 2)
856         LdrOpc = AArch64::LDPDpost;
857       else
858         LdrOpc = AArch64::LDPDi;
859     } else
860       llvm_unreachable("Unexpected callee saved register!");
861     DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1) << ", "
862                  << TRI->getName(Reg2) << ") -> fi#(" << CSI[i].getFrameIdx()
863                  << ", " << CSI[i + 1].getFrameIdx() << ")\n");
864
865     // Compute offset: i = 0 => offset = Count - 2; i = 2 => offset = Count - 4;
866     // etc.
867     const int Offset = (i == Count - 2) ? Count : Count - i - 2;
868     assert((Offset >= -64 && Offset <= 63) &&
869            "Offset out of bounds for LDP immediate");
870     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
871     if (LdrOpc == AArch64::LDPXpost || LdrOpc == AArch64::LDPDpost)
872       MIB.addReg(AArch64::SP, RegState::Define);
873
874     MIB.addReg(Reg2, getDefRegState(true))
875         .addReg(Reg1, getDefRegState(true))
876         .addReg(AArch64::SP)
877         .addImm(Offset); // [sp], #offset * 8  or [sp, #offset * 8]
878                          // where the factor * 8 is implicit
879   }
880   return true;
881 }
882
883 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
884                                                 BitVector &SavedRegs,
885                                                 RegScavenger *RS) const {
886   // All calls are tail calls in GHC calling conv, and functions have no
887   // prologue/epilogue.
888   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
889     return;
890
891   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
892   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
893       MF.getSubtarget().getRegisterInfo());
894   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
895   SmallVector<unsigned, 4> UnspilledCSGPRs;
896   SmallVector<unsigned, 4> UnspilledCSFPRs;
897
898   // The frame record needs to be created by saving the appropriate registers
899   if (hasFP(MF)) {
900     SavedRegs.set(AArch64::FP);
901     SavedRegs.set(AArch64::LR);
902   }
903
904   // Spill the BasePtr if it's used. Do this first thing so that the
905   // getCalleeSavedRegs() below will get the right answer.
906   if (RegInfo->hasBasePointer(MF))
907     SavedRegs.set(RegInfo->getBaseRegister());
908
909   if (RegInfo->needsStackRealignment(MF) && !RegInfo->hasBasePointer(MF))
910     SavedRegs.set(AArch64::X9);
911
912   // If any callee-saved registers are used, the frame cannot be eliminated.
913   unsigned NumGPRSpilled = 0;
914   unsigned NumFPRSpilled = 0;
915   bool ExtraCSSpill = false;
916   bool CanEliminateFrame = true;
917   DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:");
918   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
919
920   // Check pairs of consecutive callee-saved registers.
921   for (unsigned i = 0; CSRegs[i]; i += 2) {
922     assert(CSRegs[i + 1] && "Odd number of callee-saved registers!");
923
924     const unsigned OddReg = CSRegs[i];
925     const unsigned EvenReg = CSRegs[i + 1];
926     assert((AArch64::GPR64RegClass.contains(OddReg) &&
927             AArch64::GPR64RegClass.contains(EvenReg)) ^
928                (AArch64::FPR64RegClass.contains(OddReg) &&
929                 AArch64::FPR64RegClass.contains(EvenReg)) &&
930            "Register class mismatch!");
931
932     const bool OddRegUsed = SavedRegs.test(OddReg);
933     const bool EvenRegUsed = SavedRegs.test(EvenReg);
934
935     // Early exit if none of the registers in the register pair is actually
936     // used.
937     if (!OddRegUsed && !EvenRegUsed) {
938       if (AArch64::GPR64RegClass.contains(OddReg)) {
939         UnspilledCSGPRs.push_back(OddReg);
940         UnspilledCSGPRs.push_back(EvenReg);
941       } else {
942         UnspilledCSFPRs.push_back(OddReg);
943         UnspilledCSFPRs.push_back(EvenReg);
944       }
945       continue;
946     }
947
948     unsigned Reg = AArch64::NoRegister;
949     // If only one of the registers of the register pair is used, make sure to
950     // mark the other one as used as well.
951     if (OddRegUsed ^ EvenRegUsed) {
952       // Find out which register is the additional spill.
953       Reg = OddRegUsed ? EvenReg : OddReg;
954       SavedRegs.set(Reg);
955     }
956
957     DEBUG(dbgs() << ' ' << PrintReg(OddReg, RegInfo));
958     DEBUG(dbgs() << ' ' << PrintReg(EvenReg, RegInfo));
959
960     assert(((OddReg == AArch64::LR && EvenReg == AArch64::FP) ||
961             (RegInfo->getEncodingValue(OddReg) + 1 ==
962              RegInfo->getEncodingValue(EvenReg))) &&
963            "Register pair of non-adjacent registers!");
964     if (AArch64::GPR64RegClass.contains(OddReg)) {
965       NumGPRSpilled += 2;
966       // If it's not a reserved register, we can use it in lieu of an
967       // emergency spill slot for the register scavenger.
968       // FIXME: It would be better to instead keep looking and choose another
969       // unspilled register that isn't reserved, if there is one.
970       if (Reg != AArch64::NoRegister && !RegInfo->isReservedReg(MF, Reg))
971         ExtraCSSpill = true;
972     } else
973       NumFPRSpilled += 2;
974
975     CanEliminateFrame = false;
976   }
977
978   // FIXME: Set BigStack if any stack slot references may be out of range.
979   // For now, just conservatively guestimate based on unscaled indexing
980   // range. We'll end up allocating an unnecessary spill slot a lot, but
981   // realistically that's not a big deal at this stage of the game.
982   // The CSR spill slots have not been allocated yet, so estimateStackSize
983   // won't include them.
984   MachineFrameInfo *MFI = MF.getFrameInfo();
985   unsigned CFSize =
986       MFI->estimateStackSize(MF) + 8 * (NumGPRSpilled + NumFPRSpilled);
987   DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
988   bool BigStack = (CFSize >= 256);
989   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
990     AFI->setHasStackFrame(true);
991
992   // Estimate if we might need to scavenge a register at some point in order
993   // to materialize a stack offset. If so, either spill one additional
994   // callee-saved register or reserve a special spill slot to facilitate
995   // register scavenging. If we already spilled an extra callee-saved register
996   // above to keep the number of spills even, we don't need to do anything else
997   // here.
998   if (BigStack && !ExtraCSSpill) {
999
1000     // If we're adding a register to spill here, we have to add two of them
1001     // to keep the number of regs to spill even.
1002     assert(((UnspilledCSGPRs.size() & 1) == 0) && "Odd number of registers!");
1003     unsigned Count = 0;
1004     while (!UnspilledCSGPRs.empty() && Count < 2) {
1005       unsigned Reg = UnspilledCSGPRs.back();
1006       UnspilledCSGPRs.pop_back();
1007       DEBUG(dbgs() << "Spilling " << PrintReg(Reg, RegInfo)
1008                    << " to get a scratch register.\n");
1009       SavedRegs.set(Reg);
1010       ExtraCSSpill = true;
1011       ++Count;
1012     }
1013
1014     // If we didn't find an extra callee-saved register to spill, create
1015     // an emergency spill slot.
1016     if (!ExtraCSSpill) {
1017       const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
1018       int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
1019       RS->addScavengingFrameIndex(FI);
1020       DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1021                    << " as the emergency spill slot.\n");
1022     }
1023   }
1024 }