Move most user of TargetMachine::getDataLayout to the Module one
[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 definitly needed when there are both VLAs and local
76 //   variables with more-than-default alignment requirements.
77 // * A frame pointer is definitly 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 void AArch64FrameLowering::emitPrologue(MachineFunction &MF,
279                                         MachineBasicBlock &MBB) const {
280   MachineBasicBlock::iterator MBBI = MBB.begin();
281   const MachineFrameInfo *MFI = MF.getFrameInfo();
282   const Function *Fn = MF.getFunction();
283   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
284       MF.getSubtarget().getRegisterInfo());
285   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
286   MachineModuleInfo &MMI = MF.getMMI();
287   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
288   bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry();
289   bool HasFP = hasFP(MF);
290   DebugLoc DL = MBB.findDebugLoc(MBBI);
291
292   // All calls are tail calls in GHC calling conv, and functions have no
293   // prologue/epilogue.
294   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
295     return;
296
297   int NumBytes = (int)MFI->getStackSize();
298   if (!AFI->hasStackFrame()) {
299     assert(!HasFP && "unexpected function without stack frame but with FP");
300
301     // All of the stack allocation is for locals.
302     AFI->setLocalStackSize(NumBytes);
303
304     // Label used to tie together the PROLOG_LABEL and the MachineMoves.
305     MCSymbol *FrameLabel = MMI.getContext().createTempSymbol();
306
307     // REDZONE: If the stack size is less than 128 bytes, we don't need
308     // to actually allocate.
309     if (NumBytes && !canUseRedZone(MF)) {
310       emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII,
311                       MachineInstr::FrameSetup);
312
313       // Encode the stack size of the leaf function.
314       unsigned CFIIndex = MMI.addFrameInst(
315           MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes));
316       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
317           .addCFIIndex(CFIIndex)
318           .setMIFlags(MachineInstr::FrameSetup);
319     } else if (NumBytes) {
320       ++NumRedZoneFunctions;
321     }
322
323     return;
324   }
325
326   // Only set up FP if we actually need to.
327   int FPOffset = 0;
328   if (HasFP)
329     FPOffset = getFPOffsetInPrologue(MBBI);
330
331   // Move past the saves of the callee-saved registers.
332   while (isCSSave(MBBI)) {
333     ++MBBI;
334     NumBytes -= 16;
335   }
336   assert(NumBytes >= 0 && "Negative stack allocation size!?");
337   if (HasFP) {
338     // Issue    sub fp, sp, FPOffset or
339     //          mov fp,sp          when FPOffset is zero.
340     // Note: All stores of callee-saved registers are marked as "FrameSetup".
341     // This code marks the instruction(s) that set the FP also.
342     emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII,
343                     MachineInstr::FrameSetup);
344   }
345
346   // All of the remaining stack allocations are for locals.
347   AFI->setLocalStackSize(NumBytes);
348
349   // Allocate space for the rest of the frame.
350
351   const unsigned Alignment = MFI->getMaxAlignment();
352   const bool NeedsRealignment = RegInfo->needsStackRealignment(MF);
353   unsigned scratchSPReg = AArch64::SP;
354   if (NumBytes && NeedsRealignment) {
355     // Use the first callee-saved register as a scratch register.
356     scratchSPReg = AArch64::X9;
357   }
358
359   // If we're a leaf function, try using the red zone.
360   if (NumBytes && !canUseRedZone(MF))
361     // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have
362     // the correct value here, as NumBytes also includes padding bytes,
363     // which shouldn't be counted here.
364     emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII,
365                     MachineInstr::FrameSetup);
366
367   if (NumBytes && NeedsRealignment) {
368     const unsigned NrBitsToZero = countTrailingZeros(Alignment);
369     assert(NrBitsToZero > 1);
370     assert(scratchSPReg != AArch64::SP);
371
372     // SUB X9, SP, NumBytes
373     //   -- X9 is temporary register, so shouldn't contain any live data here,
374     //   -- free to use. This is already produced by emitFrameOffset above.
375     // AND SP, X9, 0b11111...0000
376     // The logical immediates have a non-trivial encoding. The following
377     // formula computes the encoded immediate with all ones but
378     // NrBitsToZero zero bits as least significant bits.
379     uint32_t andMaskEncoded =
380         (1                   <<12) // = N
381       | ((64-NrBitsToZero)   << 6) // immr
382       | ((64-NrBitsToZero-1) << 0) // imms
383       ;
384     BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP)
385       .addReg(scratchSPReg, RegState::Kill)
386       .addImm(andMaskEncoded);
387   }
388
389   // If we need a base pointer, set it up here. It's whatever the value of the
390   // stack pointer is at this point. Any variable size objects will be allocated
391   // after this, so we can still use the base pointer to reference locals.
392   //
393   // FIXME: Clarify FrameSetup flags here.
394   // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is
395   // needed.
396   if (RegInfo->hasBasePointer(MF)) {
397     TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP,
398                      false);
399   }
400
401   if (needsFrameMoves) {
402     const DataLayout &TD = MF.getDataLayout();
403     const int StackGrowth = -TD.getPointerSize(0);
404     unsigned FramePtr = RegInfo->getFrameRegister(MF);
405     // An example of the prologue:
406     //
407     //     .globl __foo
408     //     .align 2
409     //  __foo:
410     // Ltmp0:
411     //     .cfi_startproc
412     //     .cfi_personality 155, ___gxx_personality_v0
413     // Leh_func_begin:
414     //     .cfi_lsda 16, Lexception33
415     //
416     //     stp  xa,bx, [sp, -#offset]!
417     //     ...
418     //     stp  x28, x27, [sp, #offset-32]
419     //     stp  fp, lr, [sp, #offset-16]
420     //     add  fp, sp, #offset - 16
421     //     sub  sp, sp, #1360
422     //
423     // The Stack:
424     //       +-------------------------------------------+
425     // 10000 | ........ | ........ | ........ | ........ |
426     // 10004 | ........ | ........ | ........ | ........ |
427     //       +-------------------------------------------+
428     // 10008 | ........ | ........ | ........ | ........ |
429     // 1000c | ........ | ........ | ........ | ........ |
430     //       +===========================================+
431     // 10010 |                X28 Register               |
432     // 10014 |                X28 Register               |
433     //       +-------------------------------------------+
434     // 10018 |                X27 Register               |
435     // 1001c |                X27 Register               |
436     //       +===========================================+
437     // 10020 |                Frame Pointer              |
438     // 10024 |                Frame Pointer              |
439     //       +-------------------------------------------+
440     // 10028 |                Link Register              |
441     // 1002c |                Link Register              |
442     //       +===========================================+
443     // 10030 | ........ | ........ | ........ | ........ |
444     // 10034 | ........ | ........ | ........ | ........ |
445     //       +-------------------------------------------+
446     // 10038 | ........ | ........ | ........ | ........ |
447     // 1003c | ........ | ........ | ........ | ........ |
448     //       +-------------------------------------------+
449     //
450     //     [sp] = 10030        ::    >>initial value<<
451     //     sp = 10020          ::  stp fp, lr, [sp, #-16]!
452     //     fp = sp == 10020    ::  mov fp, sp
453     //     [sp] == 10020       ::  stp x28, x27, [sp, #-16]!
454     //     sp == 10010         ::    >>final value<<
455     //
456     // The frame pointer (w29) points to address 10020. If we use an offset of
457     // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
458     // for w27, and -32 for w28:
459     //
460     //  Ltmp1:
461     //     .cfi_def_cfa w29, 16
462     //  Ltmp2:
463     //     .cfi_offset w30, -8
464     //  Ltmp3:
465     //     .cfi_offset w29, -16
466     //  Ltmp4:
467     //     .cfi_offset w27, -24
468     //  Ltmp5:
469     //     .cfi_offset w28, -32
470
471     if (HasFP) {
472       // Define the current CFA rule to use the provided FP.
473       unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true);
474       unsigned CFIIndex = MMI.addFrameInst(
475           MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth));
476       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
477           .addCFIIndex(CFIIndex)
478           .setMIFlags(MachineInstr::FrameSetup);
479
480       // Record the location of the stored LR
481       unsigned LR = RegInfo->getDwarfRegNum(AArch64::LR, true);
482       CFIIndex = MMI.addFrameInst(
483           MCCFIInstruction::createOffset(nullptr, LR, StackGrowth));
484       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
485           .addCFIIndex(CFIIndex)
486           .setMIFlags(MachineInstr::FrameSetup);
487
488       // Record the location of the stored FP
489       CFIIndex = MMI.addFrameInst(
490           MCCFIInstruction::createOffset(nullptr, Reg, 2 * StackGrowth));
491       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
492           .addCFIIndex(CFIIndex)
493           .setMIFlags(MachineInstr::FrameSetup);
494     } else {
495       // Encode the stack size of the leaf function.
496       unsigned CFIIndex = MMI.addFrameInst(
497           MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize()));
498       BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
499           .addCFIIndex(CFIIndex)
500           .setMIFlags(MachineInstr::FrameSetup);
501     }
502
503     // Now emit the moves for whatever callee saved regs we have.
504     emitCalleeSavedFrameMoves(MBB, MBBI, FramePtr);
505   }
506 }
507
508 static bool isCalleeSavedRegister(unsigned Reg, const MCPhysReg *CSRegs) {
509   for (unsigned i = 0; CSRegs[i]; ++i)
510     if (Reg == CSRegs[i])
511       return true;
512   return false;
513 }
514
515 static bool isCSRestore(MachineInstr *MI, const MCPhysReg *CSRegs) {
516   unsigned RtIdx = 0;
517   if (MI->getOpcode() == AArch64::LDPXpost ||
518       MI->getOpcode() == AArch64::LDPDpost)
519     RtIdx = 1;
520
521   if (MI->getOpcode() == AArch64::LDPXpost ||
522       MI->getOpcode() == AArch64::LDPDpost ||
523       MI->getOpcode() == AArch64::LDPXi || MI->getOpcode() == AArch64::LDPDi) {
524     if (!isCalleeSavedRegister(MI->getOperand(RtIdx).getReg(), CSRegs) ||
525         !isCalleeSavedRegister(MI->getOperand(RtIdx + 1).getReg(), CSRegs) ||
526         MI->getOperand(RtIdx + 2).getReg() != AArch64::SP)
527       return false;
528     return true;
529   }
530
531   return false;
532 }
533
534 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF,
535                                         MachineBasicBlock &MBB) const {
536   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
537   MachineFrameInfo *MFI = MF.getFrameInfo();
538   const AArch64InstrInfo *TII =
539       static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo());
540   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
541       MF.getSubtarget().getRegisterInfo());
542   DebugLoc DL;
543   bool IsTailCallReturn = false;
544   if (MBB.end() != MBBI) {
545     DL = MBBI->getDebugLoc();
546     unsigned RetOpcode = MBBI->getOpcode();
547     IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi ||
548       RetOpcode == AArch64::TCRETURNri;
549   }
550   int NumBytes = MFI->getStackSize();
551   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
552
553   // All calls are tail calls in GHC calling conv, and functions have no
554   // prologue/epilogue.
555   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
556     return;
557
558   // Initial and residual are named for consistency with the prologue. Note that
559   // in the epilogue, the residual adjustment is executed first.
560   uint64_t ArgumentPopSize = 0;
561   if (IsTailCallReturn) {
562     MachineOperand &StackAdjust = MBBI->getOperand(1);
563
564     // For a tail-call in a callee-pops-arguments environment, some or all of
565     // the stack may actually be in use for the call's arguments, this is
566     // calculated during LowerCall and consumed here...
567     ArgumentPopSize = StackAdjust.getImm();
568   } else {
569     // ... otherwise the amount to pop is *all* of the argument space,
570     // conveniently stored in the MachineFunctionInfo by
571     // LowerFormalArguments. This will, of course, be zero for the C calling
572     // convention.
573     ArgumentPopSize = AFI->getArgumentStackToRestore();
574   }
575
576   // The stack frame should be like below,
577   //
578   //      ----------------------                     ---
579   //      |                    |                      |
580   //      | BytesInStackArgArea|              CalleeArgStackSize
581   //      | (NumReusableBytes) |                (of tail call)
582   //      |                    |                     ---
583   //      |                    |                      |
584   //      ---------------------|        ---           |
585   //      |                    |         |            |
586   //      |   CalleeSavedReg   |         |            |
587   //      | (NumRestores * 16) |         |            |
588   //      |                    |         |            |
589   //      ---------------------|         |         NumBytes
590   //      |                    |     StackSize  (StackAdjustUp)
591   //      |   LocalStackSize   |         |            |
592   //      | (covering callee   |         |            |
593   //      |       args)        |         |            |
594   //      |                    |         |            |
595   //      ----------------------        ---          ---
596   //
597   // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize
598   //             = StackSize + ArgumentPopSize
599   //
600   // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps
601   // it as the 2nd argument of AArch64ISD::TC_RETURN.
602   NumBytes += ArgumentPopSize;
603
604   unsigned NumRestores = 0;
605   // Move past the restores of the callee-saved registers.
606   MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator();
607   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
608   if (LastPopI != MBB.begin()) {
609     do {
610       ++NumRestores;
611       --LastPopI;
612     } while (LastPopI != MBB.begin() && isCSRestore(LastPopI, CSRegs));
613     if (!isCSRestore(LastPopI, CSRegs)) {
614       ++LastPopI;
615       --NumRestores;
616     }
617   }
618   NumBytes -= NumRestores * 16;
619   assert(NumBytes >= 0 && "Negative stack allocation size!?");
620
621   if (!hasFP(MF)) {
622     // If this was a redzone leaf function, we don't need to restore the
623     // stack pointer.
624     if (!canUseRedZone(MF))
625       emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes,
626                       TII);
627     return;
628   }
629
630   // Restore the original stack pointer.
631   // FIXME: Rather than doing the math here, we should instead just use
632   // non-post-indexed loads for the restores if we aren't actually going to
633   // be able to save any instructions.
634   if (NumBytes || MFI->hasVarSizedObjects())
635     emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP,
636                     -(NumRestores - 1) * 16, TII, MachineInstr::NoFlags);
637 }
638
639 /// getFrameIndexOffset - Returns the displacement from the frame register to
640 /// the stack frame of the specified index.
641 int AArch64FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
642                                               int FI) const {
643   unsigned FrameReg;
644   return getFrameIndexReference(MF, FI, FrameReg);
645 }
646
647 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
648 /// debug info.  It's the same as what we use for resolving the code-gen
649 /// references for now.  FIXME: This can go wrong when references are
650 /// SP-relative and simple call frames aren't used.
651 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF,
652                                                  int FI,
653                                                  unsigned &FrameReg) const {
654   return resolveFrameIndexReference(MF, FI, FrameReg);
655 }
656
657 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF,
658                                                      int FI, unsigned &FrameReg,
659                                                      bool PreferFP) const {
660   const MachineFrameInfo *MFI = MF.getFrameInfo();
661   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
662       MF.getSubtarget().getRegisterInfo());
663   const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
664   int FPOffset = MFI->getObjectOffset(FI) + 16;
665   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
666   bool isFixed = MFI->isFixedObjectIndex(FI);
667
668   // Use frame pointer to reference fixed objects. Use it for locals if
669   // there are VLAs or a dynamically realigned SP (and thus the SP isn't
670   // reliable as a base). Make sure useFPForScavengingIndex() does the
671   // right thing for the emergency spill slot.
672   bool UseFP = false;
673   if (AFI->hasStackFrame()) {
674     // Note: Keeping the following as multiple 'if' statements rather than
675     // merging to a single expression for readability.
676     //
677     // Argument access should always use the FP.
678     if (isFixed) {
679       UseFP = hasFP(MF);
680     } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) &&
681                !RegInfo->needsStackRealignment(MF)) {
682       // Use SP or FP, whichever gives us the best chance of the offset
683       // being in range for direct access. If the FPOffset is positive,
684       // that'll always be best, as the SP will be even further away.
685       // If the FPOffset is negative, we have to keep in mind that the
686       // available offset range for negative offsets is smaller than for
687       // positive ones. If we have variable sized objects, we're stuck with
688       // using the FP regardless, though, as the SP offset is unknown
689       // and we don't have a base pointer available. If an offset is
690       // available via the FP and the SP, use whichever is closest.
691       if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 ||
692           (FPOffset >= -256 && Offset > -FPOffset))
693         UseFP = true;
694     }
695   }
696
697   assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) &&
698          "In the presence of dynamic stack pointer realignment, "
699          "non-argument objects cannot be accessed through the frame pointer");
700
701   if (UseFP) {
702     FrameReg = RegInfo->getFrameRegister(MF);
703     return FPOffset;
704   }
705
706   // Use the base pointer if we have one.
707   if (RegInfo->hasBasePointer(MF))
708     FrameReg = RegInfo->getBaseRegister();
709   else {
710     FrameReg = AArch64::SP;
711     // If we're using the red zone for this function, the SP won't actually
712     // be adjusted, so the offsets will be negative. They're also all
713     // within range of the signed 9-bit immediate instructions.
714     if (canUseRedZone(MF))
715       Offset -= AFI->getLocalStackSize();
716   }
717
718   return Offset;
719 }
720
721 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) {
722   if (Reg != AArch64::LR)
723     return getKillRegState(true);
724
725   // LR maybe referred to later by an @llvm.returnaddress intrinsic.
726   bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR);
727   bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken());
728   return getKillRegState(LRKill);
729 }
730
731 bool AArch64FrameLowering::spillCalleeSavedRegisters(
732     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
733     const std::vector<CalleeSavedInfo> &CSI,
734     const TargetRegisterInfo *TRI) const {
735   MachineFunction &MF = *MBB.getParent();
736   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
737   unsigned Count = CSI.size();
738   DebugLoc DL;
739   assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
740
741   if (MI != MBB.end())
742     DL = MI->getDebugLoc();
743
744   for (unsigned i = 0; i < Count; i += 2) {
745     unsigned idx = Count - i - 2;
746     unsigned Reg1 = CSI[idx].getReg();
747     unsigned Reg2 = CSI[idx + 1].getReg();
748     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
749     // list to come in sorted by frame index so that we can issue the store
750     // pair instructions directly. Assert if we see anything otherwise.
751     //
752     // The order of the registers in the list is controlled by
753     // getCalleeSavedRegs(), so they will always be in-order, as well.
754     assert(CSI[idx].getFrameIdx() + 1 == CSI[idx + 1].getFrameIdx() &&
755            "Out of order callee saved regs!");
756     unsigned StrOpc;
757     assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
758     assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
759     // Issue sequence of non-sp increment and pi sp spills for cs regs. The
760     // first spill is a pre-increment that allocates the stack.
761     // For example:
762     //    stp     x22, x21, [sp, #-48]!   // addImm(-6)
763     //    stp     x20, x19, [sp, #16]    // addImm(+2)
764     //    stp     fp, lr, [sp, #32]      // addImm(+4)
765     // Rationale: This sequence saves uop updates compared to a sequence of
766     // pre-increment spills like stp xi,xj,[sp,#-16]!
767     // Note: Similar rational and sequence for restores in epilog.
768     if (AArch64::GPR64RegClass.contains(Reg1)) {
769       assert(AArch64::GPR64RegClass.contains(Reg2) &&
770              "Expected GPR64 callee-saved register pair!");
771       // For first spill use pre-increment store.
772       if (i == 0)
773         StrOpc = AArch64::STPXpre;
774       else
775         StrOpc = AArch64::STPXi;
776     } else if (AArch64::FPR64RegClass.contains(Reg1)) {
777       assert(AArch64::FPR64RegClass.contains(Reg2) &&
778              "Expected FPR64 callee-saved register pair!");
779       // For first spill use pre-increment store.
780       if (i == 0)
781         StrOpc = AArch64::STPDpre;
782       else
783         StrOpc = AArch64::STPDi;
784     } else
785       llvm_unreachable("Unexpected callee saved register!");
786     DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1) << ", "
787                  << TRI->getName(Reg2) << ") -> fi#(" << CSI[idx].getFrameIdx()
788                  << ", " << CSI[idx + 1].getFrameIdx() << ")\n");
789     // Compute offset: i = 0 => offset = -Count;
790     //                 i = 2 => offset = -(Count - 2) + Count = 2 = i; etc.
791     const int Offset = (i == 0) ? -Count : i;
792     assert((Offset >= -64 && Offset <= 63) &&
793            "Offset out of bounds for STP immediate");
794     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
795     if (StrOpc == AArch64::STPDpre || StrOpc == AArch64::STPXpre)
796       MIB.addReg(AArch64::SP, RegState::Define);
797
798     MBB.addLiveIn(Reg1);
799     MBB.addLiveIn(Reg2);
800     MIB.addReg(Reg2, getPrologueDeath(MF, Reg2))
801         .addReg(Reg1, getPrologueDeath(MF, Reg1))
802         .addReg(AArch64::SP)
803         .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit
804         .setMIFlag(MachineInstr::FrameSetup);
805   }
806   return true;
807 }
808
809 bool AArch64FrameLowering::restoreCalleeSavedRegisters(
810     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
811     const std::vector<CalleeSavedInfo> &CSI,
812     const TargetRegisterInfo *TRI) const {
813   MachineFunction &MF = *MBB.getParent();
814   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
815   unsigned Count = CSI.size();
816   DebugLoc DL;
817   assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
818
819   if (MI != MBB.end())
820     DL = MI->getDebugLoc();
821
822   for (unsigned i = 0; i < Count; i += 2) {
823     unsigned Reg1 = CSI[i].getReg();
824     unsigned Reg2 = CSI[i + 1].getReg();
825     // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
826     // list to come in sorted by frame index so that we can issue the store
827     // pair instructions directly. Assert if we see anything otherwise.
828     assert(CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx() &&
829            "Out of order callee saved regs!");
830     // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only
831     // the last load is sp-pi post-increment and de-allocates the stack:
832     // For example:
833     //    ldp     fp, lr, [sp, #32]       // addImm(+4)
834     //    ldp     x20, x19, [sp, #16]     // addImm(+2)
835     //    ldp     x22, x21, [sp], #48     // addImm(+6)
836     // Note: see comment in spillCalleeSavedRegisters()
837     unsigned LdrOpc;
838
839     assert((Count & 1) == 0 && "Odd number of callee-saved regs to spill!");
840     assert((i & 1) == 0 && "Odd index for callee-saved reg spill!");
841     if (AArch64::GPR64RegClass.contains(Reg1)) {
842       assert(AArch64::GPR64RegClass.contains(Reg2) &&
843              "Expected GPR64 callee-saved register pair!");
844       if (i == Count - 2)
845         LdrOpc = AArch64::LDPXpost;
846       else
847         LdrOpc = AArch64::LDPXi;
848     } else if (AArch64::FPR64RegClass.contains(Reg1)) {
849       assert(AArch64::FPR64RegClass.contains(Reg2) &&
850              "Expected FPR64 callee-saved register pair!");
851       if (i == Count - 2)
852         LdrOpc = AArch64::LDPDpost;
853       else
854         LdrOpc = AArch64::LDPDi;
855     } else
856       llvm_unreachable("Unexpected callee saved register!");
857     DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1) << ", "
858                  << TRI->getName(Reg2) << ") -> fi#(" << CSI[i].getFrameIdx()
859                  << ", " << CSI[i + 1].getFrameIdx() << ")\n");
860
861     // Compute offset: i = 0 => offset = Count - 2; i = 2 => offset = Count - 4;
862     // etc.
863     const int Offset = (i == Count - 2) ? Count : Count - i - 2;
864     assert((Offset >= -64 && Offset <= 63) &&
865            "Offset out of bounds for LDP immediate");
866     MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc));
867     if (LdrOpc == AArch64::LDPXpost || LdrOpc == AArch64::LDPDpost)
868       MIB.addReg(AArch64::SP, RegState::Define);
869
870     MIB.addReg(Reg2, getDefRegState(true))
871         .addReg(Reg1, getDefRegState(true))
872         .addReg(AArch64::SP)
873         .addImm(Offset); // [sp], #offset * 8  or [sp, #offset * 8]
874                          // where the factor * 8 is implicit
875   }
876   return true;
877 }
878
879 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF,
880                                                 BitVector &SavedRegs,
881                                                 RegScavenger *RS) const {
882   // All calls are tail calls in GHC calling conv, and functions have no
883   // prologue/epilogue.
884   if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
885     return;
886
887   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
888   const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>(
889       MF.getSubtarget().getRegisterInfo());
890   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
891   SmallVector<unsigned, 4> UnspilledCSGPRs;
892   SmallVector<unsigned, 4> UnspilledCSFPRs;
893
894   // The frame record needs to be created by saving the appropriate registers
895   if (hasFP(MF)) {
896     SavedRegs.set(AArch64::FP);
897     SavedRegs.set(AArch64::LR);
898   }
899
900   // Spill the BasePtr if it's used. Do this first thing so that the
901   // getCalleeSavedRegs() below will get the right answer.
902   if (RegInfo->hasBasePointer(MF))
903     SavedRegs.set(RegInfo->getBaseRegister());
904
905   if (RegInfo->needsStackRealignment(MF) && !RegInfo->hasBasePointer(MF))
906     SavedRegs.set(AArch64::X9);
907
908   // If any callee-saved registers are used, the frame cannot be eliminated.
909   unsigned NumGPRSpilled = 0;
910   unsigned NumFPRSpilled = 0;
911   bool ExtraCSSpill = false;
912   bool CanEliminateFrame = true;
913   DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:");
914   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
915
916   // Check pairs of consecutive callee-saved registers.
917   for (unsigned i = 0; CSRegs[i]; i += 2) {
918     assert(CSRegs[i + 1] && "Odd number of callee-saved registers!");
919
920     const unsigned OddReg = CSRegs[i];
921     const unsigned EvenReg = CSRegs[i + 1];
922     assert((AArch64::GPR64RegClass.contains(OddReg) &&
923             AArch64::GPR64RegClass.contains(EvenReg)) ^
924                (AArch64::FPR64RegClass.contains(OddReg) &&
925                 AArch64::FPR64RegClass.contains(EvenReg)) &&
926            "Register class mismatch!");
927
928     const bool OddRegUsed = SavedRegs.test(OddReg);
929     const bool EvenRegUsed = SavedRegs.test(EvenReg);
930
931     // Early exit if none of the registers in the register pair is actually
932     // used.
933     if (!OddRegUsed && !EvenRegUsed) {
934       if (AArch64::GPR64RegClass.contains(OddReg)) {
935         UnspilledCSGPRs.push_back(OddReg);
936         UnspilledCSGPRs.push_back(EvenReg);
937       } else {
938         UnspilledCSFPRs.push_back(OddReg);
939         UnspilledCSFPRs.push_back(EvenReg);
940       }
941       continue;
942     }
943
944     unsigned Reg = AArch64::NoRegister;
945     // If only one of the registers of the register pair is used, make sure to
946     // mark the other one as used as well.
947     if (OddRegUsed ^ EvenRegUsed) {
948       // Find out which register is the additional spill.
949       Reg = OddRegUsed ? EvenReg : OddReg;
950       SavedRegs.set(Reg);
951     }
952
953     DEBUG(dbgs() << ' ' << PrintReg(OddReg, RegInfo));
954     DEBUG(dbgs() << ' ' << PrintReg(EvenReg, RegInfo));
955
956     assert(((OddReg == AArch64::LR && EvenReg == AArch64::FP) ||
957             (RegInfo->getEncodingValue(OddReg) + 1 ==
958              RegInfo->getEncodingValue(EvenReg))) &&
959            "Register pair of non-adjacent registers!");
960     if (AArch64::GPR64RegClass.contains(OddReg)) {
961       NumGPRSpilled += 2;
962       // If it's not a reserved register, we can use it in lieu of an
963       // emergency spill slot for the register scavenger.
964       // FIXME: It would be better to instead keep looking and choose another
965       // unspilled register that isn't reserved, if there is one.
966       if (Reg != AArch64::NoRegister && !RegInfo->isReservedReg(MF, Reg))
967         ExtraCSSpill = true;
968     } else
969       NumFPRSpilled += 2;
970
971     CanEliminateFrame = false;
972   }
973
974   // FIXME: Set BigStack if any stack slot references may be out of range.
975   // For now, just conservatively guestimate based on unscaled indexing
976   // range. We'll end up allocating an unnecessary spill slot a lot, but
977   // realistically that's not a big deal at this stage of the game.
978   // The CSR spill slots have not been allocated yet, so estimateStackSize
979   // won't include them.
980   MachineFrameInfo *MFI = MF.getFrameInfo();
981   unsigned CFSize =
982       MFI->estimateStackSize(MF) + 8 * (NumGPRSpilled + NumFPRSpilled);
983   DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n");
984   bool BigStack = (CFSize >= 256);
985   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
986     AFI->setHasStackFrame(true);
987
988   // Estimate if we might need to scavenge a register at some point in order
989   // to materialize a stack offset. If so, either spill one additional
990   // callee-saved register or reserve a special spill slot to facilitate
991   // register scavenging. If we already spilled an extra callee-saved register
992   // above to keep the number of spills even, we don't need to do anything else
993   // here.
994   if (BigStack && !ExtraCSSpill) {
995
996     // If we're adding a register to spill here, we have to add two of them
997     // to keep the number of regs to spill even.
998     assert(((UnspilledCSGPRs.size() & 1) == 0) && "Odd number of registers!");
999     unsigned Count = 0;
1000     while (!UnspilledCSGPRs.empty() && Count < 2) {
1001       unsigned Reg = UnspilledCSGPRs.back();
1002       UnspilledCSGPRs.pop_back();
1003       DEBUG(dbgs() << "Spilling " << PrintReg(Reg, RegInfo)
1004                    << " to get a scratch register.\n");
1005       SavedRegs.set(Reg);
1006       ExtraCSSpill = true;
1007       ++Count;
1008     }
1009
1010     // If we didn't find an extra callee-saved register to spill, create
1011     // an emergency spill slot.
1012     if (!ExtraCSSpill) {
1013       const TargetRegisterClass *RC = &AArch64::GPR64RegClass;
1014       int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false);
1015       RS->addScavengingFrameIndex(FI);
1016       DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
1017                    << " as the emergency spill slot.\n");
1018     }
1019   }
1020 }