blob: af4c97db684a5e43b73bb172d4b4c5165d7fad6c [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Anton Korobeynikov2f931282011-01-10 12:39:04 +000010// This file contains the ARM implementation of TargetFrameLowering class.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000011//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov2f931282011-01-10 12:39:04 +000014#include "ARMFrameLowering.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000015#include "ARMBaseInstrInfo.h"
Evan Chenge45d6852011-01-11 21:46:47 +000016#include "ARMBaseRegisterInfo.h"
Oliver Stannardb14c6252014-04-02 16:10:33 +000017#include "ARMConstantPoolValue.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000018#include "ARMMachineFunctionInfo.h"
Evan Chenga20cde32011-07-20 23:34:39 +000019#include "MCTargetDesc/ARMAddressingModes.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000020#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Evan Chengeb56dca2010-11-22 18:12:04 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +000025#include "llvm/CodeGen/RegisterScavenging.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Function.h"
Saleem Abdulrasool25947c32014-04-30 07:05:07 +000028#include "llvm/IR/Module.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000029#include "llvm/MC/MCContext.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000030#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetOptions.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000032
33using namespace llvm;
34
Benjamin Kramer9fceb902012-02-24 22:09:25 +000035static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000036SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000037 cl::desc("Align ARM NEON spills in prolog and epilog"));
38
39static MachineBasicBlock::iterator
40skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
41 unsigned NumAlignedDPRCS2Regs);
42
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000043/// hasFP - Return true if the specified function should have a dedicated frame
44/// pointer register. This is true if the function has variable sized allocas
45/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000046bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000047 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
48
Evan Cheng801d98b2012-01-04 01:55:04 +000049 // iOS requires FP not to be clobbered for backtracing purpose.
50 if (STI.isTargetIOS())
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000051 return true;
52
53 const MachineFrameInfo *MFI = MF.getFrameInfo();
54 // Always eliminate non-leaf frame pointers.
Nick Lewycky50f02cb2011-12-02 22:16:29 +000055 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
56 MFI->hasCalls()) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000057 RegInfo->needsStackRealignment(MF) ||
58 MFI->hasVarSizedObjects() ||
59 MFI->isFrameAddressTaken());
60}
61
Bob Wilson657f2272011-01-13 21:10:12 +000062/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
63/// not required, we reserve argument space for call sites in the function
64/// immediately on entry to the current function. This eliminates the need for
65/// add/sub sp brackets around call sites. Returns true if the call frame is
66/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000067bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000068 const MachineFrameInfo *FFI = MF.getFrameInfo();
69 unsigned CFSize = FFI->getMaxCallFrameSize();
70 // It's not always a good idea to include the call frame as part of the
71 // stack frame. ARM (especially Thumb) has small immediate offset to
72 // address the stack frame. So a large call frame can cause poor codegen
73 // and may even makes it impossible to scavenge a register.
74 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
75 return false;
76
77 return !MF.getFrameInfo()->hasVarSizedObjects();
78}
79
Bob Wilson657f2272011-01-13 21:10:12 +000080/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
81/// call frame pseudos can be simplified. Unlike most targets, having a FP
82/// is not sufficient here since we still may reference some objects via SP
83/// even when FP is available in Thumb2 mode.
84bool
85ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000086 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
87}
88
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000089static bool isCSRestore(MachineInstr *MI,
90 const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +000091 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +000092 // Integer spill area is handled with "pop".
Tim Northover93bcc662013-11-08 17:18:07 +000093 if (isPopOpcode(MI->getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +000094 // The first two operands are predicates. The last two are
95 // imp-def and imp-use of SP. Check everything in between.
96 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
97 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
98 return false;
99 return true;
100 }
Owen Anderson2aedba62011-07-26 20:54:26 +0000101 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
102 MI->getOpcode() == ARM::LDR_POST_REG ||
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000103 MI->getOpcode() == ARM::t2LDR_POST) &&
104 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
105 MI->getOperand(1).getReg() == ARM::SP)
106 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000107
108 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000109}
110
Tim Northoverc9432eb2013-11-04 23:04:15 +0000111static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
112 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
113 const ARMBaseInstrInfo &TII, unsigned DestReg,
114 unsigned SrcReg, int NumBytes,
115 unsigned MIFlags = MachineInstr::NoFlags,
116 ARMCC::CondCodes Pred = ARMCC::AL,
117 unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000118 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000119 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000120 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000121 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000122 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000123 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000124}
125
Tim Northoverc9432eb2013-11-04 23:04:15 +0000126static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
127 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
128 const ARMBaseInstrInfo &TII, int NumBytes,
129 unsigned MIFlags = MachineInstr::NoFlags,
130 ARMCC::CondCodes Pred = ARMCC::AL,
131 unsigned PredReg = 0) {
132 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
133 MIFlags, Pred, PredReg);
134}
135
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000136static int sizeOfSPAdjustment(const MachineInstr *MI) {
137 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
138 int count = 0;
139 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
140 // pred) so the list starts at 4.
141 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
142 count += 8;
143 return count;
144}
145
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000146static bool WindowsRequiresStackProbe(const MachineFunction &MF,
147 size_t StackSizeInBytes) {
148 const MachineFrameInfo *MFI = MF.getFrameInfo();
149 if (MFI->getStackProtectorIndex() > 0)
150 return StackSizeInBytes >= 4080;
151 return StackSizeInBytes >= 4096;
152}
153
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000154void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000155 MachineBasicBlock &MBB = MF.front();
156 MachineBasicBlock::iterator MBBI = MBB.begin();
157 MachineFrameInfo *MFI = MF.getFrameInfo();
158 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000159 MachineModuleInfo &MMI = MF.getMMI();
160 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000161 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000162 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000163 const ARMBaseRegisterInfo *RegInfo =
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000164 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000165 const ARMBaseInstrInfo &TII =
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000166 *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000167 assert(!AFI->isThumb1OnlyFunction() &&
168 "This emitPrologue does not support Thumb1!");
169 bool isARM = !AFI->isThumbFunction();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000170 unsigned Align = TM.getFrameLowering()->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000171 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000172 unsigned NumBytes = MFI->getStackSize();
173 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
174 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
175 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000176 int CFAOffset = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000177
178 // Determine the sizes of each callee-save spill areas and record which frame
179 // belongs to which callee-save spill areas.
180 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
181 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000182 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000183
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000184 // All calls are tail calls in GHC calling conv, and functions have no
185 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000186 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
187 return;
188
Oliver Stannardd55e1152014-03-05 15:25:27 +0000189 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000190 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000191 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000192 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000193 CFAOffset -= ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000194 unsigned CFIIndex = MMI.addFrameInst(
195 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
196 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
197 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000198 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000199
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000200 if (!AFI->hasStackFrame() &&
201 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000202 if (NumBytes - ArgRegsSaveSize != 0) {
203 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000204 MachineInstr::FrameSetup);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000205 CFAOffset -= NumBytes - ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000206 unsigned CFIIndex = MMI.addFrameInst(
207 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
208 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
209 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000210 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000211 return;
212 }
213
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000214 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000215 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
216 unsigned Reg = CSI[i].getReg();
217 int FI = CSI[i].getFrameIdx();
218 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000219 case ARM::R8:
220 case ARM::R9:
221 case ARM::R10:
222 case ARM::R11:
223 case ARM::R12:
224 if (STI.isTargetMachO()) {
225 GPRCS2Size += 4;
226 break;
227 }
228 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000229 case ARM::R0:
230 case ARM::R1:
231 case ARM::R2:
232 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000233 case ARM::R4:
234 case ARM::R5:
235 case ARM::R6:
236 case ARM::R7:
237 case ARM::LR:
238 if (Reg == FramePtr)
239 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000240 GPRCS1Size += 4;
241 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000242 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000243 // This is a DPR. Exclude the aligned DPRCS2 spills.
244 if (Reg == ARM::D8)
245 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000246 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000247 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000248 }
249 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000250
Eric Christopherb006fc92010-11-18 19:40:05 +0000251 // Move past area 1.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000252 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
253 DPRCSPush;
Tim Northover93bcc662013-11-08 17:18:07 +0000254 if (GPRCS1Size > 0)
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000255 GPRCS1Push = LastPush = MBBI++;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000256
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000257 // Determine starting offsets of spill areas.
Tim Northoverc9432eb2013-11-04 23:04:15 +0000258 bool HasFP = hasFP(MF);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000259 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
260 + GPRCS2Size + DPRCSSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000261 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
262 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
Tim Northover93bcc662013-11-08 17:18:07 +0000263 int FramePtrOffsetInPush = 0;
264 if (HasFP) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000265 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
266 + GPRCS1Size + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000267 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
268 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000269 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000270 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
271 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
272 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
273
Tim Northoverc9432eb2013-11-04 23:04:15 +0000274 // Move past area 2.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000275 if (GPRCS2Size > 0)
276 GPRCS2Push = LastPush = MBBI++;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000277
Eric Christopherb006fc92010-11-18 19:40:05 +0000278 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000279 if (DPRCSSize > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000280 DPRCSPush = MBBI;
Evan Cheng70d29632011-02-25 00:24:46 +0000281 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000282 // instructions in the prologue.
Evan Cheng70d29632011-02-25 00:24:46 +0000283 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
Tim Northover93bcc662013-11-08 17:18:07 +0000284 LastPush = MBBI++;
Evan Cheng70d29632011-02-25 00:24:46 +0000285 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000286
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000287 // Move past the aligned DPRCS2 area.
288 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
289 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
290 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
291 // leaves the stack pointer pointing to the DPRCS2 area.
292 //
293 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
294 NumBytes += MFI->getObjectOffset(D8SpillFI);
295 } else
296 NumBytes = DPRCSOffset;
297
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000298 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
299 uint32_t NumWords = NumBytes >> 2;
300
301 if (NumWords < 65536)
302 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
303 .addImm(NumWords));
304 else
305 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
306 .addImm(NumWords);
307
308 switch (TM.getCodeModel()) {
309 case CodeModel::Small:
310 case CodeModel::Medium:
311 case CodeModel::Default:
312 case CodeModel::Kernel:
313 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
314 .addImm((unsigned)ARMCC::AL).addReg(0)
315 .addExternalSymbol("__chkstk")
316 .addReg(ARM::R4, RegState::Implicit);
317 break;
318 case CodeModel::Large:
319 case CodeModel::JITDefault: {
320 LLVMContext &Ctx = MF.getMMI().getModule()->getContext();
321 const GlobalValue *F =
322 Function::Create(FunctionType::get(Type::getVoidTy(Ctx), false),
323 GlobalValue::AvailableExternallyLinkage, "__chkstk");
324
325 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
326 .addGlobalAddress(F);
327 BuildMI(MBB, MBBI, dl, TII.get(ARM::BLX))
328 .addReg(ARM::R12, RegState::Kill)
329 .addReg(ARM::R4, RegState::Implicit);
330 break;
331 }
332 }
333
334 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
335 ARM::SP)
336 .addReg(ARM::SP, RegState::Define)
337 .addReg(ARM::R4, RegState::Kill)
338 .setMIFlags(MachineInstr::FrameSetup)));
339 NumBytes = 0;
340 }
341
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000342 unsigned adjustedGPRCS1Size = GPRCS1Size;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000343 if (NumBytes) {
344 // Adjust SP after all the callee-save spills.
Tim Northovera4173712013-12-08 15:56:50 +0000345 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000346 if (LastPush == GPRCS1Push) {
Tim Northovera4173712013-12-08 15:56:50 +0000347 FramePtrOffsetInPush += NumBytes;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000348 adjustedGPRCS1Size += NumBytes;
349 NumBytes = 0;
350 }
Tim Northovera4173712013-12-08 15:56:50 +0000351 } else
Tim Northover93bcc662013-11-08 17:18:07 +0000352 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
353 MachineInstr::FrameSetup);
354
Evan Chengeb56dca2010-11-22 18:12:04 +0000355 if (HasFP && isARM)
356 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
357 // Note it's not safe to do this in Thumb2 mode because it would have
358 // taken two instructions:
359 // mov sp, r7
360 // sub sp, #24
361 // If an interrupt is taken between the two instructions, then sp is in
362 // an inconsistent state (pointing to the middle of callee-saved area).
363 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000364 AFI->setShouldRestoreSPFromFP(true);
365 }
366
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000367 if (adjustedGPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000368 CFAOffset -= adjustedGPRCS1Size;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000369 unsigned CFIIndex = MMI.addFrameInst(
370 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
371 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
372 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
373 .addCFIIndex(CFIIndex);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000374 for (const auto &Entry : CSI) {
375 unsigned Reg = Entry.getReg();
376 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000377 switch (Reg) {
378 case ARM::R8:
379 case ARM::R9:
380 case ARM::R10:
381 case ARM::R11:
382 case ARM::R12:
383 if (STI.isTargetMachO())
384 break;
385 // fallthrough
386 case ARM::R0:
387 case ARM::R1:
388 case ARM::R2:
389 case ARM::R3:
390 case ARM::R4:
391 case ARM::R5:
392 case ARM::R6:
393 case ARM::R7:
394 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000395 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
396 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
397 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
398 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000399 break;
400 }
401 }
402 }
403
Tim Northover93bcc662013-11-08 17:18:07 +0000404 // Set FP to point to the stack slot that contains the previous FP.
405 // For iOS, FP is R7, which has now been stored in spill area 1.
406 // Otherwise, if this is not iOS, all the callee-saved registers go
407 // into spill area 1, including the FP in R11. In either case, it
408 // is in area one and the adjustment needs to take place just after
409 // that push.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000410 if (HasFP) {
411 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
Tim Northover93bcc662013-11-08 17:18:07 +0000412 FramePtr, ARM::SP, FramePtrOffsetInPush,
413 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000414 if (FramePtrOffsetInPush) {
415 CFAOffset += FramePtrOffsetInPush;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000416 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
417 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
418 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
419 .addCFIIndex(CFIIndex);
420
421 } else {
422 unsigned CFIIndex =
423 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
424 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
425 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
426 .addCFIIndex(CFIIndex);
427 }
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000428 }
Tim Northover93bcc662013-11-08 17:18:07 +0000429
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000430 if (GPRCS2Size > 0) {
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000431 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000432 if (!HasFP) {
433 CFAOffset -= GPRCS2Size;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000434 unsigned CFIIndex = MMI.addFrameInst(
435 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
436 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
437 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000438 }
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000439 for (const auto &Entry : CSI) {
440 unsigned Reg = Entry.getReg();
441 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000442 switch (Reg) {
443 case ARM::R8:
444 case ARM::R9:
445 case ARM::R10:
446 case ARM::R11:
447 case ARM::R12:
448 if (STI.isTargetMachO()) {
449 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000450 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000451 unsigned CFIIndex = MMI.addFrameInst(
452 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
453 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
454 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000455 }
456 break;
457 }
458 }
459 }
460
461 if (DPRCSSize > 0) {
462 // Since vpush register list cannot have gaps, there may be multiple vpush
463 // instructions in the prologue.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000464 do {
465 MachineBasicBlock::iterator Push = DPRCSPush++;
466 if (!HasFP) {
Alp Toker98444342014-04-19 23:56:35 +0000467 CFAOffset -= sizeOfSPAdjustment(Push);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000468 unsigned CFIIndex = MMI.addFrameInst(
469 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
470 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
471 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000472 }
473 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
474
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000475 for (const auto &Entry : CSI) {
476 unsigned Reg = Entry.getReg();
477 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000478 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
479 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
480 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
481 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000482 unsigned CFIIndex = MMI.addFrameInst(
483 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
484 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
485 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000486 }
487 }
488 }
489
490 if (NumBytes) {
491 if (!HasFP) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000492 CFAOffset -= NumBytes;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000493 unsigned CFIIndex = MMI.addFrameInst(
494 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
495 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
496 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000497 }
498 }
Tim Northover93bcc662013-11-08 17:18:07 +0000499
Evan Chengeb56dca2010-11-22 18:12:04 +0000500 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000501 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
502 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000503
504 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
505 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
506 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
507
508 // If we need dynamic stack realignment, do it here. Be paranoid and make
509 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000510 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000511 // realigned.
512 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000513 unsigned MaxAlign = MFI->getMaxAlignment();
514 assert (!AFI->isThumb1OnlyFunction());
515 if (!AFI->isThumbFunction()) {
516 // Emit bic sp, sp, MaxAlign
517 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
518 TII.get(ARM::BICri), ARM::SP)
519 .addReg(ARM::SP, RegState::Kill)
520 .addImm(MaxAlign-1)));
521 } else {
522 // We cannot use sp as source/dest register here, thus we're emitting the
523 // following sequence:
524 // mov r4, sp
525 // bic r4, r4, MaxAlign
526 // mov sp, r4
527 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000528 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000529 .addReg(ARM::SP, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000530 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
531 TII.get(ARM::t2BICri), ARM::R4)
532 .addReg(ARM::R4, RegState::Kill)
533 .addImm(MaxAlign-1)));
Jim Grosbache9cc9012011-06-30 23:38:17 +0000534 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000535 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000536 }
537
538 AFI->setShouldRestoreSPFromFP(true);
539 }
540
541 // If we need a base pointer, set it up here. It's whatever the value
542 // of the stack pointer is at this point. Any variable size objects
543 // will be allocated after this, so we can still use the base pointer
544 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000545 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000546 if (RegInfo->hasBasePointer(MF)) {
547 if (isARM)
548 BuildMI(MBB, MBBI, dl,
549 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
550 .addReg(ARM::SP)
551 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
552 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000553 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000554 RegInfo->getBaseRegister())
555 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000556 }
557
558 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000559 // the sp from fp. We can assume there's an FP here since hasFP already
560 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000561 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000562 AFI->setShouldRestoreSPFromFP(true);
563}
564
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000565void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000566 MachineBasicBlock &MBB) const {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000567 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000568 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000569 unsigned RetOpcode = MBBI->getOpcode();
570 DebugLoc dl = MBBI->getDebugLoc();
571 MachineFrameInfo *MFI = MF.getFrameInfo();
572 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
573 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
574 const ARMBaseInstrInfo &TII =
575 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
576 assert(!AFI->isThumb1OnlyFunction() &&
577 "This emitEpilogue does not support Thumb1!");
578 bool isARM = !AFI->isThumbFunction();
579
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000580 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
581 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000582 int NumBytes = (int)MFI->getStackSize();
583 unsigned FramePtr = RegInfo->getFrameRegister(MF);
584
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000585 // All calls are tail calls in GHC calling conv, and functions have no
586 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000587 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
588 return;
589
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000590 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000591 if (NumBytes - ArgRegsSaveSize != 0)
592 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000593 } else {
594 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000595 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000596 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000597 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000598 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000599 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000600 if (!isCSRestore(MBBI, TII, CSRegs))
601 ++MBBI;
602 }
603
604 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000605 NumBytes -= (ArgRegsSaveSize +
606 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000607 AFI->getGPRCalleeSavedArea2Size() +
608 AFI->getDPRCalleeSavedAreaSize());
609
610 // Reset SP based on frame pointer only if the stack frame extends beyond
611 // frame pointer stack slot or target is ELF and the function has FP.
612 if (AFI->shouldRestoreSPFromFP()) {
613 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
614 if (NumBytes) {
615 if (isARM)
616 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
617 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000618 else {
619 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000620 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000621 // mov sp, r7
622 // sub sp, #24
623 // This is bad, if an interrupt is taken after the mov, sp is in an
624 // inconsistent state.
625 // Use the first callee-saved register as a scratch register.
Kaelyn Uhrain271fbb62012-10-26 23:28:41 +0000626 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000627 "No scratch register to restore SP from FP!");
628 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000629 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000630 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000631 ARM::SP)
632 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000633 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000634 } else {
635 // Thumb2 or ARM.
636 if (isARM)
637 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
638 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
639 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000640 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000641 ARM::SP)
642 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000643 }
Tim Northoverdee86042013-12-02 14:46:26 +0000644 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000645 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000646 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000647
Eric Christopherb006fc92010-11-18 19:40:05 +0000648 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000649 if (AFI->getDPRCalleeSavedAreaSize()) {
650 MBBI++;
651 // Since vpop register list cannot have gaps, there may be multiple vpop
652 // instructions in the epilogue.
653 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
654 MBBI++;
655 }
Eric Christopherb006fc92010-11-18 19:40:05 +0000656 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
657 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000658 }
659
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000660 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000661 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000662 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000663 MachineOperand &JumpTarget = MBBI->getOperand(0);
664
665 // Jump to label or value in register.
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000666 if (RetOpcode == ARM::TCRETURNdi) {
667 unsigned TCOpcode = STI.isThumb() ?
Tim Northoverd6a729b2014-01-06 14:28:05 +0000668 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000669 ARM::TAILJMPd;
Evan Chengd4b08732010-11-30 23:55:39 +0000670 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
671 if (JumpTarget.isGlobal())
672 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
673 JumpTarget.getTargetFlags());
674 else {
675 assert(JumpTarget.isSymbol());
676 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
677 JumpTarget.getTargetFlags());
678 }
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000679
680 // Add the default predicate in Thumb mode.
681 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000682 } else if (RetOpcode == ARM::TCRETURNri) {
Jim Grosbach3af6fe62011-03-15 00:30:40 +0000683 BuildMI(MBB, MBBI, dl,
684 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000685 addReg(JumpTarget.getReg(), RegState::Kill);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000686 }
687
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000688 MachineInstr *NewMI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000689 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
690 NewMI->addOperand(MBBI->getOperand(i));
691
692 // Delete the pseudo instruction TCRETURN.
693 MBB.erase(MBBI);
Cameron Zwarich033026f2011-06-17 02:16:43 +0000694 MBBI = NewMI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000695 }
696
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000697 if (ArgRegsSaveSize)
698 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000699}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000700
Bob Wilson657f2272011-01-13 21:10:12 +0000701/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
702/// debug info. It's the same as what we use for resolving the code-gen
703/// references for now. FIXME: This can go wrong when references are
704/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000705int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000706ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000707 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000708 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
709}
710
711int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000712ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000713 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000714 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000715 const MachineFrameInfo *MFI = MF.getFrameInfo();
716 const ARMBaseRegisterInfo *RegInfo =
717 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
718 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
719 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
720 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
721 bool isFixed = MFI->isFixedObjectIndex(FI);
722
723 FrameReg = ARM::SP;
724 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000725
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000726 // SP can move around if there are allocas. We may also lose track of SP
727 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000728 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000729
Anton Korobeynikov46877782010-11-20 15:59:32 +0000730 // When dynamically realigning the stack, use the frame pointer for
731 // parameters, and the stack/base pointer for locals.
732 if (RegInfo->needsStackRealignment(MF)) {
733 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
734 if (isFixed) {
735 FrameReg = RegInfo->getFrameRegister(MF);
736 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000737 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000738 assert(RegInfo->hasBasePointer(MF) &&
739 "VLAs and dynamic stack alignment, but missing base pointer!");
740 FrameReg = RegInfo->getBaseRegister();
741 }
742 return Offset;
743 }
744
745 // If there is a frame pointer, use it when we can.
746 if (hasFP(MF) && AFI->hasStackFrame()) {
747 // Use frame pointer to reference fixed objects. Use it for locals if
748 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000749 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000750 FrameReg = RegInfo->getFrameRegister(MF);
751 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000752 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000753 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000754 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000755 // Try to use the frame pointer if we can, else use the base pointer
756 // since it's available. This is handy for the emergency spill slot, in
757 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000758 if (FPOffset >= -255 && FPOffset < 0) {
759 FrameReg = RegInfo->getFrameRegister(MF);
760 return FPOffset;
761 }
Evan Chengc0d20042011-04-22 01:42:52 +0000762 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000763 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000764 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000765 // ldr <rd>, [sp, #<imm8>]
766 // if at all possible to save space.
767 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
768 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000769 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000770 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000771 if (FPOffset >= -255 && FPOffset < 0) {
772 FrameReg = RegInfo->getFrameRegister(MF);
773 return FPOffset;
774 }
775 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
776 // Otherwise, use SP or FP, whichever is closer to the stack slot.
777 FrameReg = RegInfo->getFrameRegister(MF);
778 return FPOffset;
779 }
780 }
781 // Use the base pointer if we have one.
782 if (RegInfo->hasBasePointer(MF))
783 FrameReg = RegInfo->getBaseRegister();
784 return Offset;
785}
786
Bob Wilson657f2272011-01-13 21:10:12 +0000787int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
788 int FI) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000789 unsigned FrameReg;
790 return getFrameIndexReference(MF, FI, FrameReg);
791}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000792
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000793void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000794 MachineBasicBlock::iterator MI,
795 const std::vector<CalleeSavedInfo> &CSI,
796 unsigned StmOpc, unsigned StrOpc,
797 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000798 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000799 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000800 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000801 MachineFunction &MF = *MBB.getParent();
802 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
803
804 DebugLoc DL;
805 if (MI != MBB.end()) DL = MI->getDebugLoc();
806
Evan Chengc27c9562010-12-07 19:59:34 +0000807 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000808 unsigned i = CSI.size();
809 while (i != 0) {
810 unsigned LastReg = 0;
811 for (; i != 0; --i) {
812 unsigned Reg = CSI[i-1].getReg();
Tim Northoverd6a729b2014-01-06 14:28:05 +0000813 if (!(Func)(Reg, STI.isTargetMachO())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000814
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000815 // D-registers in the aligned area DPRCS2 are NOT spilled here.
816 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
817 continue;
818
Evan Cheng775ead32010-12-07 23:08:38 +0000819 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000820 // @llvm.returnaddress is called. If LR is returned for
821 // @llvm.returnaddress then it's already added to the function and
822 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000823 bool isKill = true;
824 if (Reg == ARM::LR) {
825 if (MF.getFrameInfo()->isReturnAddressTaken() &&
826 MF.getRegInfo().isLiveIn(Reg))
827 isKill = false;
828 }
829
830 if (isKill)
831 MBB.addLiveIn(Reg);
832
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000833 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000834 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000835 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000836 if (NoGap && LastReg && LastReg != Reg-1)
837 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000838 LastReg = Reg;
839 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000840 }
841
Jim Grosbach5fccad82010-12-09 18:31:13 +0000842 if (Regs.empty())
843 continue;
844 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000845 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000846 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000847 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000848 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
849 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000850 } else if (Regs.size() == 1) {
851 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
852 ARM::SP)
853 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000854 .addReg(ARM::SP).setMIFlags(MIFlags)
855 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000856 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000857 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000858 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000859
860 // Put any subsequent vpush instructions before this one: they will refer to
861 // higher register numbers so need to be pushed first in order to preserve
862 // monotonicity.
863 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000864 }
Evan Cheng775ead32010-12-07 23:08:38 +0000865}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000866
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000867void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000868 MachineBasicBlock::iterator MI,
869 const std::vector<CalleeSavedInfo> &CSI,
870 unsigned LdmOpc, unsigned LdrOpc,
871 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000872 bool(*Func)(unsigned, bool),
873 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000874 MachineFunction &MF = *MBB.getParent();
875 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
876 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
877 DebugLoc DL = MI->getDebugLoc();
Evan Chengd6093ff2011-01-25 01:28:33 +0000878 unsigned RetOpcode = MI->getOpcode();
879 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000880 RetOpcode == ARM::TCRETURNri);
Tim Northoverd8407452013-10-01 14:33:28 +0000881 bool isInterrupt =
882 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Evan Cheng775ead32010-12-07 23:08:38 +0000883
884 SmallVector<unsigned, 4> Regs;
885 unsigned i = CSI.size();
886 while (i != 0) {
887 unsigned LastReg = 0;
888 bool DeleteRet = false;
889 for (; i != 0; --i) {
890 unsigned Reg = CSI[i-1].getReg();
Tim Northoverd6a729b2014-01-06 14:28:05 +0000891 if (!(Func)(Reg, STI.isTargetMachO())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +0000892
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000893 // The aligned reloads from area DPRCS2 are not inserted here.
894 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
895 continue;
896
Tim Northoverd8407452013-10-01 14:33:28 +0000897 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
898 STI.hasV5TOps()) {
Evan Cheng775ead32010-12-07 23:08:38 +0000899 Reg = ARM::PC;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000900 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Evan Cheng775ead32010-12-07 23:08:38 +0000901 // Fold the return instruction into the LDM.
902 DeleteRet = true;
903 }
904
Evan Cheng9d54ae62010-12-08 06:29:02 +0000905 // If NoGap is true, pop consecutive registers and then leave the rest
906 // for other instructions. e.g.
907 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
908 if (NoGap && LastReg && LastReg != Reg-1)
909 break;
910
Evan Cheng775ead32010-12-07 23:08:38 +0000911 LastReg = Reg;
912 Regs.push_back(Reg);
913 }
914
Jim Grosbach5fccad82010-12-09 18:31:13 +0000915 if (Regs.empty())
916 continue;
917 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000918 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000919 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +0000920 .addReg(ARM::SP));
921 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
922 MIB.addReg(Regs[i], getDefRegState(true));
Andrew Trick6446bf72011-08-25 17:50:53 +0000923 if (DeleteRet) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +0000924 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +0000925 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +0000926 }
Evan Cheng775ead32010-12-07 23:08:38 +0000927 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000928 } else if (Regs.size() == 1) {
929 // If we adjusted the reg to PC from LR above, switch it back here. We
930 // only do that for LDM.
931 if (Regs[0] == ARM::PC)
932 Regs[0] = ARM::LR;
933 MachineInstrBuilder MIB =
934 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
935 .addReg(ARM::SP, RegState::Define)
936 .addReg(ARM::SP);
937 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
938 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +0000939 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +0000940 MIB.addReg(0);
941 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
942 } else
943 MIB.addImm(4);
944 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000945 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000946 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000947
948 // Put any subsequent vpop instructions after this one: they will refer to
949 // higher register numbers so need to be popped afterwards.
950 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +0000951 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000952}
953
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000954/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000955/// starting from d8. Also insert stack realignment code and leave the stack
956/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000957static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
958 MachineBasicBlock::iterator MI,
959 unsigned NumAlignedDPRCS2Regs,
960 const std::vector<CalleeSavedInfo> &CSI,
961 const TargetRegisterInfo *TRI) {
962 MachineFunction &MF = *MBB.getParent();
963 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
964 DebugLoc DL = MI->getDebugLoc();
965 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
966 MachineFrameInfo &MFI = *MF.getFrameInfo();
967
968 // Mark the D-register spill slots as properly aligned. Since MFI computes
969 // stack slot layout backwards, this can actually mean that the d-reg stack
970 // slot offsets can be wrong. The offset for d8 will always be correct.
971 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
972 unsigned DNum = CSI[i].getReg() - ARM::D8;
973 if (DNum >= 8)
974 continue;
975 int FI = CSI[i].getFrameIdx();
976 // The even-numbered registers will be 16-byte aligned, the odd-numbered
977 // registers will be 8-byte aligned.
978 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
979
980 // The stack slot for D8 needs to be maximally aligned because this is
981 // actually the point where we align the stack pointer. MachineFrameInfo
982 // computes all offsets relative to the incoming stack pointer which is a
983 // bit weird when realigning the stack. Any extra padding for this
984 // over-alignment is not realized because the code inserted below adjusts
985 // the stack pointer by numregs * 8 before aligning the stack pointer.
986 if (DNum == 0)
987 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
988 }
989
990 // Move the stack pointer to the d8 spill slot, and align it at the same
991 // time. Leave the stack slot address in the scratch register r4.
992 //
993 // sub r4, sp, #numregs * 8
994 // bic r4, r4, #align - 1
995 // mov sp, r4
996 //
997 bool isThumb = AFI->isThumbFunction();
998 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
999 AFI->setShouldRestoreSPFromFP(true);
1000
1001 // sub r4, sp, #numregs * 8
1002 // The immediate is <= 64, so it doesn't need any special encoding.
1003 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1004 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1005 .addReg(ARM::SP)
1006 .addImm(8 * NumAlignedDPRCS2Regs)));
1007
1008 // bic r4, r4, #align-1
1009 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1010 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1011 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1012 .addReg(ARM::R4, RegState::Kill)
1013 .addImm(MaxAlign - 1)));
1014
1015 // mov sp, r4
1016 // The stack pointer must be adjusted before spilling anything, otherwise
1017 // the stack slots could be clobbered by an interrupt handler.
1018 // Leave r4 live, it is used below.
1019 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1020 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1021 .addReg(ARM::R4);
1022 MIB = AddDefaultPred(MIB);
1023 if (!isThumb)
1024 AddDefaultCC(MIB);
1025
1026 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1027 // r4 holds the stack slot address.
1028 unsigned NextReg = ARM::D8;
1029
1030 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1031 // The writeback is only needed when emitting two vst1.64 instructions.
1032 if (NumAlignedDPRCS2Regs >= 6) {
1033 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001034 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001035 MBB.addLiveIn(SupReg);
1036 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1037 ARM::R4)
1038 .addReg(ARM::R4, RegState::Kill).addImm(16)
1039 .addReg(NextReg)
1040 .addReg(SupReg, RegState::ImplicitKill));
1041 NextReg += 4;
1042 NumAlignedDPRCS2Regs -= 4;
1043 }
1044
1045 // We won't modify r4 beyond this point. It currently points to the next
1046 // register to be spilled.
1047 unsigned R4BaseReg = NextReg;
1048
1049 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1050 if (NumAlignedDPRCS2Regs >= 4) {
1051 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001052 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001053 MBB.addLiveIn(SupReg);
1054 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1055 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1056 .addReg(SupReg, RegState::ImplicitKill));
1057 NextReg += 4;
1058 NumAlignedDPRCS2Regs -= 4;
1059 }
1060
1061 // 16-byte aligned vst1.64 with 2 d-regs.
1062 if (NumAlignedDPRCS2Regs >= 2) {
1063 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001064 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001065 MBB.addLiveIn(SupReg);
1066 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001067 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001068 NextReg += 2;
1069 NumAlignedDPRCS2Regs -= 2;
1070 }
1071
1072 // Finally, use a vanilla vstr.64 for the odd last register.
1073 if (NumAlignedDPRCS2Regs) {
1074 MBB.addLiveIn(NextReg);
1075 // vstr.64 uses addrmode5 which has an offset scale of 4.
1076 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1077 .addReg(NextReg)
1078 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1079 }
1080
1081 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001082 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001083}
1084
1085/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1086/// iterator to the following instruction.
1087static MachineBasicBlock::iterator
1088skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1089 unsigned NumAlignedDPRCS2Regs) {
1090 // sub r4, sp, #numregs * 8
1091 // bic r4, r4, #align - 1
1092 // mov sp, r4
1093 ++MI; ++MI; ++MI;
1094 assert(MI->mayStore() && "Expecting spill instruction");
1095
1096 // These switches all fall through.
1097 switch(NumAlignedDPRCS2Regs) {
1098 case 7:
1099 ++MI;
1100 assert(MI->mayStore() && "Expecting spill instruction");
1101 default:
1102 ++MI;
1103 assert(MI->mayStore() && "Expecting spill instruction");
1104 case 1:
1105 case 2:
1106 case 4:
1107 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1108 ++MI;
1109 }
1110 return MI;
1111}
1112
1113/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1114/// starting from d8. These instructions are assumed to execute while the
1115/// stack is still aligned, unlike the code inserted by emitPopInst.
1116static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1117 MachineBasicBlock::iterator MI,
1118 unsigned NumAlignedDPRCS2Regs,
1119 const std::vector<CalleeSavedInfo> &CSI,
1120 const TargetRegisterInfo *TRI) {
1121 MachineFunction &MF = *MBB.getParent();
1122 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1123 DebugLoc DL = MI->getDebugLoc();
1124 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1125
1126 // Find the frame index assigned to d8.
1127 int D8SpillFI = 0;
1128 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1129 if (CSI[i].getReg() == ARM::D8) {
1130 D8SpillFI = CSI[i].getFrameIdx();
1131 break;
1132 }
1133
1134 // Materialize the address of the d8 spill slot into the scratch register r4.
1135 // This can be fairly complicated if the stack frame is large, so just use
1136 // the normal frame index elimination mechanism to do it. This code runs as
1137 // the initial part of the epilog where the stack and base pointers haven't
1138 // been changed yet.
1139 bool isThumb = AFI->isThumbFunction();
1140 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1141
1142 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1143 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1144 .addFrameIndex(D8SpillFI).addImm(0)));
1145
1146 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1147 unsigned NextReg = ARM::D8;
1148
1149 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1150 if (NumAlignedDPRCS2Regs >= 6) {
1151 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001152 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001153 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1154 .addReg(ARM::R4, RegState::Define)
1155 .addReg(ARM::R4, RegState::Kill).addImm(16)
1156 .addReg(SupReg, RegState::ImplicitDefine));
1157 NextReg += 4;
1158 NumAlignedDPRCS2Regs -= 4;
1159 }
1160
1161 // We won't modify r4 beyond this point. It currently points to the next
1162 // register to be spilled.
1163 unsigned R4BaseReg = NextReg;
1164
1165 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1166 if (NumAlignedDPRCS2Regs >= 4) {
1167 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001168 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001169 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1170 .addReg(ARM::R4).addImm(16)
1171 .addReg(SupReg, RegState::ImplicitDefine));
1172 NextReg += 4;
1173 NumAlignedDPRCS2Regs -= 4;
1174 }
1175
1176 // 16-byte aligned vld1.64 with 2 d-regs.
1177 if (NumAlignedDPRCS2Regs >= 2) {
1178 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001179 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001180 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1181 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001182 NextReg += 2;
1183 NumAlignedDPRCS2Regs -= 2;
1184 }
1185
1186 // Finally, use a vanilla vldr.64 for the remaining odd register.
1187 if (NumAlignedDPRCS2Regs)
1188 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1189 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1190
1191 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001192 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001193}
1194
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001195bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001196 MachineBasicBlock::iterator MI,
1197 const std::vector<CalleeSavedInfo> &CSI,
1198 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001199 if (CSI.empty())
1200 return false;
1201
1202 MachineFunction &MF = *MBB.getParent();
1203 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001204
1205 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001206 unsigned PushOneOpc = AFI->isThumbFunction() ?
1207 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001208 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001209 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1210 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001211 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001212 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001213 MachineInstr::FrameSetup);
1214 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001215 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1216
1217 // The code above does not insert spill code for the aligned DPRCS2 registers.
1218 // The stack realignment code will be inserted between the push instructions
1219 // and these spills.
1220 if (NumAlignedDPRCS2Regs)
1221 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001222
1223 return true;
1224}
1225
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001226bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001227 MachineBasicBlock::iterator MI,
1228 const std::vector<CalleeSavedInfo> &CSI,
1229 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001230 if (CSI.empty())
1231 return false;
1232
1233 MachineFunction &MF = *MBB.getParent();
1234 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001235 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001236 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1237
1238 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1239 // registers. Do that here instead.
1240 if (NumAlignedDPRCS2Regs)
1241 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001242
1243 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001244 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001245 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001246 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1247 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001248 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001249 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001250 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001251 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001252
1253 return true;
1254}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001255
1256// FIXME: Make generic?
1257static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1258 const ARMBaseInstrInfo &TII) {
1259 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001260 for (auto &MBB : MF) {
1261 for (auto &MI : MBB)
1262 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001263 }
1264 return FnSize;
1265}
1266
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001267/// estimateRSStackSizeLimit - Look at each instruction that references stack
1268/// frames and return the stack size limit beyond which some of these
1269/// instructions will require a scratch register during their expansion later.
1270// FIXME: Move to TII?
1271static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001272 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001273 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1274 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001275 for (auto &MBB : MF) {
1276 for (auto &MI : MBB) {
1277 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1278 if (!MI.getOperand(i).isFI())
1279 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001280
1281 // When using ADDri to get the address of a stack object, 255 is the
1282 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001283 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001284 Limit = std::min(Limit, (1U << 8) - 1);
1285 break;
1286 }
1287
1288 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001289 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001290 case ARMII::AddrMode3:
1291 case ARMII::AddrModeT2_i8:
1292 Limit = std::min(Limit, (1U << 8) - 1);
1293 break;
1294 case ARMII::AddrMode5:
1295 case ARMII::AddrModeT2_i8s4:
1296 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1297 break;
1298 case ARMII::AddrModeT2_i12:
1299 // i12 supports only positive offset so these will be converted to
1300 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1301 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1302 Limit = std::min(Limit, (1U << 8) - 1);
1303 break;
1304 case ARMII::AddrMode4:
1305 case ARMII::AddrMode6:
1306 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1307 // immediate offset for stack references.
1308 return 0;
1309 default:
1310 break;
1311 }
1312 break; // At most one FI per instruction
1313 }
1314 }
1315 }
1316
1317 return Limit;
1318}
1319
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001320// In functions that realign the stack, it can be an advantage to spill the
1321// callee-saved vector registers after realigning the stack. The vst1 and vld1
1322// instructions take alignment hints that can improve performance.
1323//
1324static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1325 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1326 if (!SpillAlignedNEONRegs)
1327 return;
1328
1329 // Naked functions don't spill callee-saved registers.
Bill Wendling698e84f2012-12-30 10:32:01 +00001330 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1331 Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001332 return;
1333
1334 // We are planning to use NEON instructions vst1 / vld1.
1335 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1336 return;
1337
1338 // Don't bother if the default stack alignment is sufficiently high.
1339 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1340 return;
1341
1342 // Aligned spills require stack realignment.
1343 const ARMBaseRegisterInfo *RegInfo =
1344 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1345 if (!RegInfo->canRealignStack(MF))
1346 return;
1347
1348 // We always spill contiguous d-registers starting from d8. Count how many
1349 // needs spilling. The register allocator will almost always use the
1350 // callee-saved registers in order, but it can happen that there are holes in
1351 // the range. Registers above the hole will be spilled to the standard DPRCS
1352 // area.
1353 MachineRegisterInfo &MRI = MF.getRegInfo();
1354 unsigned NumSpills = 0;
1355 for (; NumSpills < 8; ++NumSpills)
Jakob Stoklund Olesen07364422012-10-17 18:44:18 +00001356 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001357 break;
1358
1359 // Don't do this for just one d-register. It's not worth it.
1360 if (NumSpills < 2)
1361 return;
1362
1363 // Spill the first NumSpills D-registers after realigning the stack.
1364 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1365
1366 // A scratch register is required for the vst1 / vld1 instructions.
1367 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1368}
1369
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001370void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001371ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +00001372 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001373 // This tells PEI to spill the FP as if it is any other callee-save register
1374 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1375 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1376 // to combine multiple loads / stores.
1377 bool CanEliminateFrame = true;
1378 bool CS1Spilled = false;
1379 bool LRSpilled = false;
1380 unsigned NumGPRSpills = 0;
1381 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1382 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1383 const ARMBaseRegisterInfo *RegInfo =
1384 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1385 const ARMBaseInstrInfo &TII =
1386 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1387 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1388 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001389 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001390 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1391
1392 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1393 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001394 // since it's not always possible to restore sp from fp in a single
1395 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001396 // FIXME: It will be better just to find spare register here.
1397 if (AFI->isThumb2Function() &&
1398 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001399 MRI.setPhysRegUsed(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001400
Evan Cheng572756a2011-01-16 05:14:33 +00001401 if (AFI->isThumb1OnlyFunction()) {
1402 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001403 if (AFI->getArgRegsSaveSize() > 0)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001404 MRI.setPhysRegUsed(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001405
Jim Grosbachdca85312011-06-13 21:18:25 +00001406 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1407 // for sure what the stack size will be, but for this, an estimate is good
1408 // enough. If there anything changes it, it'll be a spill, which implies
1409 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001410 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001411 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001412 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001413 if (MFI->hasVarSizedObjects() || StackSize > 508)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001414 MRI.setPhysRegUsed(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001415 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001416
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001417 // See if we can spill vector registers to aligned stack.
1418 checkNumAlignedDPRCS2Regs(MF);
1419
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001420 // Spill the BasePtr if it's used.
1421 if (RegInfo->hasBasePointer(MF))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001422 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001423
1424 // Don't spill FP if the frame can be eliminated. This is determined
1425 // by scanning the callee-save registers to see if any is used.
Craig Topper840beec2014-04-04 05:16:06 +00001426 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001427 for (unsigned i = 0; CSRegs[i]; ++i) {
1428 unsigned Reg = CSRegs[i];
1429 bool Spilled = false;
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001430 if (MRI.isPhysRegUsed(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001431 Spilled = true;
1432 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001433 }
1434
Craig Topperc7242e02012-04-20 07:30:17 +00001435 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001436 continue;
1437
1438 if (Spilled) {
1439 NumGPRSpills++;
1440
Tim Northoverd6a729b2014-01-06 14:28:05 +00001441 if (!STI.isTargetMachO()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001442 if (Reg == ARM::LR)
1443 LRSpilled = true;
1444 CS1Spilled = true;
1445 continue;
1446 }
1447
1448 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1449 switch (Reg) {
1450 case ARM::LR:
1451 LRSpilled = true;
1452 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001453 case ARM::R0: case ARM::R1:
1454 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001455 case ARM::R4: case ARM::R5:
1456 case ARM::R6: case ARM::R7:
1457 CS1Spilled = true;
1458 break;
1459 default:
1460 break;
1461 }
1462 } else {
Tim Northoverd6a729b2014-01-06 14:28:05 +00001463 if (!STI.isTargetMachO()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001464 UnspilledCS1GPRs.push_back(Reg);
1465 continue;
1466 }
1467
1468 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001469 case ARM::R0: case ARM::R1:
1470 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001471 case ARM::R4: case ARM::R5:
1472 case ARM::R6: case ARM::R7:
1473 case ARM::LR:
1474 UnspilledCS1GPRs.push_back(Reg);
1475 break;
1476 default:
1477 UnspilledCS2GPRs.push_back(Reg);
1478 break;
1479 }
1480 }
1481 }
1482
1483 bool ForceLRSpill = false;
1484 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1485 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1486 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1487 // use of BL to implement far jump. If it turns out that it's not needed
1488 // then the branch fix up path will undo it.
1489 if (FnSize >= (1 << 11)) {
1490 CanEliminateFrame = false;
1491 ForceLRSpill = true;
1492 }
1493 }
1494
1495 // If any of the stack slot references may be out of range of an immediate
1496 // offset, make sure a register (or a spill slot) is available for the
1497 // register scavenger. Note that if we're indexing off the frame pointer, the
1498 // effective stack size is 4 bytes larger since the FP points to the stack
1499 // slot of the previous FP. Also, if we have variable sized objects in the
1500 // function, stack slot references will often be negative, and some of
1501 // our instructions are positive-offset only, so conservatively consider
1502 // that case to want a spill slot (or register) as well. Similarly, if
1503 // the function adjusts the stack pointer during execution and the
1504 // adjustments aren't already part of our stack size estimate, our offset
1505 // calculations may be off, so be conservative.
1506 // FIXME: We could add logic to be more precise about negative offsets
1507 // and which instructions will need a scratch register for them. Is it
1508 // worth the effort and added fragility?
1509 bool BigStack =
1510 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001511 (MFI->estimateStackSize(MF) +
1512 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001513 estimateRSStackSizeLimit(MF, this)))
1514 || MFI->hasVarSizedObjects()
1515 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1516
1517 bool ExtraCSSpill = false;
1518 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1519 AFI->setHasStackFrame(true);
1520
1521 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1522 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1523 if (!LRSpilled && CS1Spilled) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001524 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001525 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001526 SmallVectorImpl<unsigned>::iterator LRPos;
1527 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1528 (unsigned)ARM::LR);
1529 if (LRPos != UnspilledCS1GPRs.end())
1530 UnspilledCS1GPRs.erase(LRPos);
1531
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001532 ForceLRSpill = false;
1533 ExtraCSSpill = true;
1534 }
1535
1536 if (hasFP(MF)) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001537 MRI.setPhysRegUsed(FramePtr);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001538 NumGPRSpills++;
1539 }
1540
1541 // If stack and double are 8-byte aligned and we are spilling an odd number
1542 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1543 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001544 unsigned TargetAlign = getStackAlignment();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001545 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1546 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1547 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1548 unsigned Reg = UnspilledCS1GPRs[i];
1549 // Don't spill high register if the function is thumb1
1550 if (!AFI->isThumb1OnlyFunction() ||
1551 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001552 MRI.setPhysRegUsed(Reg);
1553 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001554 ExtraCSSpill = true;
1555 break;
1556 }
1557 }
1558 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1559 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001560 MRI.setPhysRegUsed(Reg);
1561 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001562 ExtraCSSpill = true;
1563 }
1564 }
1565
1566 // Estimate if we might need to scavenge a register at some point in order
1567 // to materialize a stack offset. If so, either spill one additional
1568 // callee-saved register or reserve a special spill slot to facilitate
1569 // register scavenging. Thumb1 needs a spill slot for stack pointer
1570 // adjustments also, even when the frame itself is small.
1571 if (BigStack && !ExtraCSSpill) {
1572 // If any non-reserved CS register isn't spilled, just spill one or two
1573 // extra. That should take care of it!
1574 unsigned NumExtras = TargetAlign / 4;
1575 SmallVector<unsigned, 2> Extras;
1576 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1577 unsigned Reg = UnspilledCS1GPRs.back();
1578 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001579 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001580 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1581 Reg == ARM::LR)) {
1582 Extras.push_back(Reg);
1583 NumExtras--;
1584 }
1585 }
1586 // For non-Thumb1 functions, also check for hi-reg CS registers
1587 if (!AFI->isThumb1OnlyFunction()) {
1588 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1589 unsigned Reg = UnspilledCS2GPRs.back();
1590 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001591 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001592 Extras.push_back(Reg);
1593 NumExtras--;
1594 }
1595 }
1596 }
1597 if (Extras.size() && NumExtras == 0) {
1598 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001599 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001600 }
1601 } else if (!AFI->isThumb1OnlyFunction()) {
1602 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1603 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001604 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001605 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001606 RC->getAlignment(),
1607 false));
1608 }
1609 }
1610 }
1611
1612 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001613 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001614 AFI->setLRIsSpilledForFarJump(true);
1615 }
1616}
Eli Bendersky8da87162013-02-21 20:05:00 +00001617
1618
1619void ARMFrameLowering::
1620eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1621 MachineBasicBlock::iterator I) const {
1622 const ARMBaseInstrInfo &TII =
1623 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1624 if (!hasReservedCallFrame(MF)) {
1625 // If we have alloca, convert as follows:
1626 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1627 // ADJCALLSTACKUP -> add, sp, sp, amount
1628 MachineInstr *Old = I;
1629 DebugLoc dl = Old->getDebugLoc();
1630 unsigned Amount = Old->getOperand(0).getImm();
1631 if (Amount != 0) {
1632 // We need to keep the stack aligned properly. To do this, we round the
1633 // amount of space needed for the outgoing arguments up to the next
1634 // alignment boundary.
1635 unsigned Align = getStackAlignment();
1636 Amount = (Amount+Align-1)/Align*Align;
1637
1638 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1639 assert(!AFI->isThumb1OnlyFunction() &&
1640 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1641 bool isARM = !AFI->isThumbFunction();
1642
1643 // Replace the pseudo instruction with a new instruction...
1644 unsigned Opc = Old->getOpcode();
1645 int PIdx = Old->findFirstPredOperandIdx();
1646 ARMCC::CondCodes Pred = (PIdx == -1)
1647 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1648 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1649 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1650 unsigned PredReg = Old->getOperand(2).getReg();
1651 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1652 Pred, PredReg);
1653 } else {
1654 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1655 unsigned PredReg = Old->getOperand(3).getReg();
1656 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1657 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1658 Pred, PredReg);
1659 }
1660 }
1661 }
1662 MBB.erase(I);
1663}
1664
Oliver Stannardb14c6252014-04-02 16:10:33 +00001665/// Get the minimum constant for ARM that is greater than or equal to the
1666/// argument. In ARM, constants can have any value that can be produced by
1667/// rotating an 8-bit value to the right by an even number of bits within a
1668/// 32-bit word.
1669static uint32_t alignToARMConstant(uint32_t Value) {
1670 unsigned Shifted = 0;
1671
1672 if (Value == 0)
1673 return 0;
1674
1675 while (!(Value & 0xC0000000)) {
1676 Value = Value << 2;
1677 Shifted += 2;
1678 }
1679
1680 bool Carry = (Value & 0x00FFFFFF);
1681 Value = ((Value & 0xFF000000) >> 24) + Carry;
1682
1683 if (Value & 0x0000100)
1684 Value = Value & 0x000001FC;
1685
1686 if (Shifted > 24)
1687 Value = Value >> (Shifted - 24);
1688 else
1689 Value = Value << (24 - Shifted);
1690
1691 return Value;
1692}
1693
1694// The stack limit in the TCB is set to this many bytes above the actual
1695// stack limit.
1696static const uint64_t kSplitStackAvailable = 256;
1697
1698// Adjust the function prologue to enable split stacks. This currently only
1699// supports android and linux.
1700//
1701// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1702// must be well defined in order to allow for consistent implementations of the
1703// __morestack helper function. The ABI is also not a normal ABI in that it
1704// doesn't follow the normal calling conventions because this allows the
1705// prologue of each function to be optimized further.
1706//
1707// Currently, the ABI looks like (when calling __morestack)
1708//
1709// * r4 holds the minimum stack size requested for this function call
1710// * r5 holds the stack size of the arguments to the function
1711// * the beginning of the function is 3 instructions after the call to
1712// __morestack
1713//
1714// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1715// place the arguments on to the new stack, and the 3-instruction knowledge to
1716// jump directly to the body of the function when working on the new stack.
1717//
1718// An old (and possibly no longer compatible) implementation of __morestack for
1719// ARM can be found at [1].
1720//
1721// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1722void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1723 unsigned Opcode;
1724 unsigned CFIIndex;
1725 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1726 bool Thumb = ST->isThumb();
1727
1728 // Sadly, this currently doesn't support varargs, platforms other than
1729 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1730 if (MF.getFunction()->isVarArg())
1731 report_fatal_error("Segmented stacks do not support vararg functions.");
1732 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001733 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001734
1735 MachineBasicBlock &prologueMBB = MF.front();
1736 MachineFrameInfo *MFI = MF.getFrameInfo();
1737 MachineModuleInfo &MMI = MF.getMMI();
1738 MCContext &Context = MMI.getContext();
1739 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1740 const ARMBaseInstrInfo &TII =
1741 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1742 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1743 DebugLoc DL;
1744
1745 // Use R4 and R5 as scratch registers.
1746 // We save R4 and R5 before use and restore them before leaving the function.
1747 unsigned ScratchReg0 = ARM::R4;
1748 unsigned ScratchReg1 = ARM::R5;
1749 uint64_t AlignedStackSize;
1750
1751 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1752 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1753 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1754 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1755 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1756
1757 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1758 e = prologueMBB.livein_end();
1759 i != e; ++i) {
1760 AllocMBB->addLiveIn(*i);
1761 GetMBB->addLiveIn(*i);
1762 McrMBB->addLiveIn(*i);
1763 PrevStackMBB->addLiveIn(*i);
1764 PostStackMBB->addLiveIn(*i);
1765 }
1766
1767 MF.push_front(PostStackMBB);
1768 MF.push_front(AllocMBB);
1769 MF.push_front(GetMBB);
1770 MF.push_front(McrMBB);
1771 MF.push_front(PrevStackMBB);
1772
1773 // The required stack size that is aligned to ARM constant criterion.
1774 uint64_t StackSize = MFI->getStackSize();
1775
1776 AlignedStackSize = alignToARMConstant(StackSize);
1777
1778 // When the frame size is less than 256 we just compare the stack
1779 // boundary directly to the value of the stack pointer, per gcc.
1780 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1781
1782 // We will use two of the callee save registers as scratch registers so we
1783 // need to save those registers onto the stack.
1784 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1785 // requested and arguments for __morestack().
1786 // SR0: Scratch Register #0
1787 // SR1: Scratch Register #1
1788 // push {SR0, SR1}
1789 if (Thumb) {
1790 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1791 .addReg(ScratchReg0).addReg(ScratchReg1);
1792 } else {
1793 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1794 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1795 .addReg(ScratchReg0).addReg(ScratchReg1);
1796 }
1797
1798 // Emit the relevant DWARF information about the change in stack pointer as
1799 // well as where to find both r4 and r5 (the callee-save registers)
1800 CFIIndex =
1801 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1802 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1803 .addCFIIndex(CFIIndex);
1804 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1805 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1806 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1807 .addCFIIndex(CFIIndex);
1808 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1809 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1810 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1811 .addCFIIndex(CFIIndex);
1812
1813 // mov SR1, sp
1814 if (Thumb) {
1815 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1816 .addReg(ARM::SP));
1817 } else if (CompareStackPointer) {
1818 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1819 .addReg(ARM::SP)).addReg(0);
1820 }
1821
1822 // sub SR1, sp, #StackSize
1823 if (!CompareStackPointer && Thumb) {
1824 AddDefaultPred(
1825 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1826 .addReg(ScratchReg1).addImm(AlignedStackSize));
1827 } else if (!CompareStackPointer) {
1828 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1829 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1830 }
1831
1832 if (Thumb && ST->isThumb1Only()) {
1833 unsigned PCLabelId = ARMFI->createPICLabelUId();
1834 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001835 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001836 MachineConstantPool *MCP = MF.getConstantPool();
1837 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1838
1839 // ldr SR0, [pc, offset(STACK_LIMIT)]
1840 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1841 .addConstantPoolIndex(CPI));
1842
1843 // ldr SR0, [SR0]
1844 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1845 .addReg(ScratchReg0).addImm(0));
1846 } else {
1847 // Get TLS base address from the coprocessor
1848 // mrc p15, #0, SR0, c13, c0, #3
1849 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1850 .addImm(15)
1851 .addImm(0)
1852 .addImm(13)
1853 .addImm(0)
1854 .addImm(3));
1855
1856 // Use the last tls slot on android and a private field of the TCP on linux.
1857 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1858 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1859
1860 // Get the stack limit from the right offset
1861 // ldr SR0, [sr0, #4 * TlsOffset]
1862 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1863 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1864 }
1865
1866 // Compare stack limit with stack size requested.
1867 // cmp SR0, SR1
1868 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1869 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1870 .addReg(ScratchReg0)
1871 .addReg(ScratchReg1));
1872
1873 // This jump is taken if StackLimit < SP - stack required.
1874 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1875 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1876 .addImm(ARMCC::LO)
1877 .addReg(ARM::CPSR);
1878
1879
1880 // Calling __morestack(StackSize, Size of stack arguments).
1881 // __morestack knows that the stack size requested is in SR0(r4)
1882 // and amount size of stack arguments is in SR1(r5).
1883
1884 // Pass first argument for the __morestack by Scratch Register #0.
1885 // The amount size of stack required
1886 if (Thumb) {
1887 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1888 ScratchReg0)).addImm(AlignedStackSize));
1889 } else {
1890 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1891 .addImm(AlignedStackSize)).addReg(0);
1892 }
1893 // Pass second argument for the __morestack by Scratch Register #1.
1894 // The amount size of stack consumed to save function arguments.
1895 if (Thumb) {
1896 AddDefaultPred(
1897 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1898 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1899 } else {
1900 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1901 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1902 .addReg(0);
1903 }
1904
1905 // push {lr} - Save return address of this function.
1906 if (Thumb) {
1907 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1908 .addReg(ARM::LR);
1909 } else {
1910 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1911 .addReg(ARM::SP, RegState::Define)
1912 .addReg(ARM::SP))
1913 .addReg(ARM::LR);
1914 }
1915
1916 // Emit the DWARF info about the change in stack as well as where to find the
1917 // previous link register
1918 CFIIndex =
1919 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1920 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1921 .addCFIIndex(CFIIndex);
1922 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1923 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1924 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1925 .addCFIIndex(CFIIndex);
1926
1927 // Call __morestack().
1928 if (Thumb) {
1929 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1930 .addExternalSymbol("__morestack");
1931 } else {
1932 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1933 .addExternalSymbol("__morestack");
1934 }
1935
1936 // pop {lr} - Restore return address of this original function.
1937 if (Thumb) {
1938 if (ST->isThumb1Only()) {
1939 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1940 .addReg(ScratchReg0);
1941 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1942 .addReg(ScratchReg0));
1943 } else {
1944 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1945 .addReg(ARM::LR, RegState::Define)
1946 .addReg(ARM::SP, RegState::Define)
1947 .addReg(ARM::SP)
1948 .addImm(4));
1949 }
1950 } else {
1951 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1952 .addReg(ARM::SP, RegState::Define)
1953 .addReg(ARM::SP))
1954 .addReg(ARM::LR);
1955 }
1956
1957 // Restore SR0 and SR1 in case of __morestack() was called.
1958 // __morestack() will skip PostStackMBB block so we need to restore
1959 // scratch registers from here.
1960 // pop {SR0, SR1}
1961 if (Thumb) {
1962 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1963 .addReg(ScratchReg0)
1964 .addReg(ScratchReg1);
1965 } else {
1966 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1967 .addReg(ARM::SP, RegState::Define)
1968 .addReg(ARM::SP))
1969 .addReg(ScratchReg0)
1970 .addReg(ScratchReg1);
1971 }
1972
1973 // Update the CFA offset now that we've popped
1974 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1975 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1976 .addCFIIndex(CFIIndex);
1977
1978 // bx lr - Return from this function.
1979 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
1980 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
1981
1982 // Restore SR0 and SR1 in case of __morestack() was not called.
1983 // pop {SR0, SR1}
1984 if (Thumb) {
1985 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
1986 .addReg(ScratchReg0)
1987 .addReg(ScratchReg1);
1988 } else {
1989 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
1990 .addReg(ARM::SP, RegState::Define)
1991 .addReg(ARM::SP))
1992 .addReg(ScratchReg0)
1993 .addReg(ScratchReg1);
1994 }
1995
1996 // Update the CFA offset now that we've popped
1997 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1998 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1999 .addCFIIndex(CFIIndex);
2000
2001 // Tell debuggers that r4 and r5 are now the same as they were in the
2002 // previous function, that they're the "Same Value".
2003 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2004 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2005 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2006 .addCFIIndex(CFIIndex);
2007 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2008 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2009 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2010 .addCFIIndex(CFIIndex);
2011
2012 // Organizing MBB lists
2013 PostStackMBB->addSuccessor(&prologueMBB);
2014
2015 AllocMBB->addSuccessor(PostStackMBB);
2016
2017 GetMBB->addSuccessor(PostStackMBB);
2018 GetMBB->addSuccessor(AllocMBB);
2019
2020 McrMBB->addSuccessor(GetMBB);
2021
2022 PrevStackMBB->addSuccessor(McrMBB);
2023
2024#ifdef XDEBUG
2025 MF.verify();
2026#endif
2027}