blob: 6888ae994c58f27098a96edd2601f83462738854 [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"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000028#include "llvm/MC/MCContext.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000029#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetOptions.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000031
32using namespace llvm;
33
Benjamin Kramer9fceb902012-02-24 22:09:25 +000034static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000035SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000036 cl::desc("Align ARM NEON spills in prolog and epilog"));
37
38static MachineBasicBlock::iterator
39skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
41
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000042/// hasFP - Return true if the specified function should have a dedicated frame
43/// pointer register. This is true if the function has variable sized allocas
44/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000045bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000046 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
47
Evan Cheng801d98b2012-01-04 01:55:04 +000048 // iOS requires FP not to be clobbered for backtracing purpose.
49 if (STI.isTargetIOS())
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000050 return true;
51
52 const MachineFrameInfo *MFI = MF.getFrameInfo();
53 // Always eliminate non-leaf frame pointers.
Nick Lewycky50f02cb2011-12-02 22:16:29 +000054 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
55 MFI->hasCalls()) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000056 RegInfo->needsStackRealignment(MF) ||
57 MFI->hasVarSizedObjects() ||
58 MFI->isFrameAddressTaken());
59}
60
Bob Wilson657f2272011-01-13 21:10:12 +000061/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
62/// not required, we reserve argument space for call sites in the function
63/// immediately on entry to the current function. This eliminates the need for
64/// add/sub sp brackets around call sites. Returns true if the call frame is
65/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000066bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000067 const MachineFrameInfo *FFI = MF.getFrameInfo();
68 unsigned CFSize = FFI->getMaxCallFrameSize();
69 // It's not always a good idea to include the call frame as part of the
70 // stack frame. ARM (especially Thumb) has small immediate offset to
71 // address the stack frame. So a large call frame can cause poor codegen
72 // and may even makes it impossible to scavenge a register.
73 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
74 return false;
75
76 return !MF.getFrameInfo()->hasVarSizedObjects();
77}
78
Bob Wilson657f2272011-01-13 21:10:12 +000079/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
80/// call frame pseudos can be simplified. Unlike most targets, having a FP
81/// is not sufficient here since we still may reference some objects via SP
82/// even when FP is available in Thumb2 mode.
83bool
84ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000085 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
86}
87
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000088static bool isCSRestore(MachineInstr *MI,
89 const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +000090 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +000091 // Integer spill area is handled with "pop".
Tim Northover93bcc662013-11-08 17:18:07 +000092 if (isPopOpcode(MI->getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +000093 // The first two operands are predicates. The last two are
94 // imp-def and imp-use of SP. Check everything in between.
95 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
96 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
97 return false;
98 return true;
99 }
Owen Anderson2aedba62011-07-26 20:54:26 +0000100 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
101 MI->getOpcode() == ARM::LDR_POST_REG ||
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000102 MI->getOpcode() == ARM::t2LDR_POST) &&
103 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
104 MI->getOperand(1).getReg() == ARM::SP)
105 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000106
107 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000108}
109
Tim Northoverc9432eb2013-11-04 23:04:15 +0000110static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
112 const ARMBaseInstrInfo &TII, unsigned DestReg,
113 unsigned SrcReg, int NumBytes,
114 unsigned MIFlags = MachineInstr::NoFlags,
115 ARMCC::CondCodes Pred = ARMCC::AL,
116 unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000117 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000118 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000119 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000120 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000121 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000122 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000123}
124
Tim Northoverc9432eb2013-11-04 23:04:15 +0000125static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
126 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
127 const ARMBaseInstrInfo &TII, int NumBytes,
128 unsigned MIFlags = MachineInstr::NoFlags,
129 ARMCC::CondCodes Pred = ARMCC::AL,
130 unsigned PredReg = 0) {
131 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
132 MIFlags, Pred, PredReg);
133}
134
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000135static int sizeOfSPAdjustment(const MachineInstr *MI) {
136 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
137 int count = 0;
138 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
139 // pred) so the list starts at 4.
140 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
141 count += 8;
142 return count;
143}
144
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000145static bool WindowsRequiresStackProbe(const MachineFunction &MF,
146 size_t StackSizeInBytes) {
147 const MachineFrameInfo *MFI = MF.getFrameInfo();
148 if (MFI->getStackProtectorIndex() > 0)
149 return StackSizeInBytes >= 4080;
150 return StackSizeInBytes >= 4096;
151}
152
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000153void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000154 MachineBasicBlock &MBB = MF.front();
155 MachineBasicBlock::iterator MBBI = MBB.begin();
156 MachineFrameInfo *MFI = MF.getFrameInfo();
157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000158 MachineModuleInfo &MMI = MF.getMMI();
159 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000160 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000161 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000162 const ARMBaseRegisterInfo *RegInfo =
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000163 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000164 const ARMBaseInstrInfo &TII =
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000165 *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000166 assert(!AFI->isThumb1OnlyFunction() &&
167 "This emitPrologue does not support Thumb1!");
168 bool isARM = !AFI->isThumbFunction();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000169 unsigned Align = TM.getFrameLowering()->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000170 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000171 unsigned NumBytes = MFI->getStackSize();
172 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
173 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
174 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000175 int CFAOffset = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000176
177 // Determine the sizes of each callee-save spill areas and record which frame
178 // belongs to which callee-save spill areas.
179 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
180 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000181 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000182
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000183 // All calls are tail calls in GHC calling conv, and functions have no
184 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000185 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
186 return;
187
Oliver Stannardd55e1152014-03-05 15:25:27 +0000188 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000189 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000190 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000191 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000192 CFAOffset -= ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000193 unsigned CFIIndex = MMI.addFrameInst(
194 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
195 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
196 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000197 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000198
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000199 if (!AFI->hasStackFrame() &&
200 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000201 if (NumBytes - ArgRegsSaveSize != 0) {
202 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000203 MachineInstr::FrameSetup);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000204 CFAOffset -= NumBytes - ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000205 unsigned CFIIndex = MMI.addFrameInst(
206 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
207 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
208 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000209 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000210 return;
211 }
212
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000213 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000214 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
215 unsigned Reg = CSI[i].getReg();
216 int FI = CSI[i].getFrameIdx();
217 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000218 case ARM::R8:
219 case ARM::R9:
220 case ARM::R10:
221 case ARM::R11:
222 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000223 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000224 GPRCS2Size += 4;
225 break;
226 }
227 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000228 case ARM::R0:
229 case ARM::R1:
230 case ARM::R2:
231 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000232 case ARM::R4:
233 case ARM::R5:
234 case ARM::R6:
235 case ARM::R7:
236 case ARM::LR:
237 if (Reg == FramePtr)
238 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000239 GPRCS1Size += 4;
240 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000241 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000242 // This is a DPR. Exclude the aligned DPRCS2 spills.
243 if (Reg == ARM::D8)
244 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000245 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000246 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000247 }
248 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000249
Eric Christopherb006fc92010-11-18 19:40:05 +0000250 // Move past area 1.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000251 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
252 DPRCSPush;
Tim Northover93bcc662013-11-08 17:18:07 +0000253 if (GPRCS1Size > 0)
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000254 GPRCS1Push = LastPush = MBBI++;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000255
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000256 // Determine starting offsets of spill areas.
Tim Northoverc9432eb2013-11-04 23:04:15 +0000257 bool HasFP = hasFP(MF);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000258 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
259 + GPRCS2Size + DPRCSSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000260 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
261 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
Tim Northover93bcc662013-11-08 17:18:07 +0000262 int FramePtrOffsetInPush = 0;
263 if (HasFP) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000264 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
265 + GPRCS1Size + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000266 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
267 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000268 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000269 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
270 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
271 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
272
Tim Northoverc9432eb2013-11-04 23:04:15 +0000273 // Move past area 2.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000274 if (GPRCS2Size > 0)
275 GPRCS2Push = LastPush = MBBI++;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000276
Eric Christopherb006fc92010-11-18 19:40:05 +0000277 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000278 if (DPRCSSize > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000279 DPRCSPush = MBBI;
Evan Cheng70d29632011-02-25 00:24:46 +0000280 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000281 // instructions in the prologue.
Evan Cheng70d29632011-02-25 00:24:46 +0000282 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
Tim Northover93bcc662013-11-08 17:18:07 +0000283 LastPush = MBBI++;
Evan Cheng70d29632011-02-25 00:24:46 +0000284 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000285
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000286 // Move past the aligned DPRCS2 area.
287 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
288 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
289 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
290 // leaves the stack pointer pointing to the DPRCS2 area.
291 //
292 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
293 NumBytes += MFI->getObjectOffset(D8SpillFI);
294 } else
295 NumBytes = DPRCSOffset;
296
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000297 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
298 uint32_t NumWords = NumBytes >> 2;
299
300 if (NumWords < 65536)
301 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000302 .addImm(NumWords)
303 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000304 else
305 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000306 .addImm(NumWords)
307 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000308
309 switch (TM.getCodeModel()) {
310 case CodeModel::Small:
311 case CodeModel::Medium:
312 case CodeModel::Default:
313 case CodeModel::Kernel:
314 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
315 .addImm((unsigned)ARMCC::AL).addReg(0)
316 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000317 .addReg(ARM::R4, RegState::Implicit)
318 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000319 break;
320 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000321 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000322 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000323 .addExternalSymbol("__chkstk")
324 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000325
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000326 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
327 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000328 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000329 .addReg(ARM::R4, RegState::Implicit)
330 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000331 break;
332 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000333
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:
Tim Northover86f60b72014-05-30 13:23:06 +0000383 if (STI.isTargetDarwin())
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000384 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:
Tim Northover86f60b72014-05-30 13:23:06 +0000448 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000449 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 Northover86f60b72014-05-30 13:23:06 +0000813 if (!(Func)(Reg, STI.isTargetDarwin())) 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 Northover86f60b72014-05-30 13:23:06 +0000891 if (!(Func)(Reg, STI.isTargetDarwin())) 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 Northover86f60b72014-05-30 13:23:06 +00001441 if (!STI.isTargetDarwin()) {
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 Northover86f60b72014-05-30 13:23:06 +00001463 if (!STI.isTargetDarwin()) {
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);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001538 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1539 FramePtr);
1540 if (FPPos != UnspilledCS1GPRs.end())
1541 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001542 NumGPRSpills++;
1543 }
1544
1545 // If stack and double are 8-byte aligned and we are spilling an odd number
1546 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1547 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001548 unsigned TargetAlign = getStackAlignment();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001549 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1550 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1551 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1552 unsigned Reg = UnspilledCS1GPRs[i];
1553 // Don't spill high register if the function is thumb1
1554 if (!AFI->isThumb1OnlyFunction() ||
1555 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001556 MRI.setPhysRegUsed(Reg);
1557 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001558 ExtraCSSpill = true;
1559 break;
1560 }
1561 }
1562 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1563 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001564 MRI.setPhysRegUsed(Reg);
1565 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001566 ExtraCSSpill = true;
1567 }
1568 }
1569
1570 // Estimate if we might need to scavenge a register at some point in order
1571 // to materialize a stack offset. If so, either spill one additional
1572 // callee-saved register or reserve a special spill slot to facilitate
1573 // register scavenging. Thumb1 needs a spill slot for stack pointer
1574 // adjustments also, even when the frame itself is small.
1575 if (BigStack && !ExtraCSSpill) {
1576 // If any non-reserved CS register isn't spilled, just spill one or two
1577 // extra. That should take care of it!
1578 unsigned NumExtras = TargetAlign / 4;
1579 SmallVector<unsigned, 2> Extras;
1580 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1581 unsigned Reg = UnspilledCS1GPRs.back();
1582 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001583 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001584 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1585 Reg == ARM::LR)) {
1586 Extras.push_back(Reg);
1587 NumExtras--;
1588 }
1589 }
1590 // For non-Thumb1 functions, also check for hi-reg CS registers
1591 if (!AFI->isThumb1OnlyFunction()) {
1592 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1593 unsigned Reg = UnspilledCS2GPRs.back();
1594 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001595 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001596 Extras.push_back(Reg);
1597 NumExtras--;
1598 }
1599 }
1600 }
1601 if (Extras.size() && NumExtras == 0) {
1602 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001603 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001604 }
1605 } else if (!AFI->isThumb1OnlyFunction()) {
1606 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1607 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001608 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001609 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001610 RC->getAlignment(),
1611 false));
1612 }
1613 }
1614 }
1615
1616 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001617 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001618 AFI->setLRIsSpilledForFarJump(true);
1619 }
1620}
Eli Bendersky8da87162013-02-21 20:05:00 +00001621
1622
1623void ARMFrameLowering::
1624eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1625 MachineBasicBlock::iterator I) const {
1626 const ARMBaseInstrInfo &TII =
1627 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1628 if (!hasReservedCallFrame(MF)) {
1629 // If we have alloca, convert as follows:
1630 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1631 // ADJCALLSTACKUP -> add, sp, sp, amount
1632 MachineInstr *Old = I;
1633 DebugLoc dl = Old->getDebugLoc();
1634 unsigned Amount = Old->getOperand(0).getImm();
1635 if (Amount != 0) {
1636 // We need to keep the stack aligned properly. To do this, we round the
1637 // amount of space needed for the outgoing arguments up to the next
1638 // alignment boundary.
1639 unsigned Align = getStackAlignment();
1640 Amount = (Amount+Align-1)/Align*Align;
1641
1642 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1643 assert(!AFI->isThumb1OnlyFunction() &&
1644 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1645 bool isARM = !AFI->isThumbFunction();
1646
1647 // Replace the pseudo instruction with a new instruction...
1648 unsigned Opc = Old->getOpcode();
1649 int PIdx = Old->findFirstPredOperandIdx();
1650 ARMCC::CondCodes Pred = (PIdx == -1)
1651 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1652 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1653 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1654 unsigned PredReg = Old->getOperand(2).getReg();
1655 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1656 Pred, PredReg);
1657 } else {
1658 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1659 unsigned PredReg = Old->getOperand(3).getReg();
1660 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1661 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1662 Pred, PredReg);
1663 }
1664 }
1665 }
1666 MBB.erase(I);
1667}
1668
Oliver Stannardb14c6252014-04-02 16:10:33 +00001669/// Get the minimum constant for ARM that is greater than or equal to the
1670/// argument. In ARM, constants can have any value that can be produced by
1671/// rotating an 8-bit value to the right by an even number of bits within a
1672/// 32-bit word.
1673static uint32_t alignToARMConstant(uint32_t Value) {
1674 unsigned Shifted = 0;
1675
1676 if (Value == 0)
1677 return 0;
1678
1679 while (!(Value & 0xC0000000)) {
1680 Value = Value << 2;
1681 Shifted += 2;
1682 }
1683
1684 bool Carry = (Value & 0x00FFFFFF);
1685 Value = ((Value & 0xFF000000) >> 24) + Carry;
1686
1687 if (Value & 0x0000100)
1688 Value = Value & 0x000001FC;
1689
1690 if (Shifted > 24)
1691 Value = Value >> (Shifted - 24);
1692 else
1693 Value = Value << (24 - Shifted);
1694
1695 return Value;
1696}
1697
1698// The stack limit in the TCB is set to this many bytes above the actual
1699// stack limit.
1700static const uint64_t kSplitStackAvailable = 256;
1701
1702// Adjust the function prologue to enable split stacks. This currently only
1703// supports android and linux.
1704//
1705// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1706// must be well defined in order to allow for consistent implementations of the
1707// __morestack helper function. The ABI is also not a normal ABI in that it
1708// doesn't follow the normal calling conventions because this allows the
1709// prologue of each function to be optimized further.
1710//
1711// Currently, the ABI looks like (when calling __morestack)
1712//
1713// * r4 holds the minimum stack size requested for this function call
1714// * r5 holds the stack size of the arguments to the function
1715// * the beginning of the function is 3 instructions after the call to
1716// __morestack
1717//
1718// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1719// place the arguments on to the new stack, and the 3-instruction knowledge to
1720// jump directly to the body of the function when working on the new stack.
1721//
1722// An old (and possibly no longer compatible) implementation of __morestack for
1723// ARM can be found at [1].
1724//
1725// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1726void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1727 unsigned Opcode;
1728 unsigned CFIIndex;
1729 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1730 bool Thumb = ST->isThumb();
1731
1732 // Sadly, this currently doesn't support varargs, platforms other than
1733 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1734 if (MF.getFunction()->isVarArg())
1735 report_fatal_error("Segmented stacks do not support vararg functions.");
1736 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001737 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001738
1739 MachineBasicBlock &prologueMBB = MF.front();
1740 MachineFrameInfo *MFI = MF.getFrameInfo();
1741 MachineModuleInfo &MMI = MF.getMMI();
1742 MCContext &Context = MMI.getContext();
1743 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1744 const ARMBaseInstrInfo &TII =
1745 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1746 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1747 DebugLoc DL;
1748
Tim Northoverf9e798b2014-05-22 13:03:43 +00001749 uint64_t StackSize = MFI->getStackSize();
1750
1751 // Do not generate a prologue for functions with a stack of size zero
1752 if (StackSize == 0)
1753 return;
1754
Oliver Stannardb14c6252014-04-02 16:10:33 +00001755 // Use R4 and R5 as scratch registers.
1756 // We save R4 and R5 before use and restore them before leaving the function.
1757 unsigned ScratchReg0 = ARM::R4;
1758 unsigned ScratchReg1 = ARM::R5;
1759 uint64_t AlignedStackSize;
1760
1761 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1762 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1763 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1764 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1765 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1766
1767 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1768 e = prologueMBB.livein_end();
1769 i != e; ++i) {
1770 AllocMBB->addLiveIn(*i);
1771 GetMBB->addLiveIn(*i);
1772 McrMBB->addLiveIn(*i);
1773 PrevStackMBB->addLiveIn(*i);
1774 PostStackMBB->addLiveIn(*i);
1775 }
1776
1777 MF.push_front(PostStackMBB);
1778 MF.push_front(AllocMBB);
1779 MF.push_front(GetMBB);
1780 MF.push_front(McrMBB);
1781 MF.push_front(PrevStackMBB);
1782
1783 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00001784 AlignedStackSize = alignToARMConstant(StackSize);
1785
1786 // When the frame size is less than 256 we just compare the stack
1787 // boundary directly to the value of the stack pointer, per gcc.
1788 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1789
1790 // We will use two of the callee save registers as scratch registers so we
1791 // need to save those registers onto the stack.
1792 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1793 // requested and arguments for __morestack().
1794 // SR0: Scratch Register #0
1795 // SR1: Scratch Register #1
1796 // push {SR0, SR1}
1797 if (Thumb) {
1798 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1799 .addReg(ScratchReg0).addReg(ScratchReg1);
1800 } else {
1801 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1802 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1803 .addReg(ScratchReg0).addReg(ScratchReg1);
1804 }
1805
1806 // Emit the relevant DWARF information about the change in stack pointer as
1807 // well as where to find both r4 and r5 (the callee-save registers)
1808 CFIIndex =
1809 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1810 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1811 .addCFIIndex(CFIIndex);
1812 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1813 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1814 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1815 .addCFIIndex(CFIIndex);
1816 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1817 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1818 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1819 .addCFIIndex(CFIIndex);
1820
1821 // mov SR1, sp
1822 if (Thumb) {
1823 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1824 .addReg(ARM::SP));
1825 } else if (CompareStackPointer) {
1826 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1827 .addReg(ARM::SP)).addReg(0);
1828 }
1829
1830 // sub SR1, sp, #StackSize
1831 if (!CompareStackPointer && Thumb) {
1832 AddDefaultPred(
1833 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1834 .addReg(ScratchReg1).addImm(AlignedStackSize));
1835 } else if (!CompareStackPointer) {
1836 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1837 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1838 }
1839
1840 if (Thumb && ST->isThumb1Only()) {
1841 unsigned PCLabelId = ARMFI->createPICLabelUId();
1842 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001843 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001844 MachineConstantPool *MCP = MF.getConstantPool();
1845 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1846
1847 // ldr SR0, [pc, offset(STACK_LIMIT)]
1848 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1849 .addConstantPoolIndex(CPI));
1850
1851 // ldr SR0, [SR0]
1852 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1853 .addReg(ScratchReg0).addImm(0));
1854 } else {
1855 // Get TLS base address from the coprocessor
1856 // mrc p15, #0, SR0, c13, c0, #3
1857 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1858 .addImm(15)
1859 .addImm(0)
1860 .addImm(13)
1861 .addImm(0)
1862 .addImm(3));
1863
1864 // Use the last tls slot on android and a private field of the TCP on linux.
1865 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1866 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1867
1868 // Get the stack limit from the right offset
1869 // ldr SR0, [sr0, #4 * TlsOffset]
1870 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1871 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1872 }
1873
1874 // Compare stack limit with stack size requested.
1875 // cmp SR0, SR1
1876 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1877 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1878 .addReg(ScratchReg0)
1879 .addReg(ScratchReg1));
1880
1881 // This jump is taken if StackLimit < SP - stack required.
1882 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1883 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1884 .addImm(ARMCC::LO)
1885 .addReg(ARM::CPSR);
1886
1887
1888 // Calling __morestack(StackSize, Size of stack arguments).
1889 // __morestack knows that the stack size requested is in SR0(r4)
1890 // and amount size of stack arguments is in SR1(r5).
1891
1892 // Pass first argument for the __morestack by Scratch Register #0.
1893 // The amount size of stack required
1894 if (Thumb) {
1895 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1896 ScratchReg0)).addImm(AlignedStackSize));
1897 } else {
1898 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1899 .addImm(AlignedStackSize)).addReg(0);
1900 }
1901 // Pass second argument for the __morestack by Scratch Register #1.
1902 // The amount size of stack consumed to save function arguments.
1903 if (Thumb) {
1904 AddDefaultPred(
1905 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1906 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1907 } else {
1908 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1909 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1910 .addReg(0);
1911 }
1912
1913 // push {lr} - Save return address of this function.
1914 if (Thumb) {
1915 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1916 .addReg(ARM::LR);
1917 } else {
1918 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1919 .addReg(ARM::SP, RegState::Define)
1920 .addReg(ARM::SP))
1921 .addReg(ARM::LR);
1922 }
1923
1924 // Emit the DWARF info about the change in stack as well as where to find the
1925 // previous link register
1926 CFIIndex =
1927 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1928 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1929 .addCFIIndex(CFIIndex);
1930 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1931 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1932 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1933 .addCFIIndex(CFIIndex);
1934
1935 // Call __morestack().
1936 if (Thumb) {
1937 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1938 .addExternalSymbol("__morestack");
1939 } else {
1940 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1941 .addExternalSymbol("__morestack");
1942 }
1943
1944 // pop {lr} - Restore return address of this original function.
1945 if (Thumb) {
1946 if (ST->isThumb1Only()) {
1947 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1948 .addReg(ScratchReg0);
1949 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1950 .addReg(ScratchReg0));
1951 } else {
1952 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1953 .addReg(ARM::LR, RegState::Define)
1954 .addReg(ARM::SP, RegState::Define)
1955 .addReg(ARM::SP)
1956 .addImm(4));
1957 }
1958 } else {
1959 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1960 .addReg(ARM::SP, RegState::Define)
1961 .addReg(ARM::SP))
1962 .addReg(ARM::LR);
1963 }
1964
1965 // Restore SR0 and SR1 in case of __morestack() was called.
1966 // __morestack() will skip PostStackMBB block so we need to restore
1967 // scratch registers from here.
1968 // pop {SR0, SR1}
1969 if (Thumb) {
1970 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1971 .addReg(ScratchReg0)
1972 .addReg(ScratchReg1);
1973 } else {
1974 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1975 .addReg(ARM::SP, RegState::Define)
1976 .addReg(ARM::SP))
1977 .addReg(ScratchReg0)
1978 .addReg(ScratchReg1);
1979 }
1980
1981 // Update the CFA offset now that we've popped
1982 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1983 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1984 .addCFIIndex(CFIIndex);
1985
1986 // bx lr - Return from this function.
1987 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
1988 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
1989
1990 // Restore SR0 and SR1 in case of __morestack() was not called.
1991 // pop {SR0, SR1}
1992 if (Thumb) {
1993 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
1994 .addReg(ScratchReg0)
1995 .addReg(ScratchReg1);
1996 } else {
1997 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
1998 .addReg(ARM::SP, RegState::Define)
1999 .addReg(ARM::SP))
2000 .addReg(ScratchReg0)
2001 .addReg(ScratchReg1);
2002 }
2003
2004 // Update the CFA offset now that we've popped
2005 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2006 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2007 .addCFIIndex(CFIIndex);
2008
2009 // Tell debuggers that r4 and r5 are now the same as they were in the
2010 // previous function, that they're the "Same Value".
2011 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2012 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2013 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2014 .addCFIIndex(CFIIndex);
2015 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2016 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2017 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2018 .addCFIIndex(CFIIndex);
2019
2020 // Organizing MBB lists
2021 PostStackMBB->addSuccessor(&prologueMBB);
2022
2023 AllocMBB->addSuccessor(PostStackMBB);
2024
2025 GetMBB->addSuccessor(PostStackMBB);
2026 GetMBB->addSuccessor(AllocMBB);
2027
2028 McrMBB->addSuccessor(GetMBB);
2029
2030 PrevStackMBB->addSuccessor(McrMBB);
2031
2032#ifdef XDEBUG
2033 MF.verify();
2034#endif
2035}