106f32e7eSjoerg //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file contains the ARM implementation of TargetFrameLowering class.
1006f32e7eSjoerg //
1106f32e7eSjoerg //===----------------------------------------------------------------------===//
12*da58b97aSjoerg //
13*da58b97aSjoerg // This file contains the ARM implementation of TargetFrameLowering class.
14*da58b97aSjoerg //
15*da58b97aSjoerg // On ARM, stack frames are structured as follows:
16*da58b97aSjoerg //
17*da58b97aSjoerg // The stack grows downward.
18*da58b97aSjoerg //
19*da58b97aSjoerg // All of the individual frame areas on the frame below are optional, i.e. it's
20*da58b97aSjoerg // possible to create a function so that the particular area isn't present
21*da58b97aSjoerg // in the frame.
22*da58b97aSjoerg //
23*da58b97aSjoerg // At function entry, the "frame" looks as follows:
24*da58b97aSjoerg //
25*da58b97aSjoerg // |                                   | Higher address
26*da58b97aSjoerg // |-----------------------------------|
27*da58b97aSjoerg // |                                   |
28*da58b97aSjoerg // | arguments passed on the stack     |
29*da58b97aSjoerg // |                                   |
30*da58b97aSjoerg // |-----------------------------------| <- sp
31*da58b97aSjoerg // |                                   | Lower address
32*da58b97aSjoerg //
33*da58b97aSjoerg //
34*da58b97aSjoerg // After the prologue has run, the frame has the following general structure.
35*da58b97aSjoerg // Technically the last frame area (VLAs) doesn't get created until in the
36*da58b97aSjoerg // main function body, after the prologue is run. However, it's depicted here
37*da58b97aSjoerg // for completeness.
38*da58b97aSjoerg //
39*da58b97aSjoerg // |                                   | Higher address
40*da58b97aSjoerg // |-----------------------------------|
41*da58b97aSjoerg // |                                   |
42*da58b97aSjoerg // | arguments passed on the stack     |
43*da58b97aSjoerg // |                                   |
44*da58b97aSjoerg // |-----------------------------------| <- (sp at function entry)
45*da58b97aSjoerg // |                                   |
46*da58b97aSjoerg // | varargs from registers            |
47*da58b97aSjoerg // |                                   |
48*da58b97aSjoerg // |-----------------------------------|
49*da58b97aSjoerg // |                                   |
50*da58b97aSjoerg // | prev_fp, prev_lr                  |
51*da58b97aSjoerg // | (a.k.a. "frame record")           |
52*da58b97aSjoerg // |                                   |
53*da58b97aSjoerg // |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11)
54*da58b97aSjoerg // |                                   |
55*da58b97aSjoerg // | callee-saved gpr registers        |
56*da58b97aSjoerg // |                                   |
57*da58b97aSjoerg // |-----------------------------------|
58*da58b97aSjoerg // |                                   |
59*da58b97aSjoerg // | callee-saved fp/simd regs         |
60*da58b97aSjoerg // |                                   |
61*da58b97aSjoerg // |-----------------------------------|
62*da58b97aSjoerg // |.empty.space.to.make.part.below....|
63*da58b97aSjoerg // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
64*da58b97aSjoerg // |.the.standard.8-byte.alignment.....|  compile time; if present)
65*da58b97aSjoerg // |-----------------------------------|
66*da58b97aSjoerg // |                                   |
67*da58b97aSjoerg // | local variables of fixed size     |
68*da58b97aSjoerg // | including spill slots             |
69*da58b97aSjoerg // |-----------------------------------| <- base pointer (not defined by ABI,
70*da58b97aSjoerg // |.variable-sized.local.variables....|       LLVM chooses r6)
71*da58b97aSjoerg // |.(VLAs)............................| (size of this area is unknown at
72*da58b97aSjoerg // |...................................|  compile time)
73*da58b97aSjoerg // |-----------------------------------| <- sp
74*da58b97aSjoerg // |                                   | Lower address
75*da58b97aSjoerg //
76*da58b97aSjoerg //
77*da58b97aSjoerg // To access the data in a frame, at-compile time, a constant offset must be
78*da58b97aSjoerg // computable from one of the pointers (fp, bp, sp) to access it. The size
79*da58b97aSjoerg // of the areas with a dotted background cannot be computed at compile-time
80*da58b97aSjoerg // if they are present, making it required to have all three of fp, bp and
81*da58b97aSjoerg // sp to be set up to be able to access all contents in the frame areas,
82*da58b97aSjoerg // assuming all of the frame areas are non-empty.
83*da58b97aSjoerg //
84*da58b97aSjoerg // For most functions, some of the frame areas are empty. For those functions,
85*da58b97aSjoerg // it may not be necessary to set up fp or bp:
86*da58b97aSjoerg // * A base pointer is definitely needed when there are both VLAs and local
87*da58b97aSjoerg //   variables with more-than-default alignment requirements.
88*da58b97aSjoerg // * A frame pointer is definitely needed when there are local variables with
89*da58b97aSjoerg //   more-than-default alignment requirements.
90*da58b97aSjoerg //
91*da58b97aSjoerg // In some cases when a base pointer is not strictly needed, it is generated
92*da58b97aSjoerg // anyway when offsets from the frame pointer to access local variables become
93*da58b97aSjoerg // so large that the offset can't be encoded in the immediate fields of loads
94*da58b97aSjoerg // or stores.
95*da58b97aSjoerg //
96*da58b97aSjoerg // The frame pointer might be chosen to be r7 or r11, depending on the target
97*da58b97aSjoerg // architecture and operating system. See ARMSubtarget::useR7AsFramePointer for
98*da58b97aSjoerg // details.
99*da58b97aSjoerg //
100*da58b97aSjoerg // Outgoing function arguments must be at the bottom of the stack frame when
101*da58b97aSjoerg // calling another function. If we do not have variable-sized stack objects, we
102*da58b97aSjoerg // can allocate a "reserved call frame" area at the bottom of the local
103*da58b97aSjoerg // variable area, large enough for all outgoing calls. If we do have VLAs, then
104*da58b97aSjoerg // the stack pointer must be decremented and incremented around each call to
105*da58b97aSjoerg // make space for the arguments below the VLAs.
106*da58b97aSjoerg //
107*da58b97aSjoerg //===----------------------------------------------------------------------===//
10806f32e7eSjoerg 
10906f32e7eSjoerg #include "ARMFrameLowering.h"
11006f32e7eSjoerg #include "ARMBaseInstrInfo.h"
11106f32e7eSjoerg #include "ARMBaseRegisterInfo.h"
11206f32e7eSjoerg #include "ARMConstantPoolValue.h"
11306f32e7eSjoerg #include "ARMMachineFunctionInfo.h"
11406f32e7eSjoerg #include "ARMSubtarget.h"
11506f32e7eSjoerg #include "MCTargetDesc/ARMAddressingModes.h"
11606f32e7eSjoerg #include "MCTargetDesc/ARMBaseInfo.h"
11706f32e7eSjoerg #include "Utils/ARMBaseInfo.h"
11806f32e7eSjoerg #include "llvm/ADT/BitVector.h"
11906f32e7eSjoerg #include "llvm/ADT/STLExtras.h"
12006f32e7eSjoerg #include "llvm/ADT/SmallPtrSet.h"
12106f32e7eSjoerg #include "llvm/ADT/SmallVector.h"
12206f32e7eSjoerg #include "llvm/CodeGen/MachineBasicBlock.h"
12306f32e7eSjoerg #include "llvm/CodeGen/MachineConstantPool.h"
12406f32e7eSjoerg #include "llvm/CodeGen/MachineFrameInfo.h"
12506f32e7eSjoerg #include "llvm/CodeGen/MachineFunction.h"
12606f32e7eSjoerg #include "llvm/CodeGen/MachineInstr.h"
12706f32e7eSjoerg #include "llvm/CodeGen/MachineInstrBuilder.h"
12806f32e7eSjoerg #include "llvm/CodeGen/MachineJumpTableInfo.h"
12906f32e7eSjoerg #include "llvm/CodeGen/MachineModuleInfo.h"
13006f32e7eSjoerg #include "llvm/CodeGen/MachineOperand.h"
13106f32e7eSjoerg #include "llvm/CodeGen/MachineRegisterInfo.h"
13206f32e7eSjoerg #include "llvm/CodeGen/RegisterScavenging.h"
13306f32e7eSjoerg #include "llvm/CodeGen/TargetInstrInfo.h"
13406f32e7eSjoerg #include "llvm/CodeGen/TargetOpcodes.h"
13506f32e7eSjoerg #include "llvm/CodeGen/TargetRegisterInfo.h"
13606f32e7eSjoerg #include "llvm/CodeGen/TargetSubtargetInfo.h"
13706f32e7eSjoerg #include "llvm/IR/Attributes.h"
13806f32e7eSjoerg #include "llvm/IR/CallingConv.h"
13906f32e7eSjoerg #include "llvm/IR/DebugLoc.h"
14006f32e7eSjoerg #include "llvm/IR/Function.h"
14106f32e7eSjoerg #include "llvm/MC/MCContext.h"
14206f32e7eSjoerg #include "llvm/MC/MCDwarf.h"
14306f32e7eSjoerg #include "llvm/MC/MCInstrDesc.h"
14406f32e7eSjoerg #include "llvm/MC/MCRegisterInfo.h"
14506f32e7eSjoerg #include "llvm/Support/CodeGen.h"
14606f32e7eSjoerg #include "llvm/Support/CommandLine.h"
14706f32e7eSjoerg #include "llvm/Support/Compiler.h"
14806f32e7eSjoerg #include "llvm/Support/Debug.h"
14906f32e7eSjoerg #include "llvm/Support/ErrorHandling.h"
15006f32e7eSjoerg #include "llvm/Support/MathExtras.h"
15106f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
15206f32e7eSjoerg #include "llvm/Target/TargetMachine.h"
15306f32e7eSjoerg #include "llvm/Target/TargetOptions.h"
15406f32e7eSjoerg #include <algorithm>
15506f32e7eSjoerg #include <cassert>
15606f32e7eSjoerg #include <cstddef>
15706f32e7eSjoerg #include <cstdint>
15806f32e7eSjoerg #include <iterator>
15906f32e7eSjoerg #include <utility>
16006f32e7eSjoerg #include <vector>
16106f32e7eSjoerg 
16206f32e7eSjoerg #define DEBUG_TYPE "arm-frame-lowering"
16306f32e7eSjoerg 
16406f32e7eSjoerg using namespace llvm;
16506f32e7eSjoerg 
16606f32e7eSjoerg static cl::opt<bool>
16706f32e7eSjoerg SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
16806f32e7eSjoerg                      cl::desc("Align ARM NEON spills in prolog and epilog"));
16906f32e7eSjoerg 
17006f32e7eSjoerg static MachineBasicBlock::iterator
17106f32e7eSjoerg skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
17206f32e7eSjoerg                         unsigned NumAlignedDPRCS2Regs);
17306f32e7eSjoerg 
ARMFrameLowering(const ARMSubtarget & sti)17406f32e7eSjoerg ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
17506f32e7eSjoerg     : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
17606f32e7eSjoerg       STI(sti) {}
17706f32e7eSjoerg 
keepFramePointer(const MachineFunction & MF) const17806f32e7eSjoerg bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
17906f32e7eSjoerg   // iOS always has a FP for backtracking, force other targets to keep their FP
18006f32e7eSjoerg   // when doing FastISel. The emitted code is currently superior, and in cases
18106f32e7eSjoerg   // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
18206f32e7eSjoerg   return MF.getSubtarget<ARMSubtarget>().useFastISel();
18306f32e7eSjoerg }
18406f32e7eSjoerg 
18506f32e7eSjoerg /// Returns true if the target can safely skip saving callee-saved registers
18606f32e7eSjoerg /// for noreturn nounwind functions.
enableCalleeSaveSkip(const MachineFunction & MF) const18706f32e7eSjoerg bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
18806f32e7eSjoerg   assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
18906f32e7eSjoerg          MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
19006f32e7eSjoerg          !MF.getFunction().hasFnAttribute(Attribute::UWTable));
19106f32e7eSjoerg 
19206f32e7eSjoerg   // Frame pointer and link register are not treated as normal CSR, thus we
19306f32e7eSjoerg   // can always skip CSR saves for nonreturning functions.
19406f32e7eSjoerg   return true;
19506f32e7eSjoerg }
19606f32e7eSjoerg 
19706f32e7eSjoerg /// hasFP - Return true if the specified function should have a dedicated frame
19806f32e7eSjoerg /// pointer register.  This is true if the function has variable sized allocas
19906f32e7eSjoerg /// or if frame pointer elimination is disabled.
hasFP(const MachineFunction & MF) const20006f32e7eSjoerg bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
20106f32e7eSjoerg   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
20206f32e7eSjoerg   const MachineFrameInfo &MFI = MF.getFrameInfo();
20306f32e7eSjoerg 
20406f32e7eSjoerg   // ABI-required frame pointer.
20506f32e7eSjoerg   if (MF.getTarget().Options.DisableFramePointerElim(MF))
20606f32e7eSjoerg     return true;
20706f32e7eSjoerg 
20806f32e7eSjoerg   // Frame pointer required for use within this function.
209*da58b97aSjoerg   return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
21006f32e7eSjoerg           MFI.isFrameAddressTaken());
21106f32e7eSjoerg }
21206f32e7eSjoerg 
21306f32e7eSjoerg /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
21406f32e7eSjoerg /// not required, we reserve argument space for call sites in the function
21506f32e7eSjoerg /// immediately on entry to the current function.  This eliminates the need for
21606f32e7eSjoerg /// add/sub sp brackets around call sites.  Returns true if the call frame is
21706f32e7eSjoerg /// included as part of the stack frame.
hasReservedCallFrame(const MachineFunction & MF) const21806f32e7eSjoerg bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
21906f32e7eSjoerg   const MachineFrameInfo &MFI = MF.getFrameInfo();
22006f32e7eSjoerg   unsigned CFSize = MFI.getMaxCallFrameSize();
22106f32e7eSjoerg   // It's not always a good idea to include the call frame as part of the
22206f32e7eSjoerg   // stack frame. ARM (especially Thumb) has small immediate offset to
22306f32e7eSjoerg   // address the stack frame. So a large call frame can cause poor codegen
22406f32e7eSjoerg   // and may even makes it impossible to scavenge a register.
22506f32e7eSjoerg   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
22606f32e7eSjoerg     return false;
22706f32e7eSjoerg 
22806f32e7eSjoerg   return !MFI.hasVarSizedObjects();
22906f32e7eSjoerg }
23006f32e7eSjoerg 
23106f32e7eSjoerg /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
23206f32e7eSjoerg /// call frame pseudos can be simplified.  Unlike most targets, having a FP
23306f32e7eSjoerg /// is not sufficient here since we still may reference some objects via SP
23406f32e7eSjoerg /// even when FP is available in Thumb2 mode.
23506f32e7eSjoerg bool
canSimplifyCallFramePseudos(const MachineFunction & MF) const23606f32e7eSjoerg ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
23706f32e7eSjoerg   return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
23806f32e7eSjoerg }
23906f32e7eSjoerg 
emitRegPlusImmediate(bool isARM,MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,const DebugLoc & dl,const ARMBaseInstrInfo & TII,unsigned DestReg,unsigned SrcReg,int NumBytes,unsigned MIFlags=MachineInstr::NoFlags,ARMCC::CondCodes Pred=ARMCC::AL,unsigned PredReg=0)24006f32e7eSjoerg static void emitRegPlusImmediate(
24106f32e7eSjoerg     bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
24206f32e7eSjoerg     const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
24306f32e7eSjoerg     unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
24406f32e7eSjoerg     ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
24506f32e7eSjoerg   if (isARM)
24606f32e7eSjoerg     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
24706f32e7eSjoerg                             Pred, PredReg, TII, MIFlags);
24806f32e7eSjoerg   else
24906f32e7eSjoerg     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
25006f32e7eSjoerg                            Pred, PredReg, TII, MIFlags);
25106f32e7eSjoerg }
25206f32e7eSjoerg 
emitSPUpdate(bool isARM,MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,const DebugLoc & dl,const ARMBaseInstrInfo & TII,int NumBytes,unsigned MIFlags=MachineInstr::NoFlags,ARMCC::CondCodes Pred=ARMCC::AL,unsigned PredReg=0)25306f32e7eSjoerg static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
25406f32e7eSjoerg                          MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
25506f32e7eSjoerg                          const ARMBaseInstrInfo &TII, int NumBytes,
25606f32e7eSjoerg                          unsigned MIFlags = MachineInstr::NoFlags,
25706f32e7eSjoerg                          ARMCC::CondCodes Pred = ARMCC::AL,
25806f32e7eSjoerg                          unsigned PredReg = 0) {
25906f32e7eSjoerg   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
26006f32e7eSjoerg                        MIFlags, Pred, PredReg);
26106f32e7eSjoerg }
26206f32e7eSjoerg 
sizeOfSPAdjustment(const MachineInstr & MI)26306f32e7eSjoerg static int sizeOfSPAdjustment(const MachineInstr &MI) {
26406f32e7eSjoerg   int RegSize;
26506f32e7eSjoerg   switch (MI.getOpcode()) {
26606f32e7eSjoerg   case ARM::VSTMDDB_UPD:
26706f32e7eSjoerg     RegSize = 8;
26806f32e7eSjoerg     break;
26906f32e7eSjoerg   case ARM::STMDB_UPD:
27006f32e7eSjoerg   case ARM::t2STMDB_UPD:
27106f32e7eSjoerg     RegSize = 4;
27206f32e7eSjoerg     break;
27306f32e7eSjoerg   case ARM::t2STR_PRE:
27406f32e7eSjoerg   case ARM::STR_PRE_IMM:
27506f32e7eSjoerg     return 4;
27606f32e7eSjoerg   default:
27706f32e7eSjoerg     llvm_unreachable("Unknown push or pop like instruction");
27806f32e7eSjoerg   }
27906f32e7eSjoerg 
28006f32e7eSjoerg   int count = 0;
28106f32e7eSjoerg   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
28206f32e7eSjoerg   // pred) so the list starts at 4.
28306f32e7eSjoerg   for (int i = MI.getNumOperands() - 1; i >= 4; --i)
28406f32e7eSjoerg     count += RegSize;
28506f32e7eSjoerg   return count;
28606f32e7eSjoerg }
28706f32e7eSjoerg 
WindowsRequiresStackProbe(const MachineFunction & MF,size_t StackSizeInBytes)28806f32e7eSjoerg static bool WindowsRequiresStackProbe(const MachineFunction &MF,
28906f32e7eSjoerg                                       size_t StackSizeInBytes) {
29006f32e7eSjoerg   const MachineFrameInfo &MFI = MF.getFrameInfo();
29106f32e7eSjoerg   const Function &F = MF.getFunction();
29206f32e7eSjoerg   unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
29306f32e7eSjoerg   if (F.hasFnAttribute("stack-probe-size"))
29406f32e7eSjoerg     F.getFnAttribute("stack-probe-size")
29506f32e7eSjoerg         .getValueAsString()
29606f32e7eSjoerg         .getAsInteger(0, StackProbeSize);
29706f32e7eSjoerg   return (StackSizeInBytes >= StackProbeSize) &&
29806f32e7eSjoerg          !F.hasFnAttribute("no-stack-arg-probe");
29906f32e7eSjoerg }
30006f32e7eSjoerg 
30106f32e7eSjoerg namespace {
30206f32e7eSjoerg 
30306f32e7eSjoerg struct StackAdjustingInsts {
30406f32e7eSjoerg   struct InstInfo {
30506f32e7eSjoerg     MachineBasicBlock::iterator I;
30606f32e7eSjoerg     unsigned SPAdjust;
30706f32e7eSjoerg     bool BeforeFPSet;
30806f32e7eSjoerg   };
30906f32e7eSjoerg 
31006f32e7eSjoerg   SmallVector<InstInfo, 4> Insts;
31106f32e7eSjoerg 
addInst__anonebe708080111::StackAdjustingInsts31206f32e7eSjoerg   void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
31306f32e7eSjoerg                bool BeforeFPSet = false) {
31406f32e7eSjoerg     InstInfo Info = {I, SPAdjust, BeforeFPSet};
31506f32e7eSjoerg     Insts.push_back(Info);
31606f32e7eSjoerg   }
31706f32e7eSjoerg 
addExtraBytes__anonebe708080111::StackAdjustingInsts31806f32e7eSjoerg   void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
31906f32e7eSjoerg     auto Info =
32006f32e7eSjoerg         llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
32106f32e7eSjoerg     assert(Info != Insts.end() && "invalid sp adjusting instruction");
32206f32e7eSjoerg     Info->SPAdjust += ExtraBytes;
32306f32e7eSjoerg   }
32406f32e7eSjoerg 
emitDefCFAOffsets__anonebe708080111::StackAdjustingInsts32506f32e7eSjoerg   void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
32606f32e7eSjoerg                          const ARMBaseInstrInfo &TII, bool HasFP) {
32706f32e7eSjoerg     MachineFunction &MF = *MBB.getParent();
32806f32e7eSjoerg     unsigned CFAOffset = 0;
32906f32e7eSjoerg     for (auto &Info : Insts) {
33006f32e7eSjoerg       if (HasFP && !Info.BeforeFPSet)
33106f32e7eSjoerg         return;
33206f32e7eSjoerg 
333*da58b97aSjoerg       CFAOffset += Info.SPAdjust;
33406f32e7eSjoerg       unsigned CFIIndex = MF.addFrameInst(
335*da58b97aSjoerg           MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
33606f32e7eSjoerg       BuildMI(MBB, std::next(Info.I), dl,
33706f32e7eSjoerg               TII.get(TargetOpcode::CFI_INSTRUCTION))
33806f32e7eSjoerg               .addCFIIndex(CFIIndex)
33906f32e7eSjoerg               .setMIFlags(MachineInstr::FrameSetup);
34006f32e7eSjoerg     }
34106f32e7eSjoerg   }
34206f32e7eSjoerg };
34306f32e7eSjoerg 
34406f32e7eSjoerg } // end anonymous namespace
34506f32e7eSjoerg 
34606f32e7eSjoerg /// Emit an instruction sequence that will align the address in
34706f32e7eSjoerg /// register Reg by zero-ing out the lower bits.  For versions of the
34806f32e7eSjoerg /// architecture that support Neon, this must be done in a single
34906f32e7eSjoerg /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
35006f32e7eSjoerg /// single instruction. That function only gets called when optimizing
35106f32e7eSjoerg /// spilling of D registers on a core with the Neon instruction set
35206f32e7eSjoerg /// present.
emitAligningInstructions(MachineFunction & MF,ARMFunctionInfo * AFI,const TargetInstrInfo & TII,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,const unsigned Reg,const Align Alignment,const bool MustBeSingleInstruction)35306f32e7eSjoerg static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
35406f32e7eSjoerg                                      const TargetInstrInfo &TII,
35506f32e7eSjoerg                                      MachineBasicBlock &MBB,
35606f32e7eSjoerg                                      MachineBasicBlock::iterator MBBI,
35706f32e7eSjoerg                                      const DebugLoc &DL, const unsigned Reg,
358*da58b97aSjoerg                                      const Align Alignment,
35906f32e7eSjoerg                                      const bool MustBeSingleInstruction) {
36006f32e7eSjoerg   const ARMSubtarget &AST =
36106f32e7eSjoerg       static_cast<const ARMSubtarget &>(MF.getSubtarget());
36206f32e7eSjoerg   const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
363*da58b97aSjoerg   const unsigned AlignMask = Alignment.value() - 1U;
364*da58b97aSjoerg   const unsigned NrBitsToZero = Log2(Alignment);
36506f32e7eSjoerg   assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
36606f32e7eSjoerg   if (!AFI->isThumbFunction()) {
36706f32e7eSjoerg     // if the BFC instruction is available, use that to zero the lower
36806f32e7eSjoerg     // bits:
36906f32e7eSjoerg     //   bfc Reg, #0, log2(Alignment)
37006f32e7eSjoerg     // otherwise use BIC, if the mask to zero the required number of bits
37106f32e7eSjoerg     // can be encoded in the bic immediate field
37206f32e7eSjoerg     //   bic Reg, Reg, Alignment-1
37306f32e7eSjoerg     // otherwise, emit
37406f32e7eSjoerg     //   lsr Reg, Reg, log2(Alignment)
37506f32e7eSjoerg     //   lsl Reg, Reg, log2(Alignment)
37606f32e7eSjoerg     if (CanUseBFC) {
37706f32e7eSjoerg       BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
37806f32e7eSjoerg           .addReg(Reg, RegState::Kill)
37906f32e7eSjoerg           .addImm(~AlignMask)
38006f32e7eSjoerg           .add(predOps(ARMCC::AL));
38106f32e7eSjoerg     } else if (AlignMask <= 255) {
38206f32e7eSjoerg       BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
38306f32e7eSjoerg           .addReg(Reg, RegState::Kill)
38406f32e7eSjoerg           .addImm(AlignMask)
38506f32e7eSjoerg           .add(predOps(ARMCC::AL))
38606f32e7eSjoerg           .add(condCodeOp());
38706f32e7eSjoerg     } else {
38806f32e7eSjoerg       assert(!MustBeSingleInstruction &&
38906f32e7eSjoerg              "Shouldn't call emitAligningInstructions demanding a single "
39006f32e7eSjoerg              "instruction to be emitted for large stack alignment for a target "
39106f32e7eSjoerg              "without BFC.");
39206f32e7eSjoerg       BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
39306f32e7eSjoerg           .addReg(Reg, RegState::Kill)
39406f32e7eSjoerg           .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
39506f32e7eSjoerg           .add(predOps(ARMCC::AL))
39606f32e7eSjoerg           .add(condCodeOp());
39706f32e7eSjoerg       BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
39806f32e7eSjoerg           .addReg(Reg, RegState::Kill)
39906f32e7eSjoerg           .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
40006f32e7eSjoerg           .add(predOps(ARMCC::AL))
40106f32e7eSjoerg           .add(condCodeOp());
40206f32e7eSjoerg     }
40306f32e7eSjoerg   } else {
40406f32e7eSjoerg     // Since this is only reached for Thumb-2 targets, the BFC instruction
40506f32e7eSjoerg     // should always be available.
40606f32e7eSjoerg     assert(CanUseBFC);
40706f32e7eSjoerg     BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
40806f32e7eSjoerg         .addReg(Reg, RegState::Kill)
40906f32e7eSjoerg         .addImm(~AlignMask)
41006f32e7eSjoerg         .add(predOps(ARMCC::AL));
41106f32e7eSjoerg   }
41206f32e7eSjoerg }
41306f32e7eSjoerg 
41406f32e7eSjoerg /// We need the offset of the frame pointer relative to other MachineFrameInfo
41506f32e7eSjoerg /// offsets which are encoded relative to SP at function begin.
41606f32e7eSjoerg /// See also emitPrologue() for how the FP is set up.
41706f32e7eSjoerg /// Unfortunately we cannot determine this value in determineCalleeSaves() yet
41806f32e7eSjoerg /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
41906f32e7eSjoerg /// this to produce a conservative estimate that we check in an assert() later.
getMaxFPOffset(const ARMSubtarget & STI,const ARMFunctionInfo & AFI)420*da58b97aSjoerg static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI) {
42106f32e7eSjoerg   // For Thumb1, push.w isn't available, so the first push will always push
42206f32e7eSjoerg   // r7 and lr onto the stack first.
42306f32e7eSjoerg   if (AFI.isThumb1OnlyFunction())
42406f32e7eSjoerg     return -AFI.getArgRegsSaveSize() - (2 * 4);
42506f32e7eSjoerg   // This is a conservative estimation: Assume the frame pointer being r7 and
42606f32e7eSjoerg   // pc("r15") up to r8 getting spilled before (= 8 registers).
427*da58b97aSjoerg   int FPCXTSaveSize = (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0;
428*da58b97aSjoerg   return - FPCXTSaveSize - AFI.getArgRegsSaveSize() - (8 * 4);
42906f32e7eSjoerg }
43006f32e7eSjoerg 
emitPrologue(MachineFunction & MF,MachineBasicBlock & MBB) const43106f32e7eSjoerg void ARMFrameLowering::emitPrologue(MachineFunction &MF,
43206f32e7eSjoerg                                     MachineBasicBlock &MBB) const {
43306f32e7eSjoerg   MachineBasicBlock::iterator MBBI = MBB.begin();
43406f32e7eSjoerg   MachineFrameInfo  &MFI = MF.getFrameInfo();
43506f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
43606f32e7eSjoerg   MachineModuleInfo &MMI = MF.getMMI();
43706f32e7eSjoerg   MCContext &Context = MMI.getContext();
43806f32e7eSjoerg   const TargetMachine &TM = MF.getTarget();
43906f32e7eSjoerg   const MCRegisterInfo *MRI = Context.getRegisterInfo();
44006f32e7eSjoerg   const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
44106f32e7eSjoerg   const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
44206f32e7eSjoerg   assert(!AFI->isThumb1OnlyFunction() &&
44306f32e7eSjoerg          "This emitPrologue does not support Thumb1!");
44406f32e7eSjoerg   bool isARM = !AFI->isThumbFunction();
445*da58b97aSjoerg   Align Alignment = STI.getFrameLowering()->getStackAlign();
44606f32e7eSjoerg   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
44706f32e7eSjoerg   unsigned NumBytes = MFI.getStackSize();
44806f32e7eSjoerg   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
449*da58b97aSjoerg   int FPCXTSaveSize = 0;
45006f32e7eSjoerg 
45106f32e7eSjoerg   // Debug location must be unknown since the first debug location is used
45206f32e7eSjoerg   // to determine the end of the prologue.
45306f32e7eSjoerg   DebugLoc dl;
45406f32e7eSjoerg 
45506f32e7eSjoerg   Register FramePtr = RegInfo->getFrameRegister(MF);
45606f32e7eSjoerg 
45706f32e7eSjoerg   // Determine the sizes of each callee-save spill areas and record which frame
45806f32e7eSjoerg   // belongs to which callee-save spill areas.
45906f32e7eSjoerg   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
46006f32e7eSjoerg   int FramePtrSpillFI = 0;
46106f32e7eSjoerg   int D8SpillFI = 0;
46206f32e7eSjoerg 
46306f32e7eSjoerg   // All calls are tail calls in GHC calling conv, and functions have no
46406f32e7eSjoerg   // prologue/epilogue.
46506f32e7eSjoerg   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
46606f32e7eSjoerg     return;
46706f32e7eSjoerg 
46806f32e7eSjoerg   StackAdjustingInsts DefCFAOffsetCandidates;
46906f32e7eSjoerg   bool HasFP = hasFP(MF);
47006f32e7eSjoerg 
47106f32e7eSjoerg   // Allocate the vararg register save area.
47206f32e7eSjoerg   if (ArgRegsSaveSize) {
47306f32e7eSjoerg     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
47406f32e7eSjoerg                  MachineInstr::FrameSetup);
47506f32e7eSjoerg     DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
47606f32e7eSjoerg   }
47706f32e7eSjoerg 
47806f32e7eSjoerg   if (!AFI->hasStackFrame() &&
47906f32e7eSjoerg       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
48006f32e7eSjoerg     if (NumBytes - ArgRegsSaveSize != 0) {
48106f32e7eSjoerg       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
48206f32e7eSjoerg                    MachineInstr::FrameSetup);
48306f32e7eSjoerg       DefCFAOffsetCandidates.addInst(std::prev(MBBI),
48406f32e7eSjoerg                                      NumBytes - ArgRegsSaveSize, true);
48506f32e7eSjoerg     }
48606f32e7eSjoerg     DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
48706f32e7eSjoerg     return;
48806f32e7eSjoerg   }
48906f32e7eSjoerg 
49006f32e7eSjoerg   // Determine spill area sizes.
49106f32e7eSjoerg   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
49206f32e7eSjoerg     unsigned Reg = CSI[i].getReg();
49306f32e7eSjoerg     int FI = CSI[i].getFrameIdx();
49406f32e7eSjoerg     switch (Reg) {
49506f32e7eSjoerg     case ARM::R8:
49606f32e7eSjoerg     case ARM::R9:
49706f32e7eSjoerg     case ARM::R10:
49806f32e7eSjoerg     case ARM::R11:
49906f32e7eSjoerg     case ARM::R12:
50006f32e7eSjoerg       if (STI.splitFramePushPop(MF)) {
50106f32e7eSjoerg         GPRCS2Size += 4;
50206f32e7eSjoerg         break;
50306f32e7eSjoerg       }
50406f32e7eSjoerg       LLVM_FALLTHROUGH;
50506f32e7eSjoerg     case ARM::R0:
50606f32e7eSjoerg     case ARM::R1:
50706f32e7eSjoerg     case ARM::R2:
50806f32e7eSjoerg     case ARM::R3:
50906f32e7eSjoerg     case ARM::R4:
51006f32e7eSjoerg     case ARM::R5:
51106f32e7eSjoerg     case ARM::R6:
51206f32e7eSjoerg     case ARM::R7:
51306f32e7eSjoerg     case ARM::LR:
51406f32e7eSjoerg       if (Reg == FramePtr)
51506f32e7eSjoerg         FramePtrSpillFI = FI;
51606f32e7eSjoerg       GPRCS1Size += 4;
51706f32e7eSjoerg       break;
518*da58b97aSjoerg     case ARM::FPCXTNS:
519*da58b97aSjoerg       FPCXTSaveSize = 4;
520*da58b97aSjoerg       break;
52106f32e7eSjoerg     default:
52206f32e7eSjoerg       // This is a DPR. Exclude the aligned DPRCS2 spills.
52306f32e7eSjoerg       if (Reg == ARM::D8)
52406f32e7eSjoerg         D8SpillFI = FI;
52506f32e7eSjoerg       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
52606f32e7eSjoerg         DPRCSSize += 8;
52706f32e7eSjoerg     }
52806f32e7eSjoerg   }
52906f32e7eSjoerg 
530*da58b97aSjoerg   // Move past FPCXT area.
53106f32e7eSjoerg   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
532*da58b97aSjoerg   if (FPCXTSaveSize > 0) {
533*da58b97aSjoerg     LastPush = MBBI++;
534*da58b97aSjoerg     DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, true);
535*da58b97aSjoerg   }
536*da58b97aSjoerg 
537*da58b97aSjoerg   // Move past area 1.
53806f32e7eSjoerg   if (GPRCS1Size > 0) {
53906f32e7eSjoerg     GPRCS1Push = LastPush = MBBI++;
54006f32e7eSjoerg     DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
54106f32e7eSjoerg   }
54206f32e7eSjoerg 
54306f32e7eSjoerg   // Determine starting offsets of spill areas.
544*da58b97aSjoerg   unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize;
545*da58b97aSjoerg   unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size;
54606f32e7eSjoerg   unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
547*da58b97aSjoerg   Align DPRAlign = DPRCSSize ? std::min(Align(8), Alignment) : Align(4);
548*da58b97aSjoerg   unsigned DPRGapSize =
549*da58b97aSjoerg       (GPRCS1Size + GPRCS2Size + FPCXTSaveSize + ArgRegsSaveSize) %
550*da58b97aSjoerg       DPRAlign.value();
551*da58b97aSjoerg 
55206f32e7eSjoerg   unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
55306f32e7eSjoerg   int FramePtrOffsetInPush = 0;
55406f32e7eSjoerg   if (HasFP) {
55506f32e7eSjoerg     int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
556*da58b97aSjoerg     assert(getMaxFPOffset(STI, *AFI) <= FPOffset &&
55706f32e7eSjoerg            "Max FP estimation is wrong");
558*da58b97aSjoerg     FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize + FPCXTSaveSize;
55906f32e7eSjoerg     AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
56006f32e7eSjoerg                                 NumBytes);
56106f32e7eSjoerg   }
56206f32e7eSjoerg   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
56306f32e7eSjoerg   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
56406f32e7eSjoerg   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
56506f32e7eSjoerg 
56606f32e7eSjoerg   // Move past area 2.
56706f32e7eSjoerg   if (GPRCS2Size > 0) {
56806f32e7eSjoerg     GPRCS2Push = LastPush = MBBI++;
56906f32e7eSjoerg     DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
57006f32e7eSjoerg   }
57106f32e7eSjoerg 
57206f32e7eSjoerg   // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
57306f32e7eSjoerg   // .cfi_offset operations will reflect that.
57406f32e7eSjoerg   if (DPRGapSize) {
57506f32e7eSjoerg     assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
57606f32e7eSjoerg     if (LastPush != MBB.end() &&
57706f32e7eSjoerg         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
57806f32e7eSjoerg       DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
57906f32e7eSjoerg     else {
58006f32e7eSjoerg       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
58106f32e7eSjoerg                    MachineInstr::FrameSetup);
58206f32e7eSjoerg       DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
58306f32e7eSjoerg     }
58406f32e7eSjoerg   }
58506f32e7eSjoerg 
58606f32e7eSjoerg   // Move past area 3.
58706f32e7eSjoerg   if (DPRCSSize > 0) {
58806f32e7eSjoerg     // Since vpush register list cannot have gaps, there may be multiple vpush
58906f32e7eSjoerg     // instructions in the prologue.
59006f32e7eSjoerg     while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
59106f32e7eSjoerg       DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
59206f32e7eSjoerg       LastPush = MBBI++;
59306f32e7eSjoerg     }
59406f32e7eSjoerg   }
59506f32e7eSjoerg 
59606f32e7eSjoerg   // Move past the aligned DPRCS2 area.
59706f32e7eSjoerg   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
59806f32e7eSjoerg     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
59906f32e7eSjoerg     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
60006f32e7eSjoerg     // leaves the stack pointer pointing to the DPRCS2 area.
60106f32e7eSjoerg     //
60206f32e7eSjoerg     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
60306f32e7eSjoerg     NumBytes += MFI.getObjectOffset(D8SpillFI);
60406f32e7eSjoerg   } else
60506f32e7eSjoerg     NumBytes = DPRCSOffset;
60606f32e7eSjoerg 
60706f32e7eSjoerg   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
60806f32e7eSjoerg     uint32_t NumWords = NumBytes >> 2;
60906f32e7eSjoerg 
61006f32e7eSjoerg     if (NumWords < 65536)
61106f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
61206f32e7eSjoerg           .addImm(NumWords)
61306f32e7eSjoerg           .setMIFlags(MachineInstr::FrameSetup)
61406f32e7eSjoerg           .add(predOps(ARMCC::AL));
61506f32e7eSjoerg     else
61606f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
61706f32e7eSjoerg         .addImm(NumWords)
61806f32e7eSjoerg         .setMIFlags(MachineInstr::FrameSetup);
61906f32e7eSjoerg 
62006f32e7eSjoerg     switch (TM.getCodeModel()) {
62106f32e7eSjoerg     case CodeModel::Tiny:
62206f32e7eSjoerg       llvm_unreachable("Tiny code model not available on ARM.");
62306f32e7eSjoerg     case CodeModel::Small:
62406f32e7eSjoerg     case CodeModel::Medium:
62506f32e7eSjoerg     case CodeModel::Kernel:
62606f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
62706f32e7eSjoerg           .add(predOps(ARMCC::AL))
62806f32e7eSjoerg           .addExternalSymbol("__chkstk")
62906f32e7eSjoerg           .addReg(ARM::R4, RegState::Implicit)
63006f32e7eSjoerg           .setMIFlags(MachineInstr::FrameSetup);
63106f32e7eSjoerg       break;
63206f32e7eSjoerg     case CodeModel::Large:
63306f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
63406f32e7eSjoerg         .addExternalSymbol("__chkstk")
63506f32e7eSjoerg         .setMIFlags(MachineInstr::FrameSetup);
63606f32e7eSjoerg 
63706f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
63806f32e7eSjoerg           .add(predOps(ARMCC::AL))
63906f32e7eSjoerg           .addReg(ARM::R12, RegState::Kill)
64006f32e7eSjoerg           .addReg(ARM::R4, RegState::Implicit)
64106f32e7eSjoerg           .setMIFlags(MachineInstr::FrameSetup);
64206f32e7eSjoerg       break;
64306f32e7eSjoerg     }
64406f32e7eSjoerg 
64506f32e7eSjoerg     BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
64606f32e7eSjoerg         .addReg(ARM::SP, RegState::Kill)
64706f32e7eSjoerg         .addReg(ARM::R4, RegState::Kill)
64806f32e7eSjoerg         .setMIFlags(MachineInstr::FrameSetup)
64906f32e7eSjoerg         .add(predOps(ARMCC::AL))
65006f32e7eSjoerg         .add(condCodeOp());
65106f32e7eSjoerg     NumBytes = 0;
65206f32e7eSjoerg   }
65306f32e7eSjoerg 
65406f32e7eSjoerg   if (NumBytes) {
65506f32e7eSjoerg     // Adjust SP after all the callee-save spills.
65606f32e7eSjoerg     if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
65706f32e7eSjoerg         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
65806f32e7eSjoerg       DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
65906f32e7eSjoerg     else {
66006f32e7eSjoerg       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
66106f32e7eSjoerg                    MachineInstr::FrameSetup);
66206f32e7eSjoerg       DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
66306f32e7eSjoerg     }
66406f32e7eSjoerg 
66506f32e7eSjoerg     if (HasFP && isARM)
66606f32e7eSjoerg       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
66706f32e7eSjoerg       // Note it's not safe to do this in Thumb2 mode because it would have
66806f32e7eSjoerg       // taken two instructions:
66906f32e7eSjoerg       // mov sp, r7
67006f32e7eSjoerg       // sub sp, #24
67106f32e7eSjoerg       // If an interrupt is taken between the two instructions, then sp is in
67206f32e7eSjoerg       // an inconsistent state (pointing to the middle of callee-saved area).
67306f32e7eSjoerg       // The interrupt handler can end up clobbering the registers.
67406f32e7eSjoerg       AFI->setShouldRestoreSPFromFP(true);
67506f32e7eSjoerg   }
67606f32e7eSjoerg 
67706f32e7eSjoerg   // Set FP to point to the stack slot that contains the previous FP.
67806f32e7eSjoerg   // For iOS, FP is R7, which has now been stored in spill area 1.
67906f32e7eSjoerg   // Otherwise, if this is not iOS, all the callee-saved registers go
68006f32e7eSjoerg   // into spill area 1, including the FP in R11.  In either case, it
68106f32e7eSjoerg   // is in area one and the adjustment needs to take place just after
68206f32e7eSjoerg   // that push.
68306f32e7eSjoerg   if (HasFP) {
68406f32e7eSjoerg     MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
68506f32e7eSjoerg     unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
68606f32e7eSjoerg     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
68706f32e7eSjoerg                          dl, TII, FramePtr, ARM::SP,
68806f32e7eSjoerg                          PushSize + FramePtrOffsetInPush,
68906f32e7eSjoerg                          MachineInstr::FrameSetup);
69006f32e7eSjoerg     if (FramePtrOffsetInPush + PushSize != 0) {
691*da58b97aSjoerg       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
69206f32e7eSjoerg           nullptr, MRI->getDwarfRegNum(FramePtr, true),
693*da58b97aSjoerg           FPCXTSaveSize + ArgRegsSaveSize - FramePtrOffsetInPush));
69406f32e7eSjoerg       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
69506f32e7eSjoerg           .addCFIIndex(CFIIndex)
69606f32e7eSjoerg           .setMIFlags(MachineInstr::FrameSetup);
69706f32e7eSjoerg     } else {
69806f32e7eSjoerg       unsigned CFIIndex =
69906f32e7eSjoerg           MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
70006f32e7eSjoerg               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
70106f32e7eSjoerg       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
70206f32e7eSjoerg           .addCFIIndex(CFIIndex)
70306f32e7eSjoerg           .setMIFlags(MachineInstr::FrameSetup);
70406f32e7eSjoerg     }
70506f32e7eSjoerg   }
70606f32e7eSjoerg 
70706f32e7eSjoerg   // Now that the prologue's actual instructions are finalised, we can insert
70806f32e7eSjoerg   // the necessary DWARF cf instructions to describe the situation. Start by
70906f32e7eSjoerg   // recording where each register ended up:
71006f32e7eSjoerg   if (GPRCS1Size > 0) {
71106f32e7eSjoerg     MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
71206f32e7eSjoerg     int CFIIndex;
71306f32e7eSjoerg     for (const auto &Entry : CSI) {
71406f32e7eSjoerg       unsigned Reg = Entry.getReg();
71506f32e7eSjoerg       int FI = Entry.getFrameIdx();
71606f32e7eSjoerg       switch (Reg) {
71706f32e7eSjoerg       case ARM::R8:
71806f32e7eSjoerg       case ARM::R9:
71906f32e7eSjoerg       case ARM::R10:
72006f32e7eSjoerg       case ARM::R11:
72106f32e7eSjoerg       case ARM::R12:
72206f32e7eSjoerg         if (STI.splitFramePushPop(MF))
72306f32e7eSjoerg           break;
72406f32e7eSjoerg         LLVM_FALLTHROUGH;
72506f32e7eSjoerg       case ARM::R0:
72606f32e7eSjoerg       case ARM::R1:
72706f32e7eSjoerg       case ARM::R2:
72806f32e7eSjoerg       case ARM::R3:
72906f32e7eSjoerg       case ARM::R4:
73006f32e7eSjoerg       case ARM::R5:
73106f32e7eSjoerg       case ARM::R6:
73206f32e7eSjoerg       case ARM::R7:
73306f32e7eSjoerg       case ARM::LR:
73406f32e7eSjoerg         CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
73506f32e7eSjoerg             nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
73606f32e7eSjoerg         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
73706f32e7eSjoerg             .addCFIIndex(CFIIndex)
73806f32e7eSjoerg             .setMIFlags(MachineInstr::FrameSetup);
73906f32e7eSjoerg         break;
74006f32e7eSjoerg       }
74106f32e7eSjoerg     }
74206f32e7eSjoerg   }
74306f32e7eSjoerg 
74406f32e7eSjoerg   if (GPRCS2Size > 0) {
74506f32e7eSjoerg     MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
74606f32e7eSjoerg     for (const auto &Entry : CSI) {
74706f32e7eSjoerg       unsigned Reg = Entry.getReg();
74806f32e7eSjoerg       int FI = Entry.getFrameIdx();
74906f32e7eSjoerg       switch (Reg) {
75006f32e7eSjoerg       case ARM::R8:
75106f32e7eSjoerg       case ARM::R9:
75206f32e7eSjoerg       case ARM::R10:
75306f32e7eSjoerg       case ARM::R11:
75406f32e7eSjoerg       case ARM::R12:
75506f32e7eSjoerg         if (STI.splitFramePushPop(MF)) {
75606f32e7eSjoerg           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
75706f32e7eSjoerg           unsigned Offset = MFI.getObjectOffset(FI);
75806f32e7eSjoerg           unsigned CFIIndex = MF.addFrameInst(
75906f32e7eSjoerg               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
76006f32e7eSjoerg           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
76106f32e7eSjoerg               .addCFIIndex(CFIIndex)
76206f32e7eSjoerg               .setMIFlags(MachineInstr::FrameSetup);
76306f32e7eSjoerg         }
76406f32e7eSjoerg         break;
76506f32e7eSjoerg       }
76606f32e7eSjoerg     }
76706f32e7eSjoerg   }
76806f32e7eSjoerg 
76906f32e7eSjoerg   if (DPRCSSize > 0) {
77006f32e7eSjoerg     // Since vpush register list cannot have gaps, there may be multiple vpush
77106f32e7eSjoerg     // instructions in the prologue.
77206f32e7eSjoerg     MachineBasicBlock::iterator Pos = std::next(LastPush);
77306f32e7eSjoerg     for (const auto &Entry : CSI) {
77406f32e7eSjoerg       unsigned Reg = Entry.getReg();
77506f32e7eSjoerg       int FI = Entry.getFrameIdx();
77606f32e7eSjoerg       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
77706f32e7eSjoerg           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
77806f32e7eSjoerg         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
77906f32e7eSjoerg         unsigned Offset = MFI.getObjectOffset(FI);
78006f32e7eSjoerg         unsigned CFIIndex = MF.addFrameInst(
78106f32e7eSjoerg             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
78206f32e7eSjoerg         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
78306f32e7eSjoerg             .addCFIIndex(CFIIndex)
78406f32e7eSjoerg             .setMIFlags(MachineInstr::FrameSetup);
78506f32e7eSjoerg       }
78606f32e7eSjoerg     }
78706f32e7eSjoerg   }
78806f32e7eSjoerg 
78906f32e7eSjoerg   // Now we can emit descriptions of where the canonical frame address was
79006f32e7eSjoerg   // throughout the process. If we have a frame pointer, it takes over the job
79106f32e7eSjoerg   // half-way through, so only the first few .cfi_def_cfa_offset instructions
79206f32e7eSjoerg   // actually get emitted.
79306f32e7eSjoerg   DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
79406f32e7eSjoerg 
79506f32e7eSjoerg   if (STI.isTargetELF() && hasFP(MF))
79606f32e7eSjoerg     MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
79706f32e7eSjoerg                             AFI->getFramePtrSpillOffset());
79806f32e7eSjoerg 
799*da58b97aSjoerg   AFI->setFPCXTSaveAreaSize(FPCXTSaveSize);
80006f32e7eSjoerg   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
80106f32e7eSjoerg   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
80206f32e7eSjoerg   AFI->setDPRCalleeSavedGapSize(DPRGapSize);
80306f32e7eSjoerg   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
80406f32e7eSjoerg 
80506f32e7eSjoerg   // If we need dynamic stack realignment, do it here. Be paranoid and make
80606f32e7eSjoerg   // sure if we also have VLAs, we have a base pointer for frame access.
80706f32e7eSjoerg   // If aligned NEON registers were spilled, the stack has already been
80806f32e7eSjoerg   // realigned.
809*da58b97aSjoerg   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) {
810*da58b97aSjoerg     Align MaxAlign = MFI.getMaxAlign();
81106f32e7eSjoerg     assert(!AFI->isThumb1OnlyFunction());
81206f32e7eSjoerg     if (!AFI->isThumbFunction()) {
81306f32e7eSjoerg       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
81406f32e7eSjoerg                                false);
81506f32e7eSjoerg     } else {
81606f32e7eSjoerg       // We cannot use sp as source/dest register here, thus we're using r4 to
81706f32e7eSjoerg       // perform the calculations. We're emitting the following sequence:
81806f32e7eSjoerg       // mov r4, sp
81906f32e7eSjoerg       // -- use emitAligningInstructions to produce best sequence to zero
82006f32e7eSjoerg       // -- out lower bits in r4
82106f32e7eSjoerg       // mov sp, r4
82206f32e7eSjoerg       // FIXME: It will be better just to find spare register here.
82306f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
82406f32e7eSjoerg           .addReg(ARM::SP, RegState::Kill)
82506f32e7eSjoerg           .add(predOps(ARMCC::AL));
82606f32e7eSjoerg       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
82706f32e7eSjoerg                                false);
82806f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
82906f32e7eSjoerg           .addReg(ARM::R4, RegState::Kill)
83006f32e7eSjoerg           .add(predOps(ARMCC::AL));
83106f32e7eSjoerg     }
83206f32e7eSjoerg 
83306f32e7eSjoerg     AFI->setShouldRestoreSPFromFP(true);
83406f32e7eSjoerg   }
83506f32e7eSjoerg 
83606f32e7eSjoerg   // If we need a base pointer, set it up here. It's whatever the value
83706f32e7eSjoerg   // of the stack pointer is at this point. Any variable size objects
83806f32e7eSjoerg   // will be allocated after this, so we can still use the base pointer
83906f32e7eSjoerg   // to reference locals.
84006f32e7eSjoerg   // FIXME: Clarify FrameSetup flags here.
84106f32e7eSjoerg   if (RegInfo->hasBasePointer(MF)) {
84206f32e7eSjoerg     if (isARM)
84306f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
84406f32e7eSjoerg           .addReg(ARM::SP)
84506f32e7eSjoerg           .add(predOps(ARMCC::AL))
84606f32e7eSjoerg           .add(condCodeOp());
84706f32e7eSjoerg     else
84806f32e7eSjoerg       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
84906f32e7eSjoerg           .addReg(ARM::SP)
85006f32e7eSjoerg           .add(predOps(ARMCC::AL));
85106f32e7eSjoerg   }
85206f32e7eSjoerg 
85306f32e7eSjoerg   // If the frame has variable sized objects then the epilogue must restore
85406f32e7eSjoerg   // the sp from fp. We can assume there's an FP here since hasFP already
85506f32e7eSjoerg   // checks for hasVarSizedObjects.
85606f32e7eSjoerg   if (MFI.hasVarSizedObjects())
85706f32e7eSjoerg     AFI->setShouldRestoreSPFromFP(true);
85806f32e7eSjoerg }
85906f32e7eSjoerg 
emitEpilogue(MachineFunction & MF,MachineBasicBlock & MBB) const86006f32e7eSjoerg void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
86106f32e7eSjoerg                                     MachineBasicBlock &MBB) const {
86206f32e7eSjoerg   MachineFrameInfo &MFI = MF.getFrameInfo();
86306f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
86406f32e7eSjoerg   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
86506f32e7eSjoerg   const ARMBaseInstrInfo &TII =
86606f32e7eSjoerg       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
86706f32e7eSjoerg   assert(!AFI->isThumb1OnlyFunction() &&
86806f32e7eSjoerg          "This emitEpilogue does not support Thumb1!");
86906f32e7eSjoerg   bool isARM = !AFI->isThumbFunction();
87006f32e7eSjoerg 
87106f32e7eSjoerg   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
87206f32e7eSjoerg   int NumBytes = (int)MFI.getStackSize();
87306f32e7eSjoerg   Register FramePtr = RegInfo->getFrameRegister(MF);
87406f32e7eSjoerg 
87506f32e7eSjoerg   // All calls are tail calls in GHC calling conv, and functions have no
87606f32e7eSjoerg   // prologue/epilogue.
87706f32e7eSjoerg   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
87806f32e7eSjoerg     return;
87906f32e7eSjoerg 
88006f32e7eSjoerg   // First put ourselves on the first (from top) terminator instructions.
88106f32e7eSjoerg   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
88206f32e7eSjoerg   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
88306f32e7eSjoerg 
88406f32e7eSjoerg   if (!AFI->hasStackFrame()) {
88506f32e7eSjoerg     if (NumBytes - ArgRegsSaveSize != 0)
886*da58b97aSjoerg       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize,
887*da58b97aSjoerg                    MachineInstr::FrameDestroy);
88806f32e7eSjoerg   } else {
88906f32e7eSjoerg     // Unwind MBBI to point to first LDR / VLDRD.
89006f32e7eSjoerg     if (MBBI != MBB.begin()) {
89106f32e7eSjoerg       do {
89206f32e7eSjoerg         --MBBI;
893*da58b97aSjoerg       } while (MBBI != MBB.begin() &&
894*da58b97aSjoerg                MBBI->getFlag(MachineInstr::FrameDestroy));
895*da58b97aSjoerg       if (!MBBI->getFlag(MachineInstr::FrameDestroy))
89606f32e7eSjoerg         ++MBBI;
89706f32e7eSjoerg     }
89806f32e7eSjoerg 
89906f32e7eSjoerg     // Move SP to start of FP callee save spill area.
90006f32e7eSjoerg     NumBytes -= (ArgRegsSaveSize +
901*da58b97aSjoerg                  AFI->getFPCXTSaveAreaSize() +
90206f32e7eSjoerg                  AFI->getGPRCalleeSavedArea1Size() +
90306f32e7eSjoerg                  AFI->getGPRCalleeSavedArea2Size() +
90406f32e7eSjoerg                  AFI->getDPRCalleeSavedGapSize() +
90506f32e7eSjoerg                  AFI->getDPRCalleeSavedAreaSize());
90606f32e7eSjoerg 
90706f32e7eSjoerg     // Reset SP based on frame pointer only if the stack frame extends beyond
90806f32e7eSjoerg     // frame pointer stack slot or target is ELF and the function has FP.
90906f32e7eSjoerg     if (AFI->shouldRestoreSPFromFP()) {
91006f32e7eSjoerg       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
91106f32e7eSjoerg       if (NumBytes) {
91206f32e7eSjoerg         if (isARM)
91306f32e7eSjoerg           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
914*da58b97aSjoerg                                   ARMCC::AL, 0, TII,
915*da58b97aSjoerg                                   MachineInstr::FrameDestroy);
91606f32e7eSjoerg         else {
91706f32e7eSjoerg           // It's not possible to restore SP from FP in a single instruction.
91806f32e7eSjoerg           // For iOS, this looks like:
91906f32e7eSjoerg           // mov sp, r7
92006f32e7eSjoerg           // sub sp, #24
92106f32e7eSjoerg           // This is bad, if an interrupt is taken after the mov, sp is in an
92206f32e7eSjoerg           // inconsistent state.
92306f32e7eSjoerg           // Use the first callee-saved register as a scratch register.
92406f32e7eSjoerg           assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
92506f32e7eSjoerg                  "No scratch register to restore SP from FP!");
92606f32e7eSjoerg           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
927*da58b97aSjoerg                                  ARMCC::AL, 0, TII, MachineInstr::FrameDestroy);
92806f32e7eSjoerg           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
92906f32e7eSjoerg               .addReg(ARM::R4)
930*da58b97aSjoerg               .add(predOps(ARMCC::AL))
931*da58b97aSjoerg               .setMIFlag(MachineInstr::FrameDestroy);
93206f32e7eSjoerg         }
93306f32e7eSjoerg       } else {
93406f32e7eSjoerg         // Thumb2 or ARM.
93506f32e7eSjoerg         if (isARM)
93606f32e7eSjoerg           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
93706f32e7eSjoerg               .addReg(FramePtr)
93806f32e7eSjoerg               .add(predOps(ARMCC::AL))
939*da58b97aSjoerg               .add(condCodeOp())
940*da58b97aSjoerg               .setMIFlag(MachineInstr::FrameDestroy);
94106f32e7eSjoerg         else
94206f32e7eSjoerg           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
94306f32e7eSjoerg               .addReg(FramePtr)
944*da58b97aSjoerg               .add(predOps(ARMCC::AL))
945*da58b97aSjoerg               .setMIFlag(MachineInstr::FrameDestroy);
94606f32e7eSjoerg       }
94706f32e7eSjoerg     } else if (NumBytes &&
94806f32e7eSjoerg                !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
949*da58b97aSjoerg       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
950*da58b97aSjoerg                    MachineInstr::FrameDestroy);
95106f32e7eSjoerg 
95206f32e7eSjoerg     // Increment past our save areas.
95306f32e7eSjoerg     if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
95406f32e7eSjoerg       MBBI++;
95506f32e7eSjoerg       // Since vpop register list cannot have gaps, there may be multiple vpop
95606f32e7eSjoerg       // instructions in the epilogue.
95706f32e7eSjoerg       while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
95806f32e7eSjoerg         MBBI++;
95906f32e7eSjoerg     }
96006f32e7eSjoerg     if (AFI->getDPRCalleeSavedGapSize()) {
96106f32e7eSjoerg       assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
96206f32e7eSjoerg              "unexpected DPR alignment gap");
963*da58b97aSjoerg       emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(),
964*da58b97aSjoerg                    MachineInstr::FrameDestroy);
96506f32e7eSjoerg     }
96606f32e7eSjoerg 
96706f32e7eSjoerg     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
96806f32e7eSjoerg     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
969*da58b97aSjoerg     if (AFI->getFPCXTSaveAreaSize()) MBBI++;
97006f32e7eSjoerg   }
97106f32e7eSjoerg 
97206f32e7eSjoerg   if (ArgRegsSaveSize)
973*da58b97aSjoerg     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize,
974*da58b97aSjoerg                  MachineInstr::FrameDestroy);
97506f32e7eSjoerg }
97606f32e7eSjoerg 
97706f32e7eSjoerg /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
97806f32e7eSjoerg /// debug info.  It's the same as what we use for resolving the code-gen
97906f32e7eSjoerg /// references for now.  FIXME: This can go wrong when references are
98006f32e7eSjoerg /// SP-relative and simple call frames aren't used.
getFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg) const981*da58b97aSjoerg StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF,
982*da58b97aSjoerg                                                      int FI,
983*da58b97aSjoerg                                                      Register &FrameReg) const {
984*da58b97aSjoerg   return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0));
98506f32e7eSjoerg }
98606f32e7eSjoerg 
ResolveFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg,int SPAdj) const987*da58b97aSjoerg int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
988*da58b97aSjoerg                                                  int FI, Register &FrameReg,
98906f32e7eSjoerg                                                  int SPAdj) const {
99006f32e7eSjoerg   const MachineFrameInfo &MFI = MF.getFrameInfo();
99106f32e7eSjoerg   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
99206f32e7eSjoerg       MF.getSubtarget().getRegisterInfo());
99306f32e7eSjoerg   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
99406f32e7eSjoerg   int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
99506f32e7eSjoerg   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
99606f32e7eSjoerg   bool isFixed = MFI.isFixedObjectIndex(FI);
99706f32e7eSjoerg 
99806f32e7eSjoerg   FrameReg = ARM::SP;
99906f32e7eSjoerg   Offset += SPAdj;
100006f32e7eSjoerg 
100106f32e7eSjoerg   // SP can move around if there are allocas.  We may also lose track of SP
100206f32e7eSjoerg   // when emergency spilling inside a non-reserved call frame setup.
100306f32e7eSjoerg   bool hasMovingSP = !hasReservedCallFrame(MF);
100406f32e7eSjoerg 
100506f32e7eSjoerg   // When dynamically realigning the stack, use the frame pointer for
100606f32e7eSjoerg   // parameters, and the stack/base pointer for locals.
1007*da58b97aSjoerg   if (RegInfo->hasStackRealignment(MF)) {
100806f32e7eSjoerg     assert(hasFP(MF) && "dynamic stack realignment without a FP!");
100906f32e7eSjoerg     if (isFixed) {
101006f32e7eSjoerg       FrameReg = RegInfo->getFrameRegister(MF);
101106f32e7eSjoerg       Offset = FPOffset;
101206f32e7eSjoerg     } else if (hasMovingSP) {
101306f32e7eSjoerg       assert(RegInfo->hasBasePointer(MF) &&
101406f32e7eSjoerg              "VLAs and dynamic stack alignment, but missing base pointer!");
101506f32e7eSjoerg       FrameReg = RegInfo->getBaseRegister();
101606f32e7eSjoerg       Offset -= SPAdj;
101706f32e7eSjoerg     }
101806f32e7eSjoerg     return Offset;
101906f32e7eSjoerg   }
102006f32e7eSjoerg 
102106f32e7eSjoerg   // If there is a frame pointer, use it when we can.
102206f32e7eSjoerg   if (hasFP(MF) && AFI->hasStackFrame()) {
102306f32e7eSjoerg     // Use frame pointer to reference fixed objects. Use it for locals if
102406f32e7eSjoerg     // there are VLAs (and thus the SP isn't reliable as a base).
102506f32e7eSjoerg     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
102606f32e7eSjoerg       FrameReg = RegInfo->getFrameRegister(MF);
102706f32e7eSjoerg       return FPOffset;
102806f32e7eSjoerg     } else if (hasMovingSP) {
102906f32e7eSjoerg       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
103006f32e7eSjoerg       if (AFI->isThumb2Function()) {
103106f32e7eSjoerg         // Try to use the frame pointer if we can, else use the base pointer
103206f32e7eSjoerg         // since it's available. This is handy for the emergency spill slot, in
103306f32e7eSjoerg         // particular.
103406f32e7eSjoerg         if (FPOffset >= -255 && FPOffset < 0) {
103506f32e7eSjoerg           FrameReg = RegInfo->getFrameRegister(MF);
103606f32e7eSjoerg           return FPOffset;
103706f32e7eSjoerg         }
103806f32e7eSjoerg       }
103906f32e7eSjoerg     } else if (AFI->isThumbFunction()) {
104006f32e7eSjoerg       // Prefer SP to base pointer, if the offset is suitably aligned and in
104106f32e7eSjoerg       // range as the effective range of the immediate offset is bigger when
104206f32e7eSjoerg       // basing off SP.
104306f32e7eSjoerg       // Use  add <rd>, sp, #<imm8>
104406f32e7eSjoerg       //      ldr <rd>, [sp, #<imm8>]
104506f32e7eSjoerg       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
104606f32e7eSjoerg         return Offset;
104706f32e7eSjoerg       // In Thumb2 mode, the negative offset is very limited. Try to avoid
104806f32e7eSjoerg       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
104906f32e7eSjoerg       if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
105006f32e7eSjoerg         FrameReg = RegInfo->getFrameRegister(MF);
105106f32e7eSjoerg         return FPOffset;
105206f32e7eSjoerg       }
105306f32e7eSjoerg     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
105406f32e7eSjoerg       // Otherwise, use SP or FP, whichever is closer to the stack slot.
105506f32e7eSjoerg       FrameReg = RegInfo->getFrameRegister(MF);
105606f32e7eSjoerg       return FPOffset;
105706f32e7eSjoerg     }
105806f32e7eSjoerg   }
105906f32e7eSjoerg   // Use the base pointer if we have one.
106006f32e7eSjoerg   // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
106106f32e7eSjoerg   // That can happen if we forced a base pointer for a large call frame.
106206f32e7eSjoerg   if (RegInfo->hasBasePointer(MF)) {
106306f32e7eSjoerg     FrameReg = RegInfo->getBaseRegister();
106406f32e7eSjoerg     Offset -= SPAdj;
106506f32e7eSjoerg   }
106606f32e7eSjoerg   return Offset;
106706f32e7eSjoerg }
106806f32e7eSjoerg 
emitPushInst(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,ArrayRef<CalleeSavedInfo> CSI,unsigned StmOpc,unsigned StrOpc,bool NoGap,bool (* Func)(unsigned,bool),unsigned NumAlignedDPRCS2Regs,unsigned MIFlags) const106906f32e7eSjoerg void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
107006f32e7eSjoerg                                     MachineBasicBlock::iterator MI,
1071*da58b97aSjoerg                                     ArrayRef<CalleeSavedInfo> CSI,
107206f32e7eSjoerg                                     unsigned StmOpc, unsigned StrOpc,
1073*da58b97aSjoerg                                     bool NoGap, bool (*Func)(unsigned, bool),
107406f32e7eSjoerg                                     unsigned NumAlignedDPRCS2Regs,
107506f32e7eSjoerg                                     unsigned MIFlags) const {
107606f32e7eSjoerg   MachineFunction &MF = *MBB.getParent();
107706f32e7eSjoerg   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
107806f32e7eSjoerg   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
107906f32e7eSjoerg 
108006f32e7eSjoerg   DebugLoc DL;
108106f32e7eSjoerg 
108206f32e7eSjoerg   using RegAndKill = std::pair<unsigned, bool>;
108306f32e7eSjoerg 
108406f32e7eSjoerg   SmallVector<RegAndKill, 4> Regs;
108506f32e7eSjoerg   unsigned i = CSI.size();
108606f32e7eSjoerg   while (i != 0) {
108706f32e7eSjoerg     unsigned LastReg = 0;
108806f32e7eSjoerg     for (; i != 0; --i) {
108906f32e7eSjoerg       unsigned Reg = CSI[i-1].getReg();
109006f32e7eSjoerg       if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
109106f32e7eSjoerg 
109206f32e7eSjoerg       // D-registers in the aligned area DPRCS2 are NOT spilled here.
109306f32e7eSjoerg       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
109406f32e7eSjoerg         continue;
109506f32e7eSjoerg 
109606f32e7eSjoerg       const MachineRegisterInfo &MRI = MF.getRegInfo();
109706f32e7eSjoerg       bool isLiveIn = MRI.isLiveIn(Reg);
109806f32e7eSjoerg       if (!isLiveIn && !MRI.isReserved(Reg))
109906f32e7eSjoerg         MBB.addLiveIn(Reg);
110006f32e7eSjoerg       // If NoGap is true, push consecutive registers and then leave the rest
110106f32e7eSjoerg       // for other instructions. e.g.
110206f32e7eSjoerg       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
110306f32e7eSjoerg       if (NoGap && LastReg && LastReg != Reg-1)
110406f32e7eSjoerg         break;
110506f32e7eSjoerg       LastReg = Reg;
110606f32e7eSjoerg       // Do not set a kill flag on values that are also marked as live-in. This
110706f32e7eSjoerg       // happens with the @llvm-returnaddress intrinsic and with arguments
110806f32e7eSjoerg       // passed in callee saved registers.
110906f32e7eSjoerg       // Omitting the kill flags is conservatively correct even if the live-in
111006f32e7eSjoerg       // is not used after all.
111106f32e7eSjoerg       Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
111206f32e7eSjoerg     }
111306f32e7eSjoerg 
111406f32e7eSjoerg     if (Regs.empty())
111506f32e7eSjoerg       continue;
111606f32e7eSjoerg 
111706f32e7eSjoerg     llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
111806f32e7eSjoerg       return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
111906f32e7eSjoerg     });
112006f32e7eSjoerg 
112106f32e7eSjoerg     if (Regs.size() > 1 || StrOpc== 0) {
112206f32e7eSjoerg       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
112306f32e7eSjoerg                                     .addReg(ARM::SP)
112406f32e7eSjoerg                                     .setMIFlags(MIFlags)
112506f32e7eSjoerg                                     .add(predOps(ARMCC::AL));
112606f32e7eSjoerg       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
112706f32e7eSjoerg         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
112806f32e7eSjoerg     } else if (Regs.size() == 1) {
112906f32e7eSjoerg       BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
113006f32e7eSjoerg           .addReg(Regs[0].first, getKillRegState(Regs[0].second))
113106f32e7eSjoerg           .addReg(ARM::SP)
113206f32e7eSjoerg           .setMIFlags(MIFlags)
113306f32e7eSjoerg           .addImm(-4)
113406f32e7eSjoerg           .add(predOps(ARMCC::AL));
113506f32e7eSjoerg     }
113606f32e7eSjoerg     Regs.clear();
113706f32e7eSjoerg 
113806f32e7eSjoerg     // Put any subsequent vpush instructions before this one: they will refer to
113906f32e7eSjoerg     // higher register numbers so need to be pushed first in order to preserve
114006f32e7eSjoerg     // monotonicity.
114106f32e7eSjoerg     if (MI != MBB.begin())
114206f32e7eSjoerg       --MI;
114306f32e7eSjoerg   }
114406f32e7eSjoerg }
114506f32e7eSjoerg 
emitPopInst(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,MutableArrayRef<CalleeSavedInfo> CSI,unsigned LdmOpc,unsigned LdrOpc,bool isVarArg,bool NoGap,bool (* Func)(unsigned,bool),unsigned NumAlignedDPRCS2Regs) const114606f32e7eSjoerg void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
114706f32e7eSjoerg                                    MachineBasicBlock::iterator MI,
1148*da58b97aSjoerg                                    MutableArrayRef<CalleeSavedInfo> CSI,
114906f32e7eSjoerg                                    unsigned LdmOpc, unsigned LdrOpc,
115006f32e7eSjoerg                                    bool isVarArg, bool NoGap,
115106f32e7eSjoerg                                    bool (*Func)(unsigned, bool),
115206f32e7eSjoerg                                    unsigned NumAlignedDPRCS2Regs) const {
115306f32e7eSjoerg   MachineFunction &MF = *MBB.getParent();
115406f32e7eSjoerg   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
115506f32e7eSjoerg   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
115606f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
115706f32e7eSjoerg   DebugLoc DL;
115806f32e7eSjoerg   bool isTailCall = false;
115906f32e7eSjoerg   bool isInterrupt = false;
116006f32e7eSjoerg   bool isTrap = false;
1161*da58b97aSjoerg   bool isCmseEntry = false;
116206f32e7eSjoerg   if (MBB.end() != MI) {
116306f32e7eSjoerg     DL = MI->getDebugLoc();
116406f32e7eSjoerg     unsigned RetOpcode = MI->getOpcode();
116506f32e7eSjoerg     isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
116606f32e7eSjoerg     isInterrupt =
116706f32e7eSjoerg         RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
116806f32e7eSjoerg     isTrap =
116906f32e7eSjoerg         RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
117006f32e7eSjoerg         RetOpcode == ARM::tTRAP;
1171*da58b97aSjoerg     isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET);
117206f32e7eSjoerg   }
117306f32e7eSjoerg 
117406f32e7eSjoerg   SmallVector<unsigned, 4> Regs;
117506f32e7eSjoerg   unsigned i = CSI.size();
117606f32e7eSjoerg   while (i != 0) {
117706f32e7eSjoerg     unsigned LastReg = 0;
117806f32e7eSjoerg     bool DeleteRet = false;
117906f32e7eSjoerg     for (; i != 0; --i) {
118006f32e7eSjoerg       CalleeSavedInfo &Info = CSI[i-1];
118106f32e7eSjoerg       unsigned Reg = Info.getReg();
118206f32e7eSjoerg       if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
118306f32e7eSjoerg 
118406f32e7eSjoerg       // The aligned reloads from area DPRCS2 are not inserted here.
118506f32e7eSjoerg       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
118606f32e7eSjoerg         continue;
118706f32e7eSjoerg 
118806f32e7eSjoerg       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1189*da58b97aSjoerg           !isCmseEntry && !isTrap && STI.hasV5TOps()) {
119006f32e7eSjoerg         if (MBB.succ_empty()) {
119106f32e7eSjoerg           Reg = ARM::PC;
119206f32e7eSjoerg           // Fold the return instruction into the LDM.
119306f32e7eSjoerg           DeleteRet = true;
119406f32e7eSjoerg           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
119506f32e7eSjoerg           // We 'restore' LR into PC so it is not live out of the return block:
119606f32e7eSjoerg           // Clear Restored bit.
119706f32e7eSjoerg           Info.setRestored(false);
119806f32e7eSjoerg         } else
119906f32e7eSjoerg           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
120006f32e7eSjoerg       }
120106f32e7eSjoerg 
120206f32e7eSjoerg       // If NoGap is true, pop consecutive registers and then leave the rest
120306f32e7eSjoerg       // for other instructions. e.g.
120406f32e7eSjoerg       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
120506f32e7eSjoerg       if (NoGap && LastReg && LastReg != Reg-1)
120606f32e7eSjoerg         break;
120706f32e7eSjoerg 
120806f32e7eSjoerg       LastReg = Reg;
120906f32e7eSjoerg       Regs.push_back(Reg);
121006f32e7eSjoerg     }
121106f32e7eSjoerg 
121206f32e7eSjoerg     if (Regs.empty())
121306f32e7eSjoerg       continue;
121406f32e7eSjoerg 
121506f32e7eSjoerg     llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
121606f32e7eSjoerg       return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
121706f32e7eSjoerg     });
121806f32e7eSjoerg 
121906f32e7eSjoerg     if (Regs.size() > 1 || LdrOpc == 0) {
122006f32e7eSjoerg       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
122106f32e7eSjoerg                                     .addReg(ARM::SP)
1222*da58b97aSjoerg                                     .add(predOps(ARMCC::AL))
1223*da58b97aSjoerg                                     .setMIFlags(MachineInstr::FrameDestroy);
122406f32e7eSjoerg       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
122506f32e7eSjoerg         MIB.addReg(Regs[i], getDefRegState(true));
122606f32e7eSjoerg       if (DeleteRet) {
122706f32e7eSjoerg         if (MI != MBB.end()) {
122806f32e7eSjoerg           MIB.copyImplicitOps(*MI);
122906f32e7eSjoerg           MI->eraseFromParent();
123006f32e7eSjoerg         }
123106f32e7eSjoerg       }
123206f32e7eSjoerg       MI = MIB;
123306f32e7eSjoerg     } else if (Regs.size() == 1) {
123406f32e7eSjoerg       // If we adjusted the reg to PC from LR above, switch it back here. We
123506f32e7eSjoerg       // only do that for LDM.
123606f32e7eSjoerg       if (Regs[0] == ARM::PC)
123706f32e7eSjoerg         Regs[0] = ARM::LR;
123806f32e7eSjoerg       MachineInstrBuilder MIB =
123906f32e7eSjoerg         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
124006f32e7eSjoerg           .addReg(ARM::SP, RegState::Define)
1241*da58b97aSjoerg           .addReg(ARM::SP)
1242*da58b97aSjoerg           .setMIFlags(MachineInstr::FrameDestroy);
124306f32e7eSjoerg       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
124406f32e7eSjoerg       // that refactoring is complete (eventually).
124506f32e7eSjoerg       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
124606f32e7eSjoerg         MIB.addReg(0);
124706f32e7eSjoerg         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
124806f32e7eSjoerg       } else
124906f32e7eSjoerg         MIB.addImm(4);
125006f32e7eSjoerg       MIB.add(predOps(ARMCC::AL));
125106f32e7eSjoerg     }
125206f32e7eSjoerg     Regs.clear();
125306f32e7eSjoerg 
125406f32e7eSjoerg     // Put any subsequent vpop instructions after this one: they will refer to
125506f32e7eSjoerg     // higher register numbers so need to be popped afterwards.
125606f32e7eSjoerg     if (MI != MBB.end())
125706f32e7eSjoerg       ++MI;
125806f32e7eSjoerg   }
125906f32e7eSjoerg }
126006f32e7eSjoerg 
126106f32e7eSjoerg /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
126206f32e7eSjoerg /// starting from d8.  Also insert stack realignment code and leave the stack
126306f32e7eSjoerg /// pointer pointing to the d8 spill slot.
emitAlignedDPRCS2Spills(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned NumAlignedDPRCS2Regs,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI)126406f32e7eSjoerg static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
126506f32e7eSjoerg                                     MachineBasicBlock::iterator MI,
126606f32e7eSjoerg                                     unsigned NumAlignedDPRCS2Regs,
1267*da58b97aSjoerg                                     ArrayRef<CalleeSavedInfo> CSI,
126806f32e7eSjoerg                                     const TargetRegisterInfo *TRI) {
126906f32e7eSjoerg   MachineFunction &MF = *MBB.getParent();
127006f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
127106f32e7eSjoerg   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
127206f32e7eSjoerg   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
127306f32e7eSjoerg   MachineFrameInfo &MFI = MF.getFrameInfo();
127406f32e7eSjoerg 
127506f32e7eSjoerg   // Mark the D-register spill slots as properly aligned.  Since MFI computes
127606f32e7eSjoerg   // stack slot layout backwards, this can actually mean that the d-reg stack
127706f32e7eSjoerg   // slot offsets can be wrong. The offset for d8 will always be correct.
127806f32e7eSjoerg   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
127906f32e7eSjoerg     unsigned DNum = CSI[i].getReg() - ARM::D8;
128006f32e7eSjoerg     if (DNum > NumAlignedDPRCS2Regs - 1)
128106f32e7eSjoerg       continue;
128206f32e7eSjoerg     int FI = CSI[i].getFrameIdx();
128306f32e7eSjoerg     // The even-numbered registers will be 16-byte aligned, the odd-numbered
128406f32e7eSjoerg     // registers will be 8-byte aligned.
1285*da58b97aSjoerg     MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16));
128606f32e7eSjoerg 
128706f32e7eSjoerg     // The stack slot for D8 needs to be maximally aligned because this is
128806f32e7eSjoerg     // actually the point where we align the stack pointer.  MachineFrameInfo
128906f32e7eSjoerg     // computes all offsets relative to the incoming stack pointer which is a
129006f32e7eSjoerg     // bit weird when realigning the stack.  Any extra padding for this
129106f32e7eSjoerg     // over-alignment is not realized because the code inserted below adjusts
129206f32e7eSjoerg     // the stack pointer by numregs * 8 before aligning the stack pointer.
129306f32e7eSjoerg     if (DNum == 0)
1294*da58b97aSjoerg       MFI.setObjectAlignment(FI, MFI.getMaxAlign());
129506f32e7eSjoerg   }
129606f32e7eSjoerg 
129706f32e7eSjoerg   // Move the stack pointer to the d8 spill slot, and align it at the same
129806f32e7eSjoerg   // time. Leave the stack slot address in the scratch register r4.
129906f32e7eSjoerg   //
130006f32e7eSjoerg   //   sub r4, sp, #numregs * 8
130106f32e7eSjoerg   //   bic r4, r4, #align - 1
130206f32e7eSjoerg   //   mov sp, r4
130306f32e7eSjoerg   //
130406f32e7eSjoerg   bool isThumb = AFI->isThumbFunction();
130506f32e7eSjoerg   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
130606f32e7eSjoerg   AFI->setShouldRestoreSPFromFP(true);
130706f32e7eSjoerg 
130806f32e7eSjoerg   // sub r4, sp, #numregs * 8
130906f32e7eSjoerg   // The immediate is <= 64, so it doesn't need any special encoding.
131006f32e7eSjoerg   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
131106f32e7eSjoerg   BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
131206f32e7eSjoerg       .addReg(ARM::SP)
131306f32e7eSjoerg       .addImm(8 * NumAlignedDPRCS2Regs)
131406f32e7eSjoerg       .add(predOps(ARMCC::AL))
131506f32e7eSjoerg       .add(condCodeOp());
131606f32e7eSjoerg 
1317*da58b97aSjoerg   Align MaxAlign = MF.getFrameInfo().getMaxAlign();
131806f32e7eSjoerg   // We must set parameter MustBeSingleInstruction to true, since
131906f32e7eSjoerg   // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
132006f32e7eSjoerg   // stack alignment.  Luckily, this can always be done since all ARM
132106f32e7eSjoerg   // architecture versions that support Neon also support the BFC
132206f32e7eSjoerg   // instruction.
132306f32e7eSjoerg   emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
132406f32e7eSjoerg 
132506f32e7eSjoerg   // mov sp, r4
132606f32e7eSjoerg   // The stack pointer must be adjusted before spilling anything, otherwise
132706f32e7eSjoerg   // the stack slots could be clobbered by an interrupt handler.
132806f32e7eSjoerg   // Leave r4 live, it is used below.
132906f32e7eSjoerg   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
133006f32e7eSjoerg   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
133106f32e7eSjoerg                                 .addReg(ARM::R4)
133206f32e7eSjoerg                                 .add(predOps(ARMCC::AL));
133306f32e7eSjoerg   if (!isThumb)
133406f32e7eSjoerg     MIB.add(condCodeOp());
133506f32e7eSjoerg 
133606f32e7eSjoerg   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
133706f32e7eSjoerg   // r4 holds the stack slot address.
133806f32e7eSjoerg   unsigned NextReg = ARM::D8;
133906f32e7eSjoerg 
134006f32e7eSjoerg   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
134106f32e7eSjoerg   // The writeback is only needed when emitting two vst1.64 instructions.
134206f32e7eSjoerg   if (NumAlignedDPRCS2Regs >= 6) {
134306f32e7eSjoerg     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
134406f32e7eSjoerg                                                &ARM::QQPRRegClass);
134506f32e7eSjoerg     MBB.addLiveIn(SupReg);
134606f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
134706f32e7eSjoerg         .addReg(ARM::R4, RegState::Kill)
134806f32e7eSjoerg         .addImm(16)
134906f32e7eSjoerg         .addReg(NextReg)
135006f32e7eSjoerg         .addReg(SupReg, RegState::ImplicitKill)
135106f32e7eSjoerg         .add(predOps(ARMCC::AL));
135206f32e7eSjoerg     NextReg += 4;
135306f32e7eSjoerg     NumAlignedDPRCS2Regs -= 4;
135406f32e7eSjoerg   }
135506f32e7eSjoerg 
135606f32e7eSjoerg   // We won't modify r4 beyond this point.  It currently points to the next
135706f32e7eSjoerg   // register to be spilled.
135806f32e7eSjoerg   unsigned R4BaseReg = NextReg;
135906f32e7eSjoerg 
136006f32e7eSjoerg   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
136106f32e7eSjoerg   if (NumAlignedDPRCS2Regs >= 4) {
136206f32e7eSjoerg     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
136306f32e7eSjoerg                                                &ARM::QQPRRegClass);
136406f32e7eSjoerg     MBB.addLiveIn(SupReg);
136506f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
136606f32e7eSjoerg         .addReg(ARM::R4)
136706f32e7eSjoerg         .addImm(16)
136806f32e7eSjoerg         .addReg(NextReg)
136906f32e7eSjoerg         .addReg(SupReg, RegState::ImplicitKill)
137006f32e7eSjoerg         .add(predOps(ARMCC::AL));
137106f32e7eSjoerg     NextReg += 4;
137206f32e7eSjoerg     NumAlignedDPRCS2Regs -= 4;
137306f32e7eSjoerg   }
137406f32e7eSjoerg 
137506f32e7eSjoerg   // 16-byte aligned vst1.64 with 2 d-regs.
137606f32e7eSjoerg   if (NumAlignedDPRCS2Regs >= 2) {
137706f32e7eSjoerg     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
137806f32e7eSjoerg                                                &ARM::QPRRegClass);
137906f32e7eSjoerg     MBB.addLiveIn(SupReg);
138006f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
138106f32e7eSjoerg         .addReg(ARM::R4)
138206f32e7eSjoerg         .addImm(16)
138306f32e7eSjoerg         .addReg(SupReg)
138406f32e7eSjoerg         .add(predOps(ARMCC::AL));
138506f32e7eSjoerg     NextReg += 2;
138606f32e7eSjoerg     NumAlignedDPRCS2Regs -= 2;
138706f32e7eSjoerg   }
138806f32e7eSjoerg 
138906f32e7eSjoerg   // Finally, use a vanilla vstr.64 for the odd last register.
139006f32e7eSjoerg   if (NumAlignedDPRCS2Regs) {
139106f32e7eSjoerg     MBB.addLiveIn(NextReg);
139206f32e7eSjoerg     // vstr.64 uses addrmode5 which has an offset scale of 4.
139306f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
139406f32e7eSjoerg         .addReg(NextReg)
139506f32e7eSjoerg         .addReg(ARM::R4)
139606f32e7eSjoerg         .addImm((NextReg - R4BaseReg) * 2)
139706f32e7eSjoerg         .add(predOps(ARMCC::AL));
139806f32e7eSjoerg   }
139906f32e7eSjoerg 
140006f32e7eSjoerg   // The last spill instruction inserted should kill the scratch register r4.
140106f32e7eSjoerg   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
140206f32e7eSjoerg }
140306f32e7eSjoerg 
140406f32e7eSjoerg /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
140506f32e7eSjoerg /// iterator to the following instruction.
140606f32e7eSjoerg static MachineBasicBlock::iterator
skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,unsigned NumAlignedDPRCS2Regs)140706f32e7eSjoerg skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
140806f32e7eSjoerg                         unsigned NumAlignedDPRCS2Regs) {
140906f32e7eSjoerg   //   sub r4, sp, #numregs * 8
141006f32e7eSjoerg   //   bic r4, r4, #align - 1
141106f32e7eSjoerg   //   mov sp, r4
141206f32e7eSjoerg   ++MI; ++MI; ++MI;
141306f32e7eSjoerg   assert(MI->mayStore() && "Expecting spill instruction");
141406f32e7eSjoerg 
141506f32e7eSjoerg   // These switches all fall through.
141606f32e7eSjoerg   switch(NumAlignedDPRCS2Regs) {
141706f32e7eSjoerg   case 7:
141806f32e7eSjoerg     ++MI;
141906f32e7eSjoerg     assert(MI->mayStore() && "Expecting spill instruction");
142006f32e7eSjoerg     LLVM_FALLTHROUGH;
142106f32e7eSjoerg   default:
142206f32e7eSjoerg     ++MI;
142306f32e7eSjoerg     assert(MI->mayStore() && "Expecting spill instruction");
142406f32e7eSjoerg     LLVM_FALLTHROUGH;
142506f32e7eSjoerg   case 1:
142606f32e7eSjoerg   case 2:
142706f32e7eSjoerg   case 4:
142806f32e7eSjoerg     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
142906f32e7eSjoerg     ++MI;
143006f32e7eSjoerg   }
143106f32e7eSjoerg   return MI;
143206f32e7eSjoerg }
143306f32e7eSjoerg 
143406f32e7eSjoerg /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
143506f32e7eSjoerg /// starting from d8.  These instructions are assumed to execute while the
143606f32e7eSjoerg /// stack is still aligned, unlike the code inserted by emitPopInst.
emitAlignedDPRCS2Restores(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned NumAlignedDPRCS2Regs,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI)143706f32e7eSjoerg static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
143806f32e7eSjoerg                                       MachineBasicBlock::iterator MI,
143906f32e7eSjoerg                                       unsigned NumAlignedDPRCS2Regs,
1440*da58b97aSjoerg                                       ArrayRef<CalleeSavedInfo> CSI,
144106f32e7eSjoerg                                       const TargetRegisterInfo *TRI) {
144206f32e7eSjoerg   MachineFunction &MF = *MBB.getParent();
144306f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
144406f32e7eSjoerg   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
144506f32e7eSjoerg   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
144606f32e7eSjoerg 
144706f32e7eSjoerg   // Find the frame index assigned to d8.
144806f32e7eSjoerg   int D8SpillFI = 0;
144906f32e7eSjoerg   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
145006f32e7eSjoerg     if (CSI[i].getReg() == ARM::D8) {
145106f32e7eSjoerg       D8SpillFI = CSI[i].getFrameIdx();
145206f32e7eSjoerg       break;
145306f32e7eSjoerg     }
145406f32e7eSjoerg 
145506f32e7eSjoerg   // Materialize the address of the d8 spill slot into the scratch register r4.
145606f32e7eSjoerg   // This can be fairly complicated if the stack frame is large, so just use
145706f32e7eSjoerg   // the normal frame index elimination mechanism to do it.  This code runs as
145806f32e7eSjoerg   // the initial part of the epilog where the stack and base pointers haven't
145906f32e7eSjoerg   // been changed yet.
146006f32e7eSjoerg   bool isThumb = AFI->isThumbFunction();
146106f32e7eSjoerg   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
146206f32e7eSjoerg 
146306f32e7eSjoerg   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
146406f32e7eSjoerg   BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
146506f32e7eSjoerg       .addFrameIndex(D8SpillFI)
146606f32e7eSjoerg       .addImm(0)
146706f32e7eSjoerg       .add(predOps(ARMCC::AL))
146806f32e7eSjoerg       .add(condCodeOp());
146906f32e7eSjoerg 
147006f32e7eSjoerg   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
147106f32e7eSjoerg   unsigned NextReg = ARM::D8;
147206f32e7eSjoerg 
147306f32e7eSjoerg   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
147406f32e7eSjoerg   if (NumAlignedDPRCS2Regs >= 6) {
147506f32e7eSjoerg     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
147606f32e7eSjoerg                                                &ARM::QQPRRegClass);
147706f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
147806f32e7eSjoerg         .addReg(ARM::R4, RegState::Define)
147906f32e7eSjoerg         .addReg(ARM::R4, RegState::Kill)
148006f32e7eSjoerg         .addImm(16)
148106f32e7eSjoerg         .addReg(SupReg, RegState::ImplicitDefine)
148206f32e7eSjoerg         .add(predOps(ARMCC::AL));
148306f32e7eSjoerg     NextReg += 4;
148406f32e7eSjoerg     NumAlignedDPRCS2Regs -= 4;
148506f32e7eSjoerg   }
148606f32e7eSjoerg 
148706f32e7eSjoerg   // We won't modify r4 beyond this point.  It currently points to the next
148806f32e7eSjoerg   // register to be spilled.
148906f32e7eSjoerg   unsigned R4BaseReg = NextReg;
149006f32e7eSjoerg 
149106f32e7eSjoerg   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
149206f32e7eSjoerg   if (NumAlignedDPRCS2Regs >= 4) {
149306f32e7eSjoerg     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
149406f32e7eSjoerg                                                &ARM::QQPRRegClass);
149506f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
149606f32e7eSjoerg         .addReg(ARM::R4)
149706f32e7eSjoerg         .addImm(16)
149806f32e7eSjoerg         .addReg(SupReg, RegState::ImplicitDefine)
149906f32e7eSjoerg         .add(predOps(ARMCC::AL));
150006f32e7eSjoerg     NextReg += 4;
150106f32e7eSjoerg     NumAlignedDPRCS2Regs -= 4;
150206f32e7eSjoerg   }
150306f32e7eSjoerg 
150406f32e7eSjoerg   // 16-byte aligned vld1.64 with 2 d-regs.
150506f32e7eSjoerg   if (NumAlignedDPRCS2Regs >= 2) {
150606f32e7eSjoerg     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
150706f32e7eSjoerg                                                &ARM::QPRRegClass);
150806f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
150906f32e7eSjoerg         .addReg(ARM::R4)
151006f32e7eSjoerg         .addImm(16)
151106f32e7eSjoerg         .add(predOps(ARMCC::AL));
151206f32e7eSjoerg     NextReg += 2;
151306f32e7eSjoerg     NumAlignedDPRCS2Regs -= 2;
151406f32e7eSjoerg   }
151506f32e7eSjoerg 
151606f32e7eSjoerg   // Finally, use a vanilla vldr.64 for the remaining odd register.
151706f32e7eSjoerg   if (NumAlignedDPRCS2Regs)
151806f32e7eSjoerg     BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
151906f32e7eSjoerg         .addReg(ARM::R4)
152006f32e7eSjoerg         .addImm(2 * (NextReg - R4BaseReg))
152106f32e7eSjoerg         .add(predOps(ARMCC::AL));
152206f32e7eSjoerg 
152306f32e7eSjoerg   // Last store kills r4.
152406f32e7eSjoerg   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
152506f32e7eSjoerg }
152606f32e7eSjoerg 
spillCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const1527*da58b97aSjoerg bool ARMFrameLowering::spillCalleeSavedRegisters(
1528*da58b97aSjoerg     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1529*da58b97aSjoerg     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
153006f32e7eSjoerg   if (CSI.empty())
153106f32e7eSjoerg     return false;
153206f32e7eSjoerg 
153306f32e7eSjoerg   MachineFunction &MF = *MBB.getParent();
153406f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
153506f32e7eSjoerg 
153606f32e7eSjoerg   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
153706f32e7eSjoerg   unsigned PushOneOpc = AFI->isThumbFunction() ?
153806f32e7eSjoerg     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
153906f32e7eSjoerg   unsigned FltOpc = ARM::VSTMDDB_UPD;
154006f32e7eSjoerg   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1541*da58b97aSjoerg   // Save the non-secure floating point context.
1542*da58b97aSjoerg   if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) {
1543*da58b97aSjoerg         return C.getReg() == ARM::FPCXTNS;
1544*da58b97aSjoerg       })) {
1545*da58b97aSjoerg     BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre),
1546*da58b97aSjoerg             ARM::SP)
1547*da58b97aSjoerg         .addReg(ARM::SP)
1548*da58b97aSjoerg         .addImm(-4)
1549*da58b97aSjoerg         .add(predOps(ARMCC::AL));
1550*da58b97aSjoerg   }
155106f32e7eSjoerg   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
155206f32e7eSjoerg                MachineInstr::FrameSetup);
155306f32e7eSjoerg   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
155406f32e7eSjoerg                MachineInstr::FrameSetup);
155506f32e7eSjoerg   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
155606f32e7eSjoerg                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
155706f32e7eSjoerg 
155806f32e7eSjoerg   // The code above does not insert spill code for the aligned DPRCS2 registers.
155906f32e7eSjoerg   // The stack realignment code will be inserted between the push instructions
156006f32e7eSjoerg   // and these spills.
156106f32e7eSjoerg   if (NumAlignedDPRCS2Regs)
156206f32e7eSjoerg     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
156306f32e7eSjoerg 
156406f32e7eSjoerg   return true;
156506f32e7eSjoerg }
156606f32e7eSjoerg 
restoreCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,MutableArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const1567*da58b97aSjoerg bool ARMFrameLowering::restoreCalleeSavedRegisters(
1568*da58b97aSjoerg     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1569*da58b97aSjoerg     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
157006f32e7eSjoerg   if (CSI.empty())
157106f32e7eSjoerg     return false;
157206f32e7eSjoerg 
157306f32e7eSjoerg   MachineFunction &MF = *MBB.getParent();
157406f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
157506f32e7eSjoerg   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
157606f32e7eSjoerg   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
157706f32e7eSjoerg 
157806f32e7eSjoerg   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
157906f32e7eSjoerg   // registers. Do that here instead.
158006f32e7eSjoerg   if (NumAlignedDPRCS2Regs)
158106f32e7eSjoerg     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
158206f32e7eSjoerg 
158306f32e7eSjoerg   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
158406f32e7eSjoerg   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
158506f32e7eSjoerg   unsigned FltOpc = ARM::VLDMDIA_UPD;
158606f32e7eSjoerg   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
158706f32e7eSjoerg               NumAlignedDPRCS2Regs);
158806f32e7eSjoerg   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
158906f32e7eSjoerg               &isARMArea2Register, 0);
159006f32e7eSjoerg   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
159106f32e7eSjoerg               &isARMArea1Register, 0);
159206f32e7eSjoerg 
159306f32e7eSjoerg   return true;
159406f32e7eSjoerg }
159506f32e7eSjoerg 
159606f32e7eSjoerg // FIXME: Make generic?
EstimateFunctionSizeInBytes(const MachineFunction & MF,const ARMBaseInstrInfo & TII)159706f32e7eSjoerg static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
159806f32e7eSjoerg                                             const ARMBaseInstrInfo &TII) {
159906f32e7eSjoerg   unsigned FnSize = 0;
160006f32e7eSjoerg   for (auto &MBB : MF) {
160106f32e7eSjoerg     for (auto &MI : MBB)
160206f32e7eSjoerg       FnSize += TII.getInstSizeInBytes(MI);
160306f32e7eSjoerg   }
160406f32e7eSjoerg   if (MF.getJumpTableInfo())
160506f32e7eSjoerg     for (auto &Table: MF.getJumpTableInfo()->getJumpTables())
160606f32e7eSjoerg       FnSize += Table.MBBs.size() * 4;
160706f32e7eSjoerg   FnSize += MF.getConstantPool()->getConstants().size() * 4;
160806f32e7eSjoerg   return FnSize;
160906f32e7eSjoerg }
161006f32e7eSjoerg 
161106f32e7eSjoerg /// estimateRSStackSizeLimit - Look at each instruction that references stack
161206f32e7eSjoerg /// frames and return the stack size limit beyond which some of these
161306f32e7eSjoerg /// instructions will require a scratch register during their expansion later.
161406f32e7eSjoerg // FIXME: Move to TII?
estimateRSStackSizeLimit(MachineFunction & MF,const TargetFrameLowering * TFI,bool & HasNonSPFrameIndex)161506f32e7eSjoerg static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
161606f32e7eSjoerg                                          const TargetFrameLowering *TFI,
161706f32e7eSjoerg                                          bool &HasNonSPFrameIndex) {
161806f32e7eSjoerg   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
161906f32e7eSjoerg   const ARMBaseInstrInfo &TII =
162006f32e7eSjoerg       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
162106f32e7eSjoerg   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
162206f32e7eSjoerg   unsigned Limit = (1 << 12) - 1;
162306f32e7eSjoerg   for (auto &MBB : MF) {
162406f32e7eSjoerg     for (auto &MI : MBB) {
162506f32e7eSjoerg       if (MI.isDebugInstr())
162606f32e7eSjoerg         continue;
162706f32e7eSjoerg       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
162806f32e7eSjoerg         if (!MI.getOperand(i).isFI())
162906f32e7eSjoerg           continue;
163006f32e7eSjoerg 
163106f32e7eSjoerg         // When using ADDri to get the address of a stack object, 255 is the
163206f32e7eSjoerg         // largest offset guaranteed to fit in the immediate offset.
163306f32e7eSjoerg         if (MI.getOpcode() == ARM::ADDri) {
163406f32e7eSjoerg           Limit = std::min(Limit, (1U << 8) - 1);
163506f32e7eSjoerg           break;
163606f32e7eSjoerg         }
163706f32e7eSjoerg         // t2ADDri will not require an extra register, it can reuse the
163806f32e7eSjoerg         // destination.
163906f32e7eSjoerg         if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
164006f32e7eSjoerg           break;
164106f32e7eSjoerg 
164206f32e7eSjoerg         const MCInstrDesc &MCID = MI.getDesc();
164306f32e7eSjoerg         const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF);
164406f32e7eSjoerg         if (RegClass && !RegClass->contains(ARM::SP))
164506f32e7eSjoerg           HasNonSPFrameIndex = true;
164606f32e7eSjoerg 
164706f32e7eSjoerg         // Otherwise check the addressing mode.
164806f32e7eSjoerg         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
164906f32e7eSjoerg         case ARMII::AddrMode_i12:
165006f32e7eSjoerg         case ARMII::AddrMode2:
165106f32e7eSjoerg           // Default 12 bit limit.
165206f32e7eSjoerg           break;
165306f32e7eSjoerg         case ARMII::AddrMode3:
165406f32e7eSjoerg         case ARMII::AddrModeT2_i8:
165506f32e7eSjoerg           Limit = std::min(Limit, (1U << 8) - 1);
165606f32e7eSjoerg           break;
165706f32e7eSjoerg         case ARMII::AddrMode5FP16:
165806f32e7eSjoerg           Limit = std::min(Limit, ((1U << 8) - 1) * 2);
165906f32e7eSjoerg           break;
166006f32e7eSjoerg         case ARMII::AddrMode5:
166106f32e7eSjoerg         case ARMII::AddrModeT2_i8s4:
166206f32e7eSjoerg         case ARMII::AddrModeT2_ldrex:
166306f32e7eSjoerg           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
166406f32e7eSjoerg           break;
166506f32e7eSjoerg         case ARMII::AddrModeT2_i12:
166606f32e7eSjoerg           // i12 supports only positive offset so these will be converted to
166706f32e7eSjoerg           // i8 opcodes. See llvm::rewriteT2FrameIndex.
166806f32e7eSjoerg           if (TFI->hasFP(MF) && AFI->hasStackFrame())
166906f32e7eSjoerg             Limit = std::min(Limit, (1U << 8) - 1);
167006f32e7eSjoerg           break;
167106f32e7eSjoerg         case ARMII::AddrMode4:
167206f32e7eSjoerg         case ARMII::AddrMode6:
167306f32e7eSjoerg           // Addressing modes 4 & 6 (load/store) instructions can't encode an
167406f32e7eSjoerg           // immediate offset for stack references.
167506f32e7eSjoerg           return 0;
167606f32e7eSjoerg         case ARMII::AddrModeT2_i7:
167706f32e7eSjoerg           Limit = std::min(Limit, ((1U << 7) - 1) * 1);
167806f32e7eSjoerg           break;
167906f32e7eSjoerg         case ARMII::AddrModeT2_i7s2:
168006f32e7eSjoerg           Limit = std::min(Limit, ((1U << 7) - 1) * 2);
168106f32e7eSjoerg           break;
168206f32e7eSjoerg         case ARMII::AddrModeT2_i7s4:
168306f32e7eSjoerg           Limit = std::min(Limit, ((1U << 7) - 1) * 4);
168406f32e7eSjoerg           break;
168506f32e7eSjoerg         default:
168606f32e7eSjoerg           llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
168706f32e7eSjoerg         }
168806f32e7eSjoerg         break; // At most one FI per instruction
168906f32e7eSjoerg       }
169006f32e7eSjoerg     }
169106f32e7eSjoerg   }
169206f32e7eSjoerg 
169306f32e7eSjoerg   return Limit;
169406f32e7eSjoerg }
169506f32e7eSjoerg 
169606f32e7eSjoerg // In functions that realign the stack, it can be an advantage to spill the
169706f32e7eSjoerg // callee-saved vector registers after realigning the stack. The vst1 and vld1
169806f32e7eSjoerg // instructions take alignment hints that can improve performance.
169906f32e7eSjoerg static void
checkNumAlignedDPRCS2Regs(MachineFunction & MF,BitVector & SavedRegs)170006f32e7eSjoerg checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
170106f32e7eSjoerg   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
170206f32e7eSjoerg   if (!SpillAlignedNEONRegs)
170306f32e7eSjoerg     return;
170406f32e7eSjoerg 
170506f32e7eSjoerg   // Naked functions don't spill callee-saved registers.
170606f32e7eSjoerg   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
170706f32e7eSjoerg     return;
170806f32e7eSjoerg 
170906f32e7eSjoerg   // We are planning to use NEON instructions vst1 / vld1.
171006f32e7eSjoerg   if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
171106f32e7eSjoerg     return;
171206f32e7eSjoerg 
171306f32e7eSjoerg   // Don't bother if the default stack alignment is sufficiently high.
1714*da58b97aSjoerg   if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8))
171506f32e7eSjoerg     return;
171606f32e7eSjoerg 
171706f32e7eSjoerg   // Aligned spills require stack realignment.
171806f32e7eSjoerg   if (!static_cast<const ARMBaseRegisterInfo *>(
171906f32e7eSjoerg            MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
172006f32e7eSjoerg     return;
172106f32e7eSjoerg 
172206f32e7eSjoerg   // We always spill contiguous d-registers starting from d8. Count how many
172306f32e7eSjoerg   // needs spilling.  The register allocator will almost always use the
172406f32e7eSjoerg   // callee-saved registers in order, but it can happen that there are holes in
172506f32e7eSjoerg   // the range.  Registers above the hole will be spilled to the standard DPRCS
172606f32e7eSjoerg   // area.
172706f32e7eSjoerg   unsigned NumSpills = 0;
172806f32e7eSjoerg   for (; NumSpills < 8; ++NumSpills)
172906f32e7eSjoerg     if (!SavedRegs.test(ARM::D8 + NumSpills))
173006f32e7eSjoerg       break;
173106f32e7eSjoerg 
173206f32e7eSjoerg   // Don't do this for just one d-register. It's not worth it.
173306f32e7eSjoerg   if (NumSpills < 2)
173406f32e7eSjoerg     return;
173506f32e7eSjoerg 
173606f32e7eSjoerg   // Spill the first NumSpills D-registers after realigning the stack.
173706f32e7eSjoerg   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
173806f32e7eSjoerg 
173906f32e7eSjoerg   // A scratch register is required for the vst1 / vld1 instructions.
174006f32e7eSjoerg   SavedRegs.set(ARM::R4);
174106f32e7eSjoerg }
174206f32e7eSjoerg 
enableShrinkWrapping(const MachineFunction & MF) const1743*da58b97aSjoerg bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1744*da58b97aSjoerg   // For CMSE entry functions, we want to save the FPCXT_NS immediately
1745*da58b97aSjoerg   // upon function entry (resp. restore it immmediately before return)
1746*da58b97aSjoerg   if (STI.hasV8_1MMainlineOps() &&
1747*da58b97aSjoerg       MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction())
1748*da58b97aSjoerg     return false;
1749*da58b97aSjoerg 
1750*da58b97aSjoerg   return true;
1751*da58b97aSjoerg }
1752*da58b97aSjoerg 
determineCalleeSaves(MachineFunction & MF,BitVector & SavedRegs,RegScavenger * RS) const175306f32e7eSjoerg void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
175406f32e7eSjoerg                                             BitVector &SavedRegs,
175506f32e7eSjoerg                                             RegScavenger *RS) const {
175606f32e7eSjoerg   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
175706f32e7eSjoerg   // This tells PEI to spill the FP as if it is any other callee-save register
175806f32e7eSjoerg   // to take advantage the eliminateFrameIndex machinery. This also ensures it
175906f32e7eSjoerg   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
176006f32e7eSjoerg   // to combine multiple loads / stores.
176106f32e7eSjoerg   bool CanEliminateFrame = true;
176206f32e7eSjoerg   bool CS1Spilled = false;
176306f32e7eSjoerg   bool LRSpilled = false;
176406f32e7eSjoerg   unsigned NumGPRSpills = 0;
176506f32e7eSjoerg   unsigned NumFPRSpills = 0;
176606f32e7eSjoerg   SmallVector<unsigned, 4> UnspilledCS1GPRs;
176706f32e7eSjoerg   SmallVector<unsigned, 4> UnspilledCS2GPRs;
176806f32e7eSjoerg   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
176906f32e7eSjoerg       MF.getSubtarget().getRegisterInfo());
177006f32e7eSjoerg   const ARMBaseInstrInfo &TII =
177106f32e7eSjoerg       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
177206f32e7eSjoerg   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
177306f32e7eSjoerg   MachineFrameInfo &MFI = MF.getFrameInfo();
177406f32e7eSjoerg   MachineRegisterInfo &MRI = MF.getRegInfo();
177506f32e7eSjoerg   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
177606f32e7eSjoerg   (void)TRI;  // Silence unused warning in non-assert builds.
177706f32e7eSjoerg   Register FramePtr = RegInfo->getFrameRegister(MF);
177806f32e7eSjoerg 
177906f32e7eSjoerg   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
178006f32e7eSjoerg   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
178106f32e7eSjoerg   // since it's not always possible to restore sp from fp in a single
178206f32e7eSjoerg   // instruction.
178306f32e7eSjoerg   // FIXME: It will be better just to find spare register here.
178406f32e7eSjoerg   if (AFI->isThumb2Function() &&
1785*da58b97aSjoerg       (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)))
178606f32e7eSjoerg     SavedRegs.set(ARM::R4);
178706f32e7eSjoerg 
178806f32e7eSjoerg   // If a stack probe will be emitted, spill R4 and LR, since they are
178906f32e7eSjoerg   // clobbered by the stack probe call.
179006f32e7eSjoerg   // This estimate should be a safe, conservative estimate. The actual
179106f32e7eSjoerg   // stack probe is enabled based on the size of the local objects;
179206f32e7eSjoerg   // this estimate also includes the varargs store size.
179306f32e7eSjoerg   if (STI.isTargetWindows() &&
179406f32e7eSjoerg       WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
179506f32e7eSjoerg     SavedRegs.set(ARM::R4);
179606f32e7eSjoerg     SavedRegs.set(ARM::LR);
179706f32e7eSjoerg   }
179806f32e7eSjoerg 
179906f32e7eSjoerg   if (AFI->isThumb1OnlyFunction()) {
180006f32e7eSjoerg     // Spill LR if Thumb1 function uses variable length argument lists.
180106f32e7eSjoerg     if (AFI->getArgRegsSaveSize() > 0)
180206f32e7eSjoerg       SavedRegs.set(ARM::LR);
180306f32e7eSjoerg 
180406f32e7eSjoerg     // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
180506f32e7eSjoerg     // requires stack alignment.  We don't know for sure what the stack size
180606f32e7eSjoerg     // will be, but for this, an estimate is good enough. If there anything
180706f32e7eSjoerg     // changes it, it'll be a spill, which implies we've used all the registers
180806f32e7eSjoerg     // and so R4 is already used, so not marking it here will be OK.
180906f32e7eSjoerg     // FIXME: It will be better just to find spare register here.
1810*da58b97aSjoerg     if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) ||
181106f32e7eSjoerg         MFI.estimateStackSize(MF) > 508)
181206f32e7eSjoerg       SavedRegs.set(ARM::R4);
181306f32e7eSjoerg   }
181406f32e7eSjoerg 
181506f32e7eSjoerg   // See if we can spill vector registers to aligned stack.
181606f32e7eSjoerg   checkNumAlignedDPRCS2Regs(MF, SavedRegs);
181706f32e7eSjoerg 
181806f32e7eSjoerg   // Spill the BasePtr if it's used.
181906f32e7eSjoerg   if (RegInfo->hasBasePointer(MF))
182006f32e7eSjoerg     SavedRegs.set(RegInfo->getBaseRegister());
182106f32e7eSjoerg 
1822*da58b97aSjoerg   // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
1823*da58b97aSjoerg   if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
1824*da58b97aSjoerg     CanEliminateFrame = false;
1825*da58b97aSjoerg 
182606f32e7eSjoerg   // Don't spill FP if the frame can be eliminated. This is determined
182706f32e7eSjoerg   // by scanning the callee-save registers to see if any is modified.
182806f32e7eSjoerg   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
182906f32e7eSjoerg   for (unsigned i = 0; CSRegs[i]; ++i) {
183006f32e7eSjoerg     unsigned Reg = CSRegs[i];
183106f32e7eSjoerg     bool Spilled = false;
183206f32e7eSjoerg     if (SavedRegs.test(Reg)) {
183306f32e7eSjoerg       Spilled = true;
183406f32e7eSjoerg       CanEliminateFrame = false;
183506f32e7eSjoerg     }
183606f32e7eSjoerg 
183706f32e7eSjoerg     if (!ARM::GPRRegClass.contains(Reg)) {
183806f32e7eSjoerg       if (Spilled) {
183906f32e7eSjoerg         if (ARM::SPRRegClass.contains(Reg))
184006f32e7eSjoerg           NumFPRSpills++;
184106f32e7eSjoerg         else if (ARM::DPRRegClass.contains(Reg))
184206f32e7eSjoerg           NumFPRSpills += 2;
184306f32e7eSjoerg         else if (ARM::QPRRegClass.contains(Reg))
184406f32e7eSjoerg           NumFPRSpills += 4;
184506f32e7eSjoerg       }
184606f32e7eSjoerg       continue;
184706f32e7eSjoerg     }
184806f32e7eSjoerg 
184906f32e7eSjoerg     if (Spilled) {
185006f32e7eSjoerg       NumGPRSpills++;
185106f32e7eSjoerg 
185206f32e7eSjoerg       if (!STI.splitFramePushPop(MF)) {
185306f32e7eSjoerg         if (Reg == ARM::LR)
185406f32e7eSjoerg           LRSpilled = true;
185506f32e7eSjoerg         CS1Spilled = true;
185606f32e7eSjoerg         continue;
185706f32e7eSjoerg       }
185806f32e7eSjoerg 
185906f32e7eSjoerg       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
186006f32e7eSjoerg       switch (Reg) {
186106f32e7eSjoerg       case ARM::LR:
186206f32e7eSjoerg         LRSpilled = true;
186306f32e7eSjoerg         LLVM_FALLTHROUGH;
186406f32e7eSjoerg       case ARM::R0: case ARM::R1:
186506f32e7eSjoerg       case ARM::R2: case ARM::R3:
186606f32e7eSjoerg       case ARM::R4: case ARM::R5:
186706f32e7eSjoerg       case ARM::R6: case ARM::R7:
186806f32e7eSjoerg         CS1Spilled = true;
186906f32e7eSjoerg         break;
187006f32e7eSjoerg       default:
187106f32e7eSjoerg         break;
187206f32e7eSjoerg       }
187306f32e7eSjoerg     } else {
187406f32e7eSjoerg       if (!STI.splitFramePushPop(MF)) {
187506f32e7eSjoerg         UnspilledCS1GPRs.push_back(Reg);
187606f32e7eSjoerg         continue;
187706f32e7eSjoerg       }
187806f32e7eSjoerg 
187906f32e7eSjoerg       switch (Reg) {
188006f32e7eSjoerg       case ARM::R0: case ARM::R1:
188106f32e7eSjoerg       case ARM::R2: case ARM::R3:
188206f32e7eSjoerg       case ARM::R4: case ARM::R5:
188306f32e7eSjoerg       case ARM::R6: case ARM::R7:
188406f32e7eSjoerg       case ARM::LR:
188506f32e7eSjoerg         UnspilledCS1GPRs.push_back(Reg);
188606f32e7eSjoerg         break;
188706f32e7eSjoerg       default:
188806f32e7eSjoerg         UnspilledCS2GPRs.push_back(Reg);
188906f32e7eSjoerg         break;
189006f32e7eSjoerg       }
189106f32e7eSjoerg     }
189206f32e7eSjoerg   }
189306f32e7eSjoerg 
189406f32e7eSjoerg   bool ForceLRSpill = false;
189506f32e7eSjoerg   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
189606f32e7eSjoerg     unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII);
189706f32e7eSjoerg     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1898*da58b97aSjoerg     // use of BL to implement far jump.
189906f32e7eSjoerg     if (FnSize >= (1 << 11)) {
190006f32e7eSjoerg       CanEliminateFrame = false;
190106f32e7eSjoerg       ForceLRSpill = true;
190206f32e7eSjoerg     }
190306f32e7eSjoerg   }
190406f32e7eSjoerg 
190506f32e7eSjoerg   // If any of the stack slot references may be out of range of an immediate
190606f32e7eSjoerg   // offset, make sure a register (or a spill slot) is available for the
190706f32e7eSjoerg   // register scavenger. Note that if we're indexing off the frame pointer, the
190806f32e7eSjoerg   // effective stack size is 4 bytes larger since the FP points to the stack
190906f32e7eSjoerg   // slot of the previous FP. Also, if we have variable sized objects in the
191006f32e7eSjoerg   // function, stack slot references will often be negative, and some of
191106f32e7eSjoerg   // our instructions are positive-offset only, so conservatively consider
191206f32e7eSjoerg   // that case to want a spill slot (or register) as well. Similarly, if
191306f32e7eSjoerg   // the function adjusts the stack pointer during execution and the
191406f32e7eSjoerg   // adjustments aren't already part of our stack size estimate, our offset
191506f32e7eSjoerg   // calculations may be off, so be conservative.
191606f32e7eSjoerg   // FIXME: We could add logic to be more precise about negative offsets
191706f32e7eSjoerg   //        and which instructions will need a scratch register for them. Is it
191806f32e7eSjoerg   //        worth the effort and added fragility?
191906f32e7eSjoerg   unsigned EstimatedStackSize =
192006f32e7eSjoerg       MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
192106f32e7eSjoerg 
192206f32e7eSjoerg   // Determine biggest (positive) SP offset in MachineFrameInfo.
192306f32e7eSjoerg   int MaxFixedOffset = 0;
192406f32e7eSjoerg   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
192506f32e7eSjoerg     int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
192606f32e7eSjoerg     MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
192706f32e7eSjoerg   }
192806f32e7eSjoerg 
192906f32e7eSjoerg   bool HasFP = hasFP(MF);
193006f32e7eSjoerg   if (HasFP) {
193106f32e7eSjoerg     if (AFI->hasStackFrame())
193206f32e7eSjoerg       EstimatedStackSize += 4;
193306f32e7eSjoerg   } else {
193406f32e7eSjoerg     // If FP is not used, SP will be used to access arguments, so count the
193506f32e7eSjoerg     // size of arguments into the estimation.
193606f32e7eSjoerg     EstimatedStackSize += MaxFixedOffset;
193706f32e7eSjoerg   }
193806f32e7eSjoerg   EstimatedStackSize += 16; // For possible paddings.
193906f32e7eSjoerg 
194006f32e7eSjoerg   unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
194106f32e7eSjoerg   bool HasNonSPFrameIndex = false;
194206f32e7eSjoerg   if (AFI->isThumb1OnlyFunction()) {
194306f32e7eSjoerg     // For Thumb1, don't bother to iterate over the function. The only
194406f32e7eSjoerg     // instruction that requires an emergency spill slot is a store to a
194506f32e7eSjoerg     // frame index.
194606f32e7eSjoerg     //
194706f32e7eSjoerg     // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
194806f32e7eSjoerg     // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
194906f32e7eSjoerg     // a 5-bit unsigned immediate.
195006f32e7eSjoerg     //
195106f32e7eSjoerg     // We could try to check if the function actually contains a tSTRspi
195206f32e7eSjoerg     // that might need the spill slot, but it's not really important.
195306f32e7eSjoerg     // Functions with VLAs or extremely large call frames are rare, and
195406f32e7eSjoerg     // if a function is allocating more than 1KB of stack, an extra 4-byte
195506f32e7eSjoerg     // slot probably isn't relevant.
195606f32e7eSjoerg     if (RegInfo->hasBasePointer(MF))
195706f32e7eSjoerg       EstimatedRSStackSizeLimit = (1U << 5) * 4;
195806f32e7eSjoerg     else
195906f32e7eSjoerg       EstimatedRSStackSizeLimit = (1U << 8) * 4;
196006f32e7eSjoerg     EstimatedRSFixedSizeLimit = (1U << 5) * 4;
196106f32e7eSjoerg   } else {
196206f32e7eSjoerg     EstimatedRSStackSizeLimit =
196306f32e7eSjoerg         estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
196406f32e7eSjoerg     EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
196506f32e7eSjoerg   }
196606f32e7eSjoerg   // Final estimate of whether sp or bp-relative accesses might require
196706f32e7eSjoerg   // scavenging.
196806f32e7eSjoerg   bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
196906f32e7eSjoerg 
197006f32e7eSjoerg   // If the stack pointer moves and we don't have a base pointer, the
197106f32e7eSjoerg   // estimate logic doesn't work. The actual offsets might be larger when
197206f32e7eSjoerg   // we're constructing a call frame, or we might need to use negative
197306f32e7eSjoerg   // offsets from fp.
197406f32e7eSjoerg   bool HasMovingSP = MFI.hasVarSizedObjects() ||
197506f32e7eSjoerg     (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
197606f32e7eSjoerg   bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
197706f32e7eSjoerg 
197806f32e7eSjoerg   // If we have a frame pointer, we assume arguments will be accessed
197906f32e7eSjoerg   // relative to the frame pointer. Check whether fp-relative accesses to
198006f32e7eSjoerg   // arguments require scavenging.
198106f32e7eSjoerg   //
198206f32e7eSjoerg   // We could do slightly better on Thumb1; in some cases, an sp-relative
198306f32e7eSjoerg   // offset would be legal even though an fp-relative offset is not.
1984*da58b97aSjoerg   int MaxFPOffset = getMaxFPOffset(STI, *AFI);
198506f32e7eSjoerg   bool HasLargeArgumentList =
198606f32e7eSjoerg       HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
198706f32e7eSjoerg 
198806f32e7eSjoerg   bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
198906f32e7eSjoerg                          HasLargeArgumentList || HasNonSPFrameIndex;
199006f32e7eSjoerg   LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
199106f32e7eSjoerg                     << "; EstimatedStack: " << EstimatedStackSize
199206f32e7eSjoerg                     << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
199306f32e7eSjoerg                     << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
199406f32e7eSjoerg   if (BigFrameOffsets ||
199506f32e7eSjoerg       !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
199606f32e7eSjoerg     AFI->setHasStackFrame(true);
199706f32e7eSjoerg 
199806f32e7eSjoerg     if (HasFP) {
199906f32e7eSjoerg       SavedRegs.set(FramePtr);
200006f32e7eSjoerg       // If the frame pointer is required by the ABI, also spill LR so that we
200106f32e7eSjoerg       // emit a complete frame record.
200206f32e7eSjoerg       if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
200306f32e7eSjoerg         SavedRegs.set(ARM::LR);
200406f32e7eSjoerg         LRSpilled = true;
200506f32e7eSjoerg         NumGPRSpills++;
200606f32e7eSjoerg         auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
200706f32e7eSjoerg         if (LRPos != UnspilledCS1GPRs.end())
200806f32e7eSjoerg           UnspilledCS1GPRs.erase(LRPos);
200906f32e7eSjoerg       }
201006f32e7eSjoerg       auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
201106f32e7eSjoerg       if (FPPos != UnspilledCS1GPRs.end())
201206f32e7eSjoerg         UnspilledCS1GPRs.erase(FPPos);
201306f32e7eSjoerg       NumGPRSpills++;
201406f32e7eSjoerg       if (FramePtr == ARM::R7)
201506f32e7eSjoerg         CS1Spilled = true;
201606f32e7eSjoerg     }
201706f32e7eSjoerg 
201806f32e7eSjoerg     // This is true when we inserted a spill for a callee-save GPR which is
201906f32e7eSjoerg     // not otherwise used by the function. This guaranteees it is possible
202006f32e7eSjoerg     // to scavenge a register to hold the address of a stack slot. On Thumb1,
202106f32e7eSjoerg     // the register must be a valid operand to tSTRi, i.e. r4-r7. For other
202206f32e7eSjoerg     // subtargets, this is any GPR, i.e. r4-r11 or lr.
202306f32e7eSjoerg     //
202406f32e7eSjoerg     // If we don't insert a spill, we instead allocate an emergency spill
202506f32e7eSjoerg     // slot, which can be used by scavenging to spill an arbitrary register.
202606f32e7eSjoerg     //
202706f32e7eSjoerg     // We currently don't try to figure out whether any specific instruction
202806f32e7eSjoerg     // requires scavening an additional register.
202906f32e7eSjoerg     bool ExtraCSSpill = false;
203006f32e7eSjoerg 
203106f32e7eSjoerg     if (AFI->isThumb1OnlyFunction()) {
203206f32e7eSjoerg       // For Thumb1-only targets, we need some low registers when we save and
203306f32e7eSjoerg       // restore the high registers (which aren't allocatable, but could be
203406f32e7eSjoerg       // used by inline assembly) because the push/pop instructions can not
203506f32e7eSjoerg       // access high registers. If necessary, we might need to push more low
203606f32e7eSjoerg       // registers to ensure that there is at least one free that can be used
203706f32e7eSjoerg       // for the saving & restoring, and preferably we should ensure that as
203806f32e7eSjoerg       // many as are needed are available so that fewer push/pop instructions
203906f32e7eSjoerg       // are required.
204006f32e7eSjoerg 
204106f32e7eSjoerg       // Low registers which are not currently pushed, but could be (r4-r7).
204206f32e7eSjoerg       SmallVector<unsigned, 4> AvailableRegs;
204306f32e7eSjoerg 
204406f32e7eSjoerg       // Unused argument registers (r0-r3) can be clobbered in the prologue for
204506f32e7eSjoerg       // free.
204606f32e7eSjoerg       int EntryRegDeficit = 0;
204706f32e7eSjoerg       for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
204806f32e7eSjoerg         if (!MF.getRegInfo().isLiveIn(Reg)) {
204906f32e7eSjoerg           --EntryRegDeficit;
205006f32e7eSjoerg           LLVM_DEBUG(dbgs()
205106f32e7eSjoerg                      << printReg(Reg, TRI)
205206f32e7eSjoerg                      << " is unused argument register, EntryRegDeficit = "
205306f32e7eSjoerg                      << EntryRegDeficit << "\n");
205406f32e7eSjoerg         }
205506f32e7eSjoerg       }
205606f32e7eSjoerg 
205706f32e7eSjoerg       // Unused return registers can be clobbered in the epilogue for free.
205806f32e7eSjoerg       int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
205906f32e7eSjoerg       LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
206006f32e7eSjoerg                         << " return regs used, ExitRegDeficit = "
206106f32e7eSjoerg                         << ExitRegDeficit << "\n");
206206f32e7eSjoerg 
206306f32e7eSjoerg       int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
206406f32e7eSjoerg       LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
206506f32e7eSjoerg 
206606f32e7eSjoerg       // r4-r6 can be used in the prologue if they are pushed by the first push
206706f32e7eSjoerg       // instruction.
206806f32e7eSjoerg       for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
206906f32e7eSjoerg         if (SavedRegs.test(Reg)) {
207006f32e7eSjoerg           --RegDeficit;
207106f32e7eSjoerg           LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
207206f32e7eSjoerg                             << " is saved low register, RegDeficit = "
207306f32e7eSjoerg                             << RegDeficit << "\n");
207406f32e7eSjoerg         } else {
207506f32e7eSjoerg           AvailableRegs.push_back(Reg);
207606f32e7eSjoerg           LLVM_DEBUG(
207706f32e7eSjoerg               dbgs()
207806f32e7eSjoerg               << printReg(Reg, TRI)
207906f32e7eSjoerg               << " is non-saved low register, adding to AvailableRegs\n");
208006f32e7eSjoerg         }
208106f32e7eSjoerg       }
208206f32e7eSjoerg 
208306f32e7eSjoerg       // r7 can be used if it is not being used as the frame pointer.
208406f32e7eSjoerg       if (!HasFP) {
208506f32e7eSjoerg         if (SavedRegs.test(ARM::R7)) {
208606f32e7eSjoerg           --RegDeficit;
208706f32e7eSjoerg           LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
208806f32e7eSjoerg                             << RegDeficit << "\n");
208906f32e7eSjoerg         } else {
209006f32e7eSjoerg           AvailableRegs.push_back(ARM::R7);
209106f32e7eSjoerg           LLVM_DEBUG(
209206f32e7eSjoerg               dbgs()
209306f32e7eSjoerg               << "%r7 is non-saved low register, adding to AvailableRegs\n");
209406f32e7eSjoerg         }
209506f32e7eSjoerg       }
209606f32e7eSjoerg 
209706f32e7eSjoerg       // Each of r8-r11 needs to be copied to a low register, then pushed.
209806f32e7eSjoerg       for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
209906f32e7eSjoerg         if (SavedRegs.test(Reg)) {
210006f32e7eSjoerg           ++RegDeficit;
210106f32e7eSjoerg           LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
210206f32e7eSjoerg                             << " is saved high register, RegDeficit = "
210306f32e7eSjoerg                             << RegDeficit << "\n");
210406f32e7eSjoerg         }
210506f32e7eSjoerg       }
210606f32e7eSjoerg 
210706f32e7eSjoerg       // LR can only be used by PUSH, not POP, and can't be used at all if the
210806f32e7eSjoerg       // llvm.returnaddress intrinsic is used. This is only worth doing if we
210906f32e7eSjoerg       // are more limited at function entry than exit.
211006f32e7eSjoerg       if ((EntryRegDeficit > ExitRegDeficit) &&
211106f32e7eSjoerg           !(MF.getRegInfo().isLiveIn(ARM::LR) &&
211206f32e7eSjoerg             MF.getFrameInfo().isReturnAddressTaken())) {
211306f32e7eSjoerg         if (SavedRegs.test(ARM::LR)) {
211406f32e7eSjoerg           --RegDeficit;
211506f32e7eSjoerg           LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
211606f32e7eSjoerg                             << RegDeficit << "\n");
211706f32e7eSjoerg         } else {
211806f32e7eSjoerg           AvailableRegs.push_back(ARM::LR);
211906f32e7eSjoerg           LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
212006f32e7eSjoerg         }
212106f32e7eSjoerg       }
212206f32e7eSjoerg 
212306f32e7eSjoerg       // If there are more high registers that need pushing than low registers
212406f32e7eSjoerg       // available, push some more low registers so that we can use fewer push
212506f32e7eSjoerg       // instructions. This might not reduce RegDeficit all the way to zero,
212606f32e7eSjoerg       // because we can only guarantee that r4-r6 are available, but r8-r11 may
212706f32e7eSjoerg       // need saving.
212806f32e7eSjoerg       LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
212906f32e7eSjoerg       for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
213006f32e7eSjoerg         unsigned Reg = AvailableRegs.pop_back_val();
213106f32e7eSjoerg         LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
213206f32e7eSjoerg                           << " to make up reg deficit\n");
213306f32e7eSjoerg         SavedRegs.set(Reg);
213406f32e7eSjoerg         NumGPRSpills++;
213506f32e7eSjoerg         CS1Spilled = true;
213606f32e7eSjoerg         assert(!MRI.isReserved(Reg) && "Should not be reserved");
213706f32e7eSjoerg         if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
213806f32e7eSjoerg           ExtraCSSpill = true;
213906f32e7eSjoerg         UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
214006f32e7eSjoerg         if (Reg == ARM::LR)
214106f32e7eSjoerg           LRSpilled = true;
214206f32e7eSjoerg       }
214306f32e7eSjoerg       LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
214406f32e7eSjoerg                         << "\n");
214506f32e7eSjoerg     }
214606f32e7eSjoerg 
214706f32e7eSjoerg     // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
214806f32e7eSjoerg     // restore LR in that case.
214906f32e7eSjoerg     bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
215006f32e7eSjoerg 
215106f32e7eSjoerg     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
215206f32e7eSjoerg     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
215306f32e7eSjoerg     if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
215406f32e7eSjoerg       SavedRegs.set(ARM::LR);
215506f32e7eSjoerg       NumGPRSpills++;
215606f32e7eSjoerg       SmallVectorImpl<unsigned>::iterator LRPos;
215706f32e7eSjoerg       LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
215806f32e7eSjoerg       if (LRPos != UnspilledCS1GPRs.end())
215906f32e7eSjoerg         UnspilledCS1GPRs.erase(LRPos);
216006f32e7eSjoerg 
216106f32e7eSjoerg       ForceLRSpill = false;
216206f32e7eSjoerg       if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
216306f32e7eSjoerg           !AFI->isThumb1OnlyFunction())
216406f32e7eSjoerg         ExtraCSSpill = true;
216506f32e7eSjoerg     }
216606f32e7eSjoerg 
216706f32e7eSjoerg     // If stack and double are 8-byte aligned and we are spilling an odd number
216806f32e7eSjoerg     // of GPRs, spill one extra callee save GPR so we won't have to pad between
216906f32e7eSjoerg     // the integer and double callee save areas.
217006f32e7eSjoerg     LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
2171*da58b97aSjoerg     const Align TargetAlign = getStackAlign();
2172*da58b97aSjoerg     if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
217306f32e7eSjoerg       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
217406f32e7eSjoerg         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
217506f32e7eSjoerg           unsigned Reg = UnspilledCS1GPRs[i];
217606f32e7eSjoerg           // Don't spill high register if the function is thumb.  In the case of
217706f32e7eSjoerg           // Windows on ARM, accept R11 (frame pointer)
217806f32e7eSjoerg           if (!AFI->isThumbFunction() ||
217906f32e7eSjoerg               (STI.isTargetWindows() && Reg == ARM::R11) ||
218006f32e7eSjoerg               isARMLowRegister(Reg) ||
218106f32e7eSjoerg               (Reg == ARM::LR && !ExpensiveLRRestore)) {
218206f32e7eSjoerg             SavedRegs.set(Reg);
218306f32e7eSjoerg             LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
218406f32e7eSjoerg                               << " to make up alignment\n");
218506f32e7eSjoerg             if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
218606f32e7eSjoerg                 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
218706f32e7eSjoerg               ExtraCSSpill = true;
218806f32e7eSjoerg             break;
218906f32e7eSjoerg           }
219006f32e7eSjoerg         }
219106f32e7eSjoerg       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
219206f32e7eSjoerg         unsigned Reg = UnspilledCS2GPRs.front();
219306f32e7eSjoerg         SavedRegs.set(Reg);
219406f32e7eSjoerg         LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
219506f32e7eSjoerg                           << " to make up alignment\n");
219606f32e7eSjoerg         if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
219706f32e7eSjoerg           ExtraCSSpill = true;
219806f32e7eSjoerg       }
219906f32e7eSjoerg     }
220006f32e7eSjoerg 
220106f32e7eSjoerg     // Estimate if we might need to scavenge a register at some point in order
220206f32e7eSjoerg     // to materialize a stack offset. If so, either spill one additional
220306f32e7eSjoerg     // callee-saved register or reserve a special spill slot to facilitate
220406f32e7eSjoerg     // register scavenging. Thumb1 needs a spill slot for stack pointer
220506f32e7eSjoerg     // adjustments also, even when the frame itself is small.
220606f32e7eSjoerg     if (BigFrameOffsets && !ExtraCSSpill) {
220706f32e7eSjoerg       // If any non-reserved CS register isn't spilled, just spill one or two
220806f32e7eSjoerg       // extra. That should take care of it!
2209*da58b97aSjoerg       unsigned NumExtras = TargetAlign.value() / 4;
221006f32e7eSjoerg       SmallVector<unsigned, 2> Extras;
221106f32e7eSjoerg       while (NumExtras && !UnspilledCS1GPRs.empty()) {
2212*da58b97aSjoerg         unsigned Reg = UnspilledCS1GPRs.pop_back_val();
221306f32e7eSjoerg         if (!MRI.isReserved(Reg) &&
221406f32e7eSjoerg             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
221506f32e7eSjoerg           Extras.push_back(Reg);
221606f32e7eSjoerg           NumExtras--;
221706f32e7eSjoerg         }
221806f32e7eSjoerg       }
221906f32e7eSjoerg       // For non-Thumb1 functions, also check for hi-reg CS registers
222006f32e7eSjoerg       if (!AFI->isThumb1OnlyFunction()) {
222106f32e7eSjoerg         while (NumExtras && !UnspilledCS2GPRs.empty()) {
2222*da58b97aSjoerg           unsigned Reg = UnspilledCS2GPRs.pop_back_val();
222306f32e7eSjoerg           if (!MRI.isReserved(Reg)) {
222406f32e7eSjoerg             Extras.push_back(Reg);
222506f32e7eSjoerg             NumExtras--;
222606f32e7eSjoerg           }
222706f32e7eSjoerg         }
222806f32e7eSjoerg       }
222906f32e7eSjoerg       if (NumExtras == 0) {
223006f32e7eSjoerg         for (unsigned Reg : Extras) {
223106f32e7eSjoerg           SavedRegs.set(Reg);
223206f32e7eSjoerg           if (!MRI.isPhysRegUsed(Reg))
223306f32e7eSjoerg             ExtraCSSpill = true;
223406f32e7eSjoerg         }
223506f32e7eSjoerg       }
223606f32e7eSjoerg       if (!ExtraCSSpill && RS) {
223706f32e7eSjoerg         // Reserve a slot closest to SP or frame pointer.
223806f32e7eSjoerg         LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
223906f32e7eSjoerg         const TargetRegisterClass &RC = ARM::GPRRegClass;
224006f32e7eSjoerg         unsigned Size = TRI->getSpillSize(RC);
2241*da58b97aSjoerg         Align Alignment = TRI->getSpillAlign(RC);
2242*da58b97aSjoerg         RS->addScavengingFrameIndex(
2243*da58b97aSjoerg             MFI.CreateStackObject(Size, Alignment, false));
224406f32e7eSjoerg       }
224506f32e7eSjoerg     }
224606f32e7eSjoerg   }
224706f32e7eSjoerg 
2248*da58b97aSjoerg   if (ForceLRSpill)
224906f32e7eSjoerg     SavedRegs.set(ARM::LR);
225006f32e7eSjoerg   AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
225106f32e7eSjoerg }
225206f32e7eSjoerg 
getCalleeSaves(const MachineFunction & MF,BitVector & SavedRegs) const225306f32e7eSjoerg void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
225406f32e7eSjoerg                                       BitVector &SavedRegs) const {
225506f32e7eSjoerg   TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
225606f32e7eSjoerg 
225706f32e7eSjoerg   // If we have the "returned" parameter attribute which guarantees that we
225806f32e7eSjoerg   // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
225906f32e7eSjoerg   // record that fact for IPRA.
226006f32e7eSjoerg   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
226106f32e7eSjoerg   if (AFI->getPreservesR0())
226206f32e7eSjoerg     SavedRegs.set(ARM::R0);
226306f32e7eSjoerg }
226406f32e7eSjoerg 
assignCalleeSavedSpillSlots(MachineFunction & MF,const TargetRegisterInfo * TRI,std::vector<CalleeSavedInfo> & CSI) const2265*da58b97aSjoerg bool ARMFrameLowering::assignCalleeSavedSpillSlots(
2266*da58b97aSjoerg     MachineFunction &MF, const TargetRegisterInfo *TRI,
2267*da58b97aSjoerg     std::vector<CalleeSavedInfo> &CSI) const {
2268*da58b97aSjoerg   // For CMSE entry functions, handle floating-point context as if it was a
2269*da58b97aSjoerg   // callee-saved register.
2270*da58b97aSjoerg   if (STI.hasV8_1MMainlineOps() &&
2271*da58b97aSjoerg       MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) {
2272*da58b97aSjoerg     CSI.emplace_back(ARM::FPCXTNS);
2273*da58b97aSjoerg     CSI.back().setRestored(false);
2274*da58b97aSjoerg   }
2275*da58b97aSjoerg 
2276*da58b97aSjoerg   return false;
2277*da58b97aSjoerg }
2278*da58b97aSjoerg 
2279*da58b97aSjoerg const TargetFrameLowering::SpillSlot *
getCalleeSavedSpillSlots(unsigned & NumEntries) const2280*da58b97aSjoerg ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
2281*da58b97aSjoerg   static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}};
2282*da58b97aSjoerg   NumEntries = array_lengthof(FixedSpillOffsets);
2283*da58b97aSjoerg   return FixedSpillOffsets;
2284*da58b97aSjoerg }
2285*da58b97aSjoerg 
eliminateCallFramePseudoInstr(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const228606f32e7eSjoerg MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
228706f32e7eSjoerg     MachineFunction &MF, MachineBasicBlock &MBB,
228806f32e7eSjoerg     MachineBasicBlock::iterator I) const {
228906f32e7eSjoerg   const ARMBaseInstrInfo &TII =
229006f32e7eSjoerg       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
229106f32e7eSjoerg   if (!hasReservedCallFrame(MF)) {
229206f32e7eSjoerg     // If we have alloca, convert as follows:
229306f32e7eSjoerg     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
229406f32e7eSjoerg     // ADJCALLSTACKUP   -> add, sp, sp, amount
229506f32e7eSjoerg     MachineInstr &Old = *I;
229606f32e7eSjoerg     DebugLoc dl = Old.getDebugLoc();
229706f32e7eSjoerg     unsigned Amount = TII.getFrameSize(Old);
229806f32e7eSjoerg     if (Amount != 0) {
229906f32e7eSjoerg       // We need to keep the stack aligned properly.  To do this, we round the
230006f32e7eSjoerg       // amount of space needed for the outgoing arguments up to the next
230106f32e7eSjoerg       // alignment boundary.
230206f32e7eSjoerg       Amount = alignSPAdjust(Amount);
230306f32e7eSjoerg 
230406f32e7eSjoerg       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
230506f32e7eSjoerg       assert(!AFI->isThumb1OnlyFunction() &&
230606f32e7eSjoerg              "This eliminateCallFramePseudoInstr does not support Thumb1!");
230706f32e7eSjoerg       bool isARM = !AFI->isThumbFunction();
230806f32e7eSjoerg 
230906f32e7eSjoerg       // Replace the pseudo instruction with a new instruction...
231006f32e7eSjoerg       unsigned Opc = Old.getOpcode();
231106f32e7eSjoerg       int PIdx = Old.findFirstPredOperandIdx();
231206f32e7eSjoerg       ARMCC::CondCodes Pred =
231306f32e7eSjoerg           (PIdx == -1) ? ARMCC::AL
231406f32e7eSjoerg                        : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
231506f32e7eSjoerg       unsigned PredReg = TII.getFramePred(Old);
231606f32e7eSjoerg       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
231706f32e7eSjoerg         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
231806f32e7eSjoerg                      Pred, PredReg);
231906f32e7eSjoerg       } else {
232006f32e7eSjoerg         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
232106f32e7eSjoerg         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
232206f32e7eSjoerg                      Pred, PredReg);
232306f32e7eSjoerg       }
232406f32e7eSjoerg     }
232506f32e7eSjoerg   }
232606f32e7eSjoerg   return MBB.erase(I);
232706f32e7eSjoerg }
232806f32e7eSjoerg 
232906f32e7eSjoerg /// Get the minimum constant for ARM that is greater than or equal to the
233006f32e7eSjoerg /// argument. In ARM, constants can have any value that can be produced by
233106f32e7eSjoerg /// rotating an 8-bit value to the right by an even number of bits within a
233206f32e7eSjoerg /// 32-bit word.
alignToARMConstant(uint32_t Value)233306f32e7eSjoerg static uint32_t alignToARMConstant(uint32_t Value) {
233406f32e7eSjoerg   unsigned Shifted = 0;
233506f32e7eSjoerg 
233606f32e7eSjoerg   if (Value == 0)
233706f32e7eSjoerg       return 0;
233806f32e7eSjoerg 
233906f32e7eSjoerg   while (!(Value & 0xC0000000)) {
234006f32e7eSjoerg       Value = Value << 2;
234106f32e7eSjoerg       Shifted += 2;
234206f32e7eSjoerg   }
234306f32e7eSjoerg 
234406f32e7eSjoerg   bool Carry = (Value & 0x00FFFFFF);
234506f32e7eSjoerg   Value = ((Value & 0xFF000000) >> 24) + Carry;
234606f32e7eSjoerg 
234706f32e7eSjoerg   if (Value & 0x0000100)
234806f32e7eSjoerg       Value = Value & 0x000001FC;
234906f32e7eSjoerg 
235006f32e7eSjoerg   if (Shifted > 24)
235106f32e7eSjoerg       Value = Value >> (Shifted - 24);
235206f32e7eSjoerg   else
235306f32e7eSjoerg       Value = Value << (24 - Shifted);
235406f32e7eSjoerg 
235506f32e7eSjoerg   return Value;
235606f32e7eSjoerg }
235706f32e7eSjoerg 
235806f32e7eSjoerg // The stack limit in the TCB is set to this many bytes above the actual
235906f32e7eSjoerg // stack limit.
236006f32e7eSjoerg static const uint64_t kSplitStackAvailable = 256;
236106f32e7eSjoerg 
236206f32e7eSjoerg // Adjust the function prologue to enable split stacks. This currently only
236306f32e7eSjoerg // supports android and linux.
236406f32e7eSjoerg //
236506f32e7eSjoerg // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
236606f32e7eSjoerg // must be well defined in order to allow for consistent implementations of the
236706f32e7eSjoerg // __morestack helper function. The ABI is also not a normal ABI in that it
236806f32e7eSjoerg // doesn't follow the normal calling conventions because this allows the
236906f32e7eSjoerg // prologue of each function to be optimized further.
237006f32e7eSjoerg //
237106f32e7eSjoerg // Currently, the ABI looks like (when calling __morestack)
237206f32e7eSjoerg //
237306f32e7eSjoerg //  * r4 holds the minimum stack size requested for this function call
237406f32e7eSjoerg //  * r5 holds the stack size of the arguments to the function
237506f32e7eSjoerg //  * the beginning of the function is 3 instructions after the call to
237606f32e7eSjoerg //    __morestack
237706f32e7eSjoerg //
237806f32e7eSjoerg // Implementations of __morestack should use r4 to allocate a new stack, r5 to
237906f32e7eSjoerg // place the arguments on to the new stack, and the 3-instruction knowledge to
238006f32e7eSjoerg // jump directly to the body of the function when working on the new stack.
238106f32e7eSjoerg //
238206f32e7eSjoerg // An old (and possibly no longer compatible) implementation of __morestack for
238306f32e7eSjoerg // ARM can be found at [1].
238406f32e7eSjoerg //
238506f32e7eSjoerg // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
adjustForSegmentedStacks(MachineFunction & MF,MachineBasicBlock & PrologueMBB) const238606f32e7eSjoerg void ARMFrameLowering::adjustForSegmentedStacks(
238706f32e7eSjoerg     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
238806f32e7eSjoerg   unsigned Opcode;
238906f32e7eSjoerg   unsigned CFIIndex;
239006f32e7eSjoerg   const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
239106f32e7eSjoerg   bool Thumb = ST->isThumb();
239206f32e7eSjoerg 
239306f32e7eSjoerg   // Sadly, this currently doesn't support varargs, platforms other than
239406f32e7eSjoerg   // android/linux. Note that thumb1/thumb2 are support for android/linux.
239506f32e7eSjoerg   if (MF.getFunction().isVarArg())
239606f32e7eSjoerg     report_fatal_error("Segmented stacks do not support vararg functions.");
239706f32e7eSjoerg   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
239806f32e7eSjoerg     report_fatal_error("Segmented stacks not supported on this platform.");
239906f32e7eSjoerg 
240006f32e7eSjoerg   MachineFrameInfo &MFI = MF.getFrameInfo();
240106f32e7eSjoerg   MachineModuleInfo &MMI = MF.getMMI();
240206f32e7eSjoerg   MCContext &Context = MMI.getContext();
240306f32e7eSjoerg   const MCRegisterInfo *MRI = Context.getRegisterInfo();
240406f32e7eSjoerg   const ARMBaseInstrInfo &TII =
240506f32e7eSjoerg       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
240606f32e7eSjoerg   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
240706f32e7eSjoerg   DebugLoc DL;
240806f32e7eSjoerg 
240906f32e7eSjoerg   uint64_t StackSize = MFI.getStackSize();
241006f32e7eSjoerg 
241106f32e7eSjoerg   // Do not generate a prologue for leaf functions with a stack of size zero.
241206f32e7eSjoerg   // For non-leaf functions we have to allow for the possibility that the
241306f32e7eSjoerg   // callis to a non-split function, as in PR37807. This function could also
241406f32e7eSjoerg   // take the address of a non-split function. When the linker tries to adjust
241506f32e7eSjoerg   // its non-existent prologue, it would fail with an error. Mark the object
241606f32e7eSjoerg   // file so that such failures are not errors. See this Go language bug-report
241706f32e7eSjoerg   // https://go-review.googlesource.com/c/go/+/148819/
241806f32e7eSjoerg   if (StackSize == 0 && !MFI.hasTailCall()) {
241906f32e7eSjoerg     MF.getMMI().setHasNosplitStack(true);
242006f32e7eSjoerg     return;
242106f32e7eSjoerg   }
242206f32e7eSjoerg 
242306f32e7eSjoerg   // Use R4 and R5 as scratch registers.
242406f32e7eSjoerg   // We save R4 and R5 before use and restore them before leaving the function.
242506f32e7eSjoerg   unsigned ScratchReg0 = ARM::R4;
242606f32e7eSjoerg   unsigned ScratchReg1 = ARM::R5;
242706f32e7eSjoerg   uint64_t AlignedStackSize;
242806f32e7eSjoerg 
242906f32e7eSjoerg   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
243006f32e7eSjoerg   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
243106f32e7eSjoerg   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
243206f32e7eSjoerg   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
243306f32e7eSjoerg   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
243406f32e7eSjoerg 
243506f32e7eSjoerg   // Grab everything that reaches PrologueMBB to update there liveness as well.
243606f32e7eSjoerg   SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
243706f32e7eSjoerg   SmallVector<MachineBasicBlock *, 2> WalkList;
243806f32e7eSjoerg   WalkList.push_back(&PrologueMBB);
243906f32e7eSjoerg 
244006f32e7eSjoerg   do {
244106f32e7eSjoerg     MachineBasicBlock *CurMBB = WalkList.pop_back_val();
244206f32e7eSjoerg     for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
244306f32e7eSjoerg       if (BeforePrologueRegion.insert(PredBB).second)
244406f32e7eSjoerg         WalkList.push_back(PredBB);
244506f32e7eSjoerg     }
244606f32e7eSjoerg   } while (!WalkList.empty());
244706f32e7eSjoerg 
244806f32e7eSjoerg   // The order in that list is important.
244906f32e7eSjoerg   // The blocks will all be inserted before PrologueMBB using that order.
245006f32e7eSjoerg   // Therefore the block that should appear first in the CFG should appear
245106f32e7eSjoerg   // first in the list.
245206f32e7eSjoerg   MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
245306f32e7eSjoerg                                       PostStackMBB};
245406f32e7eSjoerg 
245506f32e7eSjoerg   for (MachineBasicBlock *B : AddedBlocks)
245606f32e7eSjoerg     BeforePrologueRegion.insert(B);
245706f32e7eSjoerg 
245806f32e7eSjoerg   for (const auto &LI : PrologueMBB.liveins()) {
245906f32e7eSjoerg     for (MachineBasicBlock *PredBB : BeforePrologueRegion)
246006f32e7eSjoerg       PredBB->addLiveIn(LI);
246106f32e7eSjoerg   }
246206f32e7eSjoerg 
246306f32e7eSjoerg   // Remove the newly added blocks from the list, since we know
246406f32e7eSjoerg   // we do not have to do the following updates for them.
246506f32e7eSjoerg   for (MachineBasicBlock *B : AddedBlocks) {
246606f32e7eSjoerg     BeforePrologueRegion.erase(B);
246706f32e7eSjoerg     MF.insert(PrologueMBB.getIterator(), B);
246806f32e7eSjoerg   }
246906f32e7eSjoerg 
247006f32e7eSjoerg   for (MachineBasicBlock *MBB : BeforePrologueRegion) {
247106f32e7eSjoerg     // Make sure the LiveIns are still sorted and unique.
247206f32e7eSjoerg     MBB->sortUniqueLiveIns();
247306f32e7eSjoerg     // Replace the edges to PrologueMBB by edges to the sequences
247406f32e7eSjoerg     // we are about to add.
247506f32e7eSjoerg     MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
247606f32e7eSjoerg   }
247706f32e7eSjoerg 
247806f32e7eSjoerg   // The required stack size that is aligned to ARM constant criterion.
247906f32e7eSjoerg   AlignedStackSize = alignToARMConstant(StackSize);
248006f32e7eSjoerg 
248106f32e7eSjoerg   // When the frame size is less than 256 we just compare the stack
248206f32e7eSjoerg   // boundary directly to the value of the stack pointer, per gcc.
248306f32e7eSjoerg   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
248406f32e7eSjoerg 
248506f32e7eSjoerg   // We will use two of the callee save registers as scratch registers so we
248606f32e7eSjoerg   // need to save those registers onto the stack.
248706f32e7eSjoerg   // We will use SR0 to hold stack limit and SR1 to hold the stack size
248806f32e7eSjoerg   // requested and arguments for __morestack().
248906f32e7eSjoerg   // SR0: Scratch Register #0
249006f32e7eSjoerg   // SR1: Scratch Register #1
249106f32e7eSjoerg   // push {SR0, SR1}
249206f32e7eSjoerg   if (Thumb) {
249306f32e7eSjoerg     BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
249406f32e7eSjoerg         .add(predOps(ARMCC::AL))
249506f32e7eSjoerg         .addReg(ScratchReg0)
249606f32e7eSjoerg         .addReg(ScratchReg1);
249706f32e7eSjoerg   } else {
249806f32e7eSjoerg     BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
249906f32e7eSjoerg         .addReg(ARM::SP, RegState::Define)
250006f32e7eSjoerg         .addReg(ARM::SP)
250106f32e7eSjoerg         .add(predOps(ARMCC::AL))
250206f32e7eSjoerg         .addReg(ScratchReg0)
250306f32e7eSjoerg         .addReg(ScratchReg1);
250406f32e7eSjoerg   }
250506f32e7eSjoerg 
250606f32e7eSjoerg   // Emit the relevant DWARF information about the change in stack pointer as
250706f32e7eSjoerg   // well as where to find both r4 and r5 (the callee-save registers)
2508*da58b97aSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 8));
250906f32e7eSjoerg   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
251006f32e7eSjoerg       .addCFIIndex(CFIIndex);
251106f32e7eSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
251206f32e7eSjoerg       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
251306f32e7eSjoerg   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
251406f32e7eSjoerg       .addCFIIndex(CFIIndex);
251506f32e7eSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
251606f32e7eSjoerg       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
251706f32e7eSjoerg   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
251806f32e7eSjoerg       .addCFIIndex(CFIIndex);
251906f32e7eSjoerg 
252006f32e7eSjoerg   // mov SR1, sp
252106f32e7eSjoerg   if (Thumb) {
252206f32e7eSjoerg     BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
252306f32e7eSjoerg         .addReg(ARM::SP)
252406f32e7eSjoerg         .add(predOps(ARMCC::AL));
252506f32e7eSjoerg   } else if (CompareStackPointer) {
252606f32e7eSjoerg     BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
252706f32e7eSjoerg         .addReg(ARM::SP)
252806f32e7eSjoerg         .add(predOps(ARMCC::AL))
252906f32e7eSjoerg         .add(condCodeOp());
253006f32e7eSjoerg   }
253106f32e7eSjoerg 
253206f32e7eSjoerg   // sub SR1, sp, #StackSize
253306f32e7eSjoerg   if (!CompareStackPointer && Thumb) {
253406f32e7eSjoerg     BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
253506f32e7eSjoerg         .add(condCodeOp())
253606f32e7eSjoerg         .addReg(ScratchReg1)
253706f32e7eSjoerg         .addImm(AlignedStackSize)
253806f32e7eSjoerg         .add(predOps(ARMCC::AL));
253906f32e7eSjoerg   } else if (!CompareStackPointer) {
254006f32e7eSjoerg     BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
254106f32e7eSjoerg         .addReg(ARM::SP)
254206f32e7eSjoerg         .addImm(AlignedStackSize)
254306f32e7eSjoerg         .add(predOps(ARMCC::AL))
254406f32e7eSjoerg         .add(condCodeOp());
254506f32e7eSjoerg   }
254606f32e7eSjoerg 
254706f32e7eSjoerg   if (Thumb && ST->isThumb1Only()) {
254806f32e7eSjoerg     unsigned PCLabelId = ARMFI->createPICLabelUId();
254906f32e7eSjoerg     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
255006f32e7eSjoerg         MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
255106f32e7eSjoerg     MachineConstantPool *MCP = MF.getConstantPool();
2552*da58b97aSjoerg     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4));
255306f32e7eSjoerg 
255406f32e7eSjoerg     // ldr SR0, [pc, offset(STACK_LIMIT)]
255506f32e7eSjoerg     BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
255606f32e7eSjoerg         .addConstantPoolIndex(CPI)
255706f32e7eSjoerg         .add(predOps(ARMCC::AL));
255806f32e7eSjoerg 
255906f32e7eSjoerg     // ldr SR0, [SR0]
256006f32e7eSjoerg     BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
256106f32e7eSjoerg         .addReg(ScratchReg0)
256206f32e7eSjoerg         .addImm(0)
256306f32e7eSjoerg         .add(predOps(ARMCC::AL));
256406f32e7eSjoerg   } else {
256506f32e7eSjoerg     // Get TLS base address from the coprocessor
256606f32e7eSjoerg     // mrc p15, #0, SR0, c13, c0, #3
2567*da58b97aSjoerg     BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
2568*da58b97aSjoerg             ScratchReg0)
256906f32e7eSjoerg         .addImm(15)
257006f32e7eSjoerg         .addImm(0)
257106f32e7eSjoerg         .addImm(13)
257206f32e7eSjoerg         .addImm(0)
257306f32e7eSjoerg         .addImm(3)
257406f32e7eSjoerg         .add(predOps(ARMCC::AL));
257506f32e7eSjoerg 
257606f32e7eSjoerg     // Use the last tls slot on android and a private field of the TCP on linux.
257706f32e7eSjoerg     assert(ST->isTargetAndroid() || ST->isTargetLinux());
257806f32e7eSjoerg     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
257906f32e7eSjoerg 
258006f32e7eSjoerg     // Get the stack limit from the right offset
258106f32e7eSjoerg     // ldr SR0, [sr0, #4 * TlsOffset]
2582*da58b97aSjoerg     BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
2583*da58b97aSjoerg             ScratchReg0)
258406f32e7eSjoerg         .addReg(ScratchReg0)
258506f32e7eSjoerg         .addImm(4 * TlsOffset)
258606f32e7eSjoerg         .add(predOps(ARMCC::AL));
258706f32e7eSjoerg   }
258806f32e7eSjoerg 
258906f32e7eSjoerg   // Compare stack limit with stack size requested.
259006f32e7eSjoerg   // cmp SR0, SR1
259106f32e7eSjoerg   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
259206f32e7eSjoerg   BuildMI(GetMBB, DL, TII.get(Opcode))
259306f32e7eSjoerg       .addReg(ScratchReg0)
259406f32e7eSjoerg       .addReg(ScratchReg1)
259506f32e7eSjoerg       .add(predOps(ARMCC::AL));
259606f32e7eSjoerg 
259706f32e7eSjoerg   // This jump is taken if StackLimit < SP - stack required.
259806f32e7eSjoerg   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
259906f32e7eSjoerg   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
260006f32e7eSjoerg        .addImm(ARMCC::LO)
260106f32e7eSjoerg        .addReg(ARM::CPSR);
260206f32e7eSjoerg 
260306f32e7eSjoerg 
260406f32e7eSjoerg   // Calling __morestack(StackSize, Size of stack arguments).
260506f32e7eSjoerg   // __morestack knows that the stack size requested is in SR0(r4)
260606f32e7eSjoerg   // and amount size of stack arguments is in SR1(r5).
260706f32e7eSjoerg 
260806f32e7eSjoerg   // Pass first argument for the __morestack by Scratch Register #0.
260906f32e7eSjoerg   //   The amount size of stack required
261006f32e7eSjoerg   if (Thumb) {
261106f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
261206f32e7eSjoerg         .add(condCodeOp())
261306f32e7eSjoerg         .addImm(AlignedStackSize)
261406f32e7eSjoerg         .add(predOps(ARMCC::AL));
261506f32e7eSjoerg   } else {
261606f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
261706f32e7eSjoerg         .addImm(AlignedStackSize)
261806f32e7eSjoerg         .add(predOps(ARMCC::AL))
261906f32e7eSjoerg         .add(condCodeOp());
262006f32e7eSjoerg   }
262106f32e7eSjoerg   // Pass second argument for the __morestack by Scratch Register #1.
262206f32e7eSjoerg   //   The amount size of stack consumed to save function arguments.
262306f32e7eSjoerg   if (Thumb) {
262406f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
262506f32e7eSjoerg         .add(condCodeOp())
262606f32e7eSjoerg         .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
262706f32e7eSjoerg         .add(predOps(ARMCC::AL));
262806f32e7eSjoerg   } else {
262906f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
263006f32e7eSjoerg         .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
263106f32e7eSjoerg         .add(predOps(ARMCC::AL))
263206f32e7eSjoerg         .add(condCodeOp());
263306f32e7eSjoerg   }
263406f32e7eSjoerg 
263506f32e7eSjoerg   // push {lr} - Save return address of this function.
263606f32e7eSjoerg   if (Thumb) {
263706f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
263806f32e7eSjoerg         .add(predOps(ARMCC::AL))
263906f32e7eSjoerg         .addReg(ARM::LR);
264006f32e7eSjoerg   } else {
264106f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
264206f32e7eSjoerg         .addReg(ARM::SP, RegState::Define)
264306f32e7eSjoerg         .addReg(ARM::SP)
264406f32e7eSjoerg         .add(predOps(ARMCC::AL))
264506f32e7eSjoerg         .addReg(ARM::LR);
264606f32e7eSjoerg   }
264706f32e7eSjoerg 
264806f32e7eSjoerg   // Emit the DWARF info about the change in stack as well as where to find the
264906f32e7eSjoerg   // previous link register
2650*da58b97aSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 12));
265106f32e7eSjoerg   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
265206f32e7eSjoerg       .addCFIIndex(CFIIndex);
265306f32e7eSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
265406f32e7eSjoerg         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
265506f32e7eSjoerg   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
265606f32e7eSjoerg       .addCFIIndex(CFIIndex);
265706f32e7eSjoerg 
265806f32e7eSjoerg   // Call __morestack().
265906f32e7eSjoerg   if (Thumb) {
266006f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
266106f32e7eSjoerg         .add(predOps(ARMCC::AL))
266206f32e7eSjoerg         .addExternalSymbol("__morestack");
266306f32e7eSjoerg   } else {
266406f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
266506f32e7eSjoerg         .addExternalSymbol("__morestack");
266606f32e7eSjoerg   }
266706f32e7eSjoerg 
266806f32e7eSjoerg   // pop {lr} - Restore return address of this original function.
266906f32e7eSjoerg   if (Thumb) {
267006f32e7eSjoerg     if (ST->isThumb1Only()) {
267106f32e7eSjoerg       BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
267206f32e7eSjoerg           .add(predOps(ARMCC::AL))
267306f32e7eSjoerg           .addReg(ScratchReg0);
267406f32e7eSjoerg       BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
267506f32e7eSjoerg           .addReg(ScratchReg0)
267606f32e7eSjoerg           .add(predOps(ARMCC::AL));
267706f32e7eSjoerg     } else {
267806f32e7eSjoerg       BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
267906f32e7eSjoerg           .addReg(ARM::LR, RegState::Define)
268006f32e7eSjoerg           .addReg(ARM::SP, RegState::Define)
268106f32e7eSjoerg           .addReg(ARM::SP)
268206f32e7eSjoerg           .addImm(4)
268306f32e7eSjoerg           .add(predOps(ARMCC::AL));
268406f32e7eSjoerg     }
268506f32e7eSjoerg   } else {
268606f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
268706f32e7eSjoerg         .addReg(ARM::SP, RegState::Define)
268806f32e7eSjoerg         .addReg(ARM::SP)
268906f32e7eSjoerg         .add(predOps(ARMCC::AL))
269006f32e7eSjoerg         .addReg(ARM::LR);
269106f32e7eSjoerg   }
269206f32e7eSjoerg 
269306f32e7eSjoerg   // Restore SR0 and SR1 in case of __morestack() was called.
269406f32e7eSjoerg   // __morestack() will skip PostStackMBB block so we need to restore
269506f32e7eSjoerg   // scratch registers from here.
269606f32e7eSjoerg   // pop {SR0, SR1}
269706f32e7eSjoerg   if (Thumb) {
269806f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
269906f32e7eSjoerg         .add(predOps(ARMCC::AL))
270006f32e7eSjoerg         .addReg(ScratchReg0)
270106f32e7eSjoerg         .addReg(ScratchReg1);
270206f32e7eSjoerg   } else {
270306f32e7eSjoerg     BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
270406f32e7eSjoerg         .addReg(ARM::SP, RegState::Define)
270506f32e7eSjoerg         .addReg(ARM::SP)
270606f32e7eSjoerg         .add(predOps(ARMCC::AL))
270706f32e7eSjoerg         .addReg(ScratchReg0)
270806f32e7eSjoerg         .addReg(ScratchReg1);
270906f32e7eSjoerg   }
271006f32e7eSjoerg 
271106f32e7eSjoerg   // Update the CFA offset now that we've popped
2712*da58b97aSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
271306f32e7eSjoerg   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
271406f32e7eSjoerg       .addCFIIndex(CFIIndex);
271506f32e7eSjoerg 
271606f32e7eSjoerg   // Return from this function.
271706f32e7eSjoerg   BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
271806f32e7eSjoerg 
271906f32e7eSjoerg   // Restore SR0 and SR1 in case of __morestack() was not called.
272006f32e7eSjoerg   // pop {SR0, SR1}
272106f32e7eSjoerg   if (Thumb) {
272206f32e7eSjoerg     BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
272306f32e7eSjoerg         .add(predOps(ARMCC::AL))
272406f32e7eSjoerg         .addReg(ScratchReg0)
272506f32e7eSjoerg         .addReg(ScratchReg1);
272606f32e7eSjoerg   } else {
272706f32e7eSjoerg     BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
272806f32e7eSjoerg         .addReg(ARM::SP, RegState::Define)
272906f32e7eSjoerg         .addReg(ARM::SP)
273006f32e7eSjoerg         .add(predOps(ARMCC::AL))
273106f32e7eSjoerg         .addReg(ScratchReg0)
273206f32e7eSjoerg         .addReg(ScratchReg1);
273306f32e7eSjoerg   }
273406f32e7eSjoerg 
273506f32e7eSjoerg   // Update the CFA offset now that we've popped
2736*da58b97aSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
273706f32e7eSjoerg   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
273806f32e7eSjoerg       .addCFIIndex(CFIIndex);
273906f32e7eSjoerg 
274006f32e7eSjoerg   // Tell debuggers that r4 and r5 are now the same as they were in the
274106f32e7eSjoerg   // previous function, that they're the "Same Value".
274206f32e7eSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
274306f32e7eSjoerg       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
274406f32e7eSjoerg   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
274506f32e7eSjoerg       .addCFIIndex(CFIIndex);
274606f32e7eSjoerg   CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
274706f32e7eSjoerg       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
274806f32e7eSjoerg   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
274906f32e7eSjoerg       .addCFIIndex(CFIIndex);
275006f32e7eSjoerg 
275106f32e7eSjoerg   // Organizing MBB lists
275206f32e7eSjoerg   PostStackMBB->addSuccessor(&PrologueMBB);
275306f32e7eSjoerg 
275406f32e7eSjoerg   AllocMBB->addSuccessor(PostStackMBB);
275506f32e7eSjoerg 
275606f32e7eSjoerg   GetMBB->addSuccessor(PostStackMBB);
275706f32e7eSjoerg   GetMBB->addSuccessor(AllocMBB);
275806f32e7eSjoerg 
275906f32e7eSjoerg   McrMBB->addSuccessor(GetMBB);
276006f32e7eSjoerg 
276106f32e7eSjoerg   PrevStackMBB->addSuccessor(McrMBB);
276206f32e7eSjoerg 
276306f32e7eSjoerg #ifdef EXPENSIVE_CHECKS
276406f32e7eSjoerg   MF.verify();
276506f32e7eSjoerg #endif
276606f32e7eSjoerg }
2767