blob: 476a12fa287f9d90245f85dc86a883b9abaa9c3f [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
Eric Christopher45fb7b62014-06-26 19:29:59 +000042ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
44 STI(sti) {}
45
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000046bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
47 // iOS always has a FP for backtracking, force other targets to keep their FP
48 // when doing FastISel. The emitted code is currently superior, and in cases
49 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
50 return TargetFrameLowering::noFramePointerElim(MF) ||
51 MF.getSubtarget<ARMSubtarget>().useFastISel();
52}
53
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000054/// hasFP - Return true if the specified function should have a dedicated frame
55/// pointer register. This is true if the function has variable sized allocas
56/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000057bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +000058 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000059
Evan Cheng801d98b2012-01-04 01:55:04 +000060 // iOS requires FP not to be clobbered for backtracing purpose.
61 if (STI.isTargetIOS())
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000062 return true;
63
64 const MachineFrameInfo *MFI = MF.getFrameInfo();
65 // Always eliminate non-leaf frame pointers.
Nick Lewycky50f02cb2011-12-02 22:16:29 +000066 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
67 MFI->hasCalls()) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000068 RegInfo->needsStackRealignment(MF) ||
69 MFI->hasVarSizedObjects() ||
70 MFI->isFrameAddressTaken());
71}
72
Bob Wilson657f2272011-01-13 21:10:12 +000073/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
74/// not required, we reserve argument space for call sites in the function
75/// immediately on entry to the current function. This eliminates the need for
76/// add/sub sp brackets around call sites. Returns true if the call frame is
77/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000078bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000079 const MachineFrameInfo *FFI = MF.getFrameInfo();
80 unsigned CFSize = FFI->getMaxCallFrameSize();
81 // It's not always a good idea to include the call frame as part of the
82 // stack frame. ARM (especially Thumb) has small immediate offset to
83 // address the stack frame. So a large call frame can cause poor codegen
84 // and may even makes it impossible to scavenge a register.
85 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
86 return false;
87
88 return !MF.getFrameInfo()->hasVarSizedObjects();
89}
90
Bob Wilson657f2272011-01-13 21:10:12 +000091/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
92/// call frame pseudos can be simplified. Unlike most targets, having a FP
93/// is not sufficient here since we still may reference some objects via SP
94/// even when FP is available in Thumb2 mode.
95bool
96ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000097 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
98}
99
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000100static bool isCSRestore(MachineInstr *MI,
101 const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000102 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000103 // Integer spill area is handled with "pop".
Tim Northover93bcc662013-11-08 17:18:07 +0000104 if (isPopOpcode(MI->getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000105 // The first two operands are predicates. The last two are
106 // imp-def and imp-use of SP. Check everything in between.
107 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
108 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
109 return false;
110 return true;
111 }
Owen Anderson2aedba62011-07-26 20:54:26 +0000112 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
113 MI->getOpcode() == ARM::LDR_POST_REG ||
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000114 MI->getOpcode() == ARM::t2LDR_POST) &&
115 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
116 MI->getOperand(1).getReg() == ARM::SP)
117 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000118
119 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000120}
121
Tim Northoverc9432eb2013-11-04 23:04:15 +0000122static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
123 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
124 const ARMBaseInstrInfo &TII, unsigned DestReg,
125 unsigned SrcReg, int NumBytes,
126 unsigned MIFlags = MachineInstr::NoFlags,
127 ARMCC::CondCodes Pred = ARMCC::AL,
128 unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000129 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000130 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000131 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000132 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000133 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000134 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000135}
136
Tim Northoverc9432eb2013-11-04 23:04:15 +0000137static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
138 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
139 const ARMBaseInstrInfo &TII, int NumBytes,
140 unsigned MIFlags = MachineInstr::NoFlags,
141 ARMCC::CondCodes Pred = ARMCC::AL,
142 unsigned PredReg = 0) {
143 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
144 MIFlags, Pred, PredReg);
145}
146
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000147static int sizeOfSPAdjustment(const MachineInstr *MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000148 int RegSize;
149 switch (MI->getOpcode()) {
150 case ARM::VSTMDDB_UPD:
151 RegSize = 8;
152 break;
153 case ARM::STMDB_UPD:
154 case ARM::t2STMDB_UPD:
155 RegSize = 4;
156 break;
157 case ARM::t2STR_PRE:
158 case ARM::STR_PRE_IMM:
159 return 4;
160 default:
161 llvm_unreachable("Unknown push or pop like instruction");
162 }
163
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000164 int count = 0;
165 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
166 // pred) so the list starts at 4.
167 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000168 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000169 return count;
170}
171
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000172static bool WindowsRequiresStackProbe(const MachineFunction &MF,
173 size_t StackSizeInBytes) {
174 const MachineFrameInfo *MFI = MF.getFrameInfo();
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000175 const Function *F = MF.getFunction();
176 unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
177 if (F->hasFnAttribute("stack-probe-size"))
178 F->getFnAttribute("stack-probe-size")
179 .getValueAsString()
180 .getAsInteger(0, StackProbeSize);
181 return StackSizeInBytes >= StackProbeSize;
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000182}
183
Tim Northover603d3162014-11-14 22:45:33 +0000184namespace {
185struct StackAdjustingInsts {
186 struct InstInfo {
187 MachineBasicBlock::iterator I;
188 unsigned SPAdjust;
189 bool BeforeFPSet;
190 };
191
192 SmallVector<InstInfo, 4> Insts;
193
194 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
195 bool BeforeFPSet = false) {
196 InstInfo Info = {I, SPAdjust, BeforeFPSet};
197 Insts.push_back(Info);
198 }
199
200 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
201 auto Info = std::find_if(Insts.begin(), Insts.end(),
202 [&](InstInfo &Info) { return Info.I == I; });
203 assert(Info != Insts.end() && "invalid sp adjusting instruction");
204 Info->SPAdjust += ExtraBytes;
205 }
206
207 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
208 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
209 unsigned CFAOffset = 0;
210 for (auto &Info : Insts) {
211 if (HasFP && !Info.BeforeFPSet)
212 return;
213
214 CFAOffset -= Info.SPAdjust;
215 unsigned CFIIndex = MMI.addFrameInst(
216 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
217 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000218 TII.get(TargetOpcode::CFI_INSTRUCTION))
219 .addCFIIndex(CFIIndex)
220 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000221 }
222 }
223};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000224}
Tim Northover603d3162014-11-14 22:45:33 +0000225
Kristof Beyls933de7a2015-01-08 15:09:14 +0000226/// Emit an instruction sequence that will align the address in
227/// register Reg by zero-ing out the lower bits. For versions of the
228/// architecture that support Neon, this must be done in a single
229/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
230/// single instruction. That function only gets called when optimizing
231/// spilling of D registers on a core with the Neon instruction set
232/// present.
233static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
234 const TargetInstrInfo &TII,
235 MachineBasicBlock &MBB,
236 MachineBasicBlock::iterator MBBI,
237 DebugLoc DL, const unsigned Reg,
238 const unsigned Alignment,
239 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000240 const ARMSubtarget &AST =
241 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000242 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
243 const unsigned AlignMask = Alignment - 1;
244 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
245 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
246 if (!AFI->isThumbFunction()) {
247 // if the BFC instruction is available, use that to zero the lower
248 // bits:
249 // bfc Reg, #0, log2(Alignment)
250 // otherwise use BIC, if the mask to zero the required number of bits
251 // can be encoded in the bic immediate field
252 // bic Reg, Reg, Alignment-1
253 // otherwise, emit
254 // lsr Reg, Reg, log2(Alignment)
255 // lsl Reg, Reg, log2(Alignment)
256 if (CanUseBFC) {
257 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
258 .addReg(Reg, RegState::Kill)
259 .addImm(~AlignMask));
260 } else if (AlignMask <= 255) {
261 AddDefaultCC(
262 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
263 .addReg(Reg, RegState::Kill)
264 .addImm(AlignMask)));
265 } else {
266 assert(!MustBeSingleInstruction &&
267 "Shouldn't call emitAligningInstructions demanding a single "
268 "instruction to be emitted for large stack alignment for a target "
269 "without BFC.");
270 AddDefaultCC(AddDefaultPred(
271 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
272 .addReg(Reg, RegState::Kill)
273 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
274 AddDefaultCC(AddDefaultPred(
275 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
276 .addReg(Reg, RegState::Kill)
277 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
278 }
279 } else {
280 // Since this is only reached for Thumb-2 targets, the BFC instruction
281 // should always be available.
282 assert(CanUseBFC);
283 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
284 .addReg(Reg, RegState::Kill)
285 .addImm(~AlignMask));
286 }
287}
288
Quentin Colombet61b305e2015-05-05 17:38:16 +0000289void ARMFrameLowering::emitPrologue(MachineFunction &MF,
290 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000291 MachineBasicBlock::iterator MBBI = MBB.begin();
292 MachineFrameInfo *MFI = MF.getFrameInfo();
293 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000294 MachineModuleInfo &MMI = MF.getMMI();
295 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000296 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000297 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000298 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
299 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000300 assert(!AFI->isThumb1OnlyFunction() &&
301 "This emitPrologue does not support Thumb1!");
302 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000303 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover8cda34f2015-03-11 18:54:22 +0000304 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000305 unsigned NumBytes = MFI->getStackSize();
306 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
307 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
308 unsigned FramePtr = RegInfo->getFrameRegister(MF);
309
310 // Determine the sizes of each callee-save spill areas and record which frame
311 // belongs to which callee-save spill areas.
312 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
313 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000314 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000315
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000316 // All calls are tail calls in GHC calling conv, and functions have no
317 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000318 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
319 return;
320
Tim Northover603d3162014-11-14 22:45:33 +0000321 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000322 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000323
Oliver Stannardd55e1152014-03-05 15:25:27 +0000324 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000325 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000326 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000327 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000328 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000329 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000330
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000331 if (!AFI->hasStackFrame() &&
332 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000333 if (NumBytes - ArgRegsSaveSize != 0) {
334 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000335 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000336 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
337 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000338 }
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000339 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000340 return;
341 }
342
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000343 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000344 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
345 unsigned Reg = CSI[i].getReg();
346 int FI = CSI[i].getFrameIdx();
347 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000348 case ARM::R8:
349 case ARM::R9:
350 case ARM::R10:
351 case ARM::R11:
352 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000353 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000354 GPRCS2Size += 4;
355 break;
356 }
357 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000358 case ARM::R0:
359 case ARM::R1:
360 case ARM::R2:
361 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000362 case ARM::R4:
363 case ARM::R5:
364 case ARM::R6:
365 case ARM::R7:
366 case ARM::LR:
367 if (Reg == FramePtr)
368 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000369 GPRCS1Size += 4;
370 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000371 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000372 // This is a DPR. Exclude the aligned DPRCS2 spills.
373 if (Reg == ARM::D8)
374 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000375 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000376 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000377 }
378 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000379
Eric Christopherb006fc92010-11-18 19:40:05 +0000380 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000381 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
382 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000383 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000384 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
385 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000386
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000387 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000388 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
389 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
390 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
391 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
392 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000393 int FramePtrOffsetInPush = 0;
394 if (HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000395 FramePtrOffsetInPush =
396 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000397 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
398 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000399 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000400 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
401 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
402 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
403
Tim Northoverc9432eb2013-11-04 23:04:15 +0000404 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000405 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000406 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000407 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
408 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000409
Tim Northover228c9432014-11-05 00:27:13 +0000410 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
411 // .cfi_offset operations will reflect that.
412 if (DPRGapSize) {
413 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Tim Northover603d3162014-11-14 22:45:33 +0000414 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
415 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
416 else {
Tim Northover228c9432014-11-05 00:27:13 +0000417 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
418 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000419 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
420 }
Tim Northover228c9432014-11-05 00:27:13 +0000421 }
422
Eric Christopherb006fc92010-11-18 19:40:05 +0000423 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000424 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000425 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000426 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000427 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
428 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000429 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000430 }
Evan Cheng70d29632011-02-25 00:24:46 +0000431 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000432
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000433 // Move past the aligned DPRCS2 area.
434 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
435 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
436 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
437 // leaves the stack pointer pointing to the DPRCS2 area.
438 //
439 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
440 NumBytes += MFI->getObjectOffset(D8SpillFI);
441 } else
442 NumBytes = DPRCSOffset;
443
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000444 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
445 uint32_t NumWords = NumBytes >> 2;
446
447 if (NumWords < 65536)
448 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000449 .addImm(NumWords)
450 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000451 else
452 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000453 .addImm(NumWords)
454 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000455
456 switch (TM.getCodeModel()) {
457 case CodeModel::Small:
458 case CodeModel::Medium:
459 case CodeModel::Default:
460 case CodeModel::Kernel:
461 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
462 .addImm((unsigned)ARMCC::AL).addReg(0)
463 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000464 .addReg(ARM::R4, RegState::Implicit)
465 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000466 break;
467 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000468 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000469 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000470 .addExternalSymbol("__chkstk")
471 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000472
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000473 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
474 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000475 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000476 .addReg(ARM::R4, RegState::Implicit)
477 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000478 break;
479 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000480
481 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
482 ARM::SP)
483 .addReg(ARM::SP, RegState::Define)
484 .addReg(ARM::R4, RegState::Kill)
485 .setMIFlags(MachineInstr::FrameSetup)));
486 NumBytes = 0;
487 }
488
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000489 if (NumBytes) {
490 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000491 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
492 tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000493 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
494 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000495 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
496 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000497 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
498 }
Tim Northover93bcc662013-11-08 17:18:07 +0000499
Evan Chengeb56dca2010-11-22 18:12:04 +0000500 if (HasFP && isARM)
501 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
502 // Note it's not safe to do this in Thumb2 mode because it would have
503 // taken two instructions:
504 // mov sp, r7
505 // sub sp, #24
506 // If an interrupt is taken between the two instructions, then sp is in
507 // an inconsistent state (pointing to the middle of callee-saved area).
508 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000509 AFI->setShouldRestoreSPFromFP(true);
510 }
511
Tim Northover603d3162014-11-14 22:45:33 +0000512 // Set FP to point to the stack slot that contains the previous FP.
513 // For iOS, FP is R7, which has now been stored in spill area 1.
514 // Otherwise, if this is not iOS, all the callee-saved registers go
515 // into spill area 1, including the FP in R11. In either case, it
516 // is in area one and the adjustment needs to take place just after
517 // that push.
518 if (HasFP) {
519 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
520 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
521 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
522 dl, TII, FramePtr, ARM::SP,
523 PushSize + FramePtrOffsetInPush,
524 MachineInstr::FrameSetup);
525 if (FramePtrOffsetInPush + PushSize != 0) {
526 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
527 nullptr, MRI->getDwarfRegNum(FramePtr, true),
528 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
529 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000530 .addCFIIndex(CFIIndex)
531 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000532 } else {
533 unsigned CFIIndex =
534 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
535 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
536 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000537 .addCFIIndex(CFIIndex)
538 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000539 }
540 }
541
542 // Now that the prologue's actual instructions are finalised, we can insert
543 // the necessary DWARF cf instructions to describe the situation. Start by
544 // recording where each register ended up:
545 if (GPRCS1Size > 0) {
546 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
547 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000548 for (const auto &Entry : CSI) {
549 unsigned Reg = Entry.getReg();
550 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000551 switch (Reg) {
552 case ARM::R8:
553 case ARM::R9:
554 case ARM::R10:
555 case ARM::R11:
556 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000557 if (STI.isTargetDarwin())
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000558 break;
559 // fallthrough
560 case ARM::R0:
561 case ARM::R1:
562 case ARM::R2:
563 case ARM::R3:
564 case ARM::R4:
565 case ARM::R5:
566 case ARM::R6:
567 case ARM::R7:
568 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000569 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
570 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
571 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000572 .addCFIIndex(CFIIndex)
573 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000574 break;
575 }
576 }
577 }
578
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000579 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000580 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000581 for (const auto &Entry : CSI) {
582 unsigned Reg = Entry.getReg();
583 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000584 switch (Reg) {
585 case ARM::R8:
586 case ARM::R9:
587 case ARM::R10:
588 case ARM::R11:
589 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000590 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000591 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000592 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000593 unsigned CFIIndex = MMI.addFrameInst(
594 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
595 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000596 .addCFIIndex(CFIIndex)
597 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000598 }
599 break;
600 }
601 }
602 }
603
604 if (DPRCSSize > 0) {
605 // Since vpush register list cannot have gaps, there may be multiple vpush
606 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000607 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000608 for (const auto &Entry : CSI) {
609 unsigned Reg = Entry.getReg();
610 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000611 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
612 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
613 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
614 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000615 unsigned CFIIndex = MMI.addFrameInst(
616 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000617 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000618 .addCFIIndex(CFIIndex)
619 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000620 }
621 }
622 }
623
Tim Northover603d3162014-11-14 22:45:33 +0000624 // Now we can emit descriptions of where the canonical frame address was
625 // throughout the process. If we have a frame pointer, it takes over the job
626 // half-way through, so only the first few .cfi_def_cfa_offset instructions
627 // actually get emitted.
628 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000629
Evan Chengeb56dca2010-11-22 18:12:04 +0000630 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000631 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
632 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000633
634 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
635 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000636 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000637 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
638
639 // If we need dynamic stack realignment, do it here. Be paranoid and make
640 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000641 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000642 // realigned.
643 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000644 unsigned MaxAlign = MFI->getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000645 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000646 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000647 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
648 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000649 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000650 // We cannot use sp as source/dest register here, thus we're using r4 to
651 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000652 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000653 // -- use emitAligningInstructions to produce best sequence to zero
654 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000655 // mov sp, r4
656 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000657 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000658 .addReg(ARM::SP, RegState::Kill));
659 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
660 false);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000661 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000662 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000663 }
664
665 AFI->setShouldRestoreSPFromFP(true);
666 }
667
668 // If we need a base pointer, set it up here. It's whatever the value
669 // of the stack pointer is at this point. Any variable size objects
670 // will be allocated after this, so we can still use the base pointer
671 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000672 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000673 if (RegInfo->hasBasePointer(MF)) {
674 if (isARM)
675 BuildMI(MBB, MBBI, dl,
676 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
677 .addReg(ARM::SP)
678 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
679 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000680 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000681 RegInfo->getBaseRegister())
682 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000683 }
684
685 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000686 // the sp from fp. We can assume there's an FP here since hasFP already
687 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000688 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000689 AFI->setShouldRestoreSPFromFP(true);
690}
691
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000692void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000693 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000694 MachineFrameInfo *MFI = MF.getFrameInfo();
695 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000696 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000697 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000698 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000699 assert(!AFI->isThumb1OnlyFunction() &&
700 "This emitEpilogue does not support Thumb1!");
701 bool isARM = !AFI->isThumbFunction();
702
Tim Northover8cda34f2015-03-11 18:54:22 +0000703 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000704 int NumBytes = (int)MFI->getStackSize();
705 unsigned FramePtr = RegInfo->getFrameRegister(MF);
706
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000707 // All calls are tail calls in GHC calling conv, and functions have no
708 // prologue/epilogue.
Quentin Colombet71a71482015-07-20 21:42:14 +0000709 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000710 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000711
712 // First put ourselves on the first (from top) terminator instructions.
713 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
714 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000715
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000716 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000717 if (NumBytes - ArgRegsSaveSize != 0)
718 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000719 } else {
720 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000721 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000722 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000723 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000724 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000725 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000726 if (!isCSRestore(MBBI, TII, CSRegs))
727 ++MBBI;
728 }
729
730 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000731 NumBytes -= (ArgRegsSaveSize +
732 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000733 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000734 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000735 AFI->getDPRCalleeSavedAreaSize());
736
737 // Reset SP based on frame pointer only if the stack frame extends beyond
738 // frame pointer stack slot or target is ELF and the function has FP.
739 if (AFI->shouldRestoreSPFromFP()) {
740 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
741 if (NumBytes) {
742 if (isARM)
743 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
744 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000745 else {
746 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000747 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000748 // mov sp, r7
749 // sub sp, #24
750 // This is bad, if an interrupt is taken after the mov, sp is in an
751 // inconsistent state.
752 // Use the first callee-saved register as a scratch register.
Matthias Braun02564862015-07-14 17:17:13 +0000753 assert(!MFI->getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000754 "No scratch register to restore SP from FP!");
755 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000756 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000757 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000758 ARM::SP)
759 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000760 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000761 } else {
762 // Thumb2 or ARM.
763 if (isARM)
764 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
765 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
766 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000767 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000768 ARM::SP)
769 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000770 }
Tim Northoverdee86042013-12-02 14:46:26 +0000771 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000772 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000773 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000774
Eric Christopherb006fc92010-11-18 19:40:05 +0000775 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000776 if (AFI->getDPRCalleeSavedAreaSize()) {
777 MBBI++;
778 // Since vpop register list cannot have gaps, there may be multiple vpop
779 // instructions in the epilogue.
780 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
781 MBBI++;
782 }
Tim Northover228c9432014-11-05 00:27:13 +0000783 if (AFI->getDPRCalleeSavedGapSize()) {
784 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
785 "unexpected DPR alignment gap");
786 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
787 }
788
Eric Christopherb006fc92010-11-18 19:40:05 +0000789 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
790 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000791 }
792
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000793 if (ArgRegsSaveSize)
794 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000795}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000796
Bob Wilson657f2272011-01-13 21:10:12 +0000797/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
798/// debug info. It's the same as what we use for resolving the code-gen
799/// references for now. FIXME: This can go wrong when references are
800/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000801int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000802ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000803 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000804 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
805}
806
807int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000808ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000809 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000810 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000811 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000812 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000813 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000814 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
815 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
816 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
817 bool isFixed = MFI->isFixedObjectIndex(FI);
818
819 FrameReg = ARM::SP;
820 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000821
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000822 // SP can move around if there are allocas. We may also lose track of SP
823 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000824 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000825
Anton Korobeynikov46877782010-11-20 15:59:32 +0000826 // When dynamically realigning the stack, use the frame pointer for
827 // parameters, and the stack/base pointer for locals.
828 if (RegInfo->needsStackRealignment(MF)) {
829 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
830 if (isFixed) {
831 FrameReg = RegInfo->getFrameRegister(MF);
832 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000833 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000834 assert(RegInfo->hasBasePointer(MF) &&
835 "VLAs and dynamic stack alignment, but missing base pointer!");
836 FrameReg = RegInfo->getBaseRegister();
837 }
838 return Offset;
839 }
840
841 // If there is a frame pointer, use it when we can.
842 if (hasFP(MF) && AFI->hasStackFrame()) {
843 // Use frame pointer to reference fixed objects. Use it for locals if
844 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000845 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000846 FrameReg = RegInfo->getFrameRegister(MF);
847 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000848 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000849 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000850 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000851 // Try to use the frame pointer if we can, else use the base pointer
852 // since it's available. This is handy for the emergency spill slot, in
853 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000854 if (FPOffset >= -255 && FPOffset < 0) {
855 FrameReg = RegInfo->getFrameRegister(MF);
856 return FPOffset;
857 }
Evan Chengc0d20042011-04-22 01:42:52 +0000858 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000859 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000860 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000861 // ldr <rd>, [sp, #<imm8>]
862 // if at all possible to save space.
863 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
864 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000865 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000866 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000867 if (FPOffset >= -255 && FPOffset < 0) {
868 FrameReg = RegInfo->getFrameRegister(MF);
869 return FPOffset;
870 }
871 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
872 // Otherwise, use SP or FP, whichever is closer to the stack slot.
873 FrameReg = RegInfo->getFrameRegister(MF);
874 return FPOffset;
875 }
876 }
877 // Use the base pointer if we have one.
878 if (RegInfo->hasBasePointer(MF))
879 FrameReg = RegInfo->getBaseRegister();
880 return Offset;
881}
882
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000883void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000884 MachineBasicBlock::iterator MI,
885 const std::vector<CalleeSavedInfo> &CSI,
886 unsigned StmOpc, unsigned StrOpc,
887 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000888 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000889 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000890 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000891 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000892 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000893
894 DebugLoc DL;
895 if (MI != MBB.end()) DL = MI->getDebugLoc();
896
Evan Chengc27c9562010-12-07 19:59:34 +0000897 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000898 unsigned i = CSI.size();
899 while (i != 0) {
900 unsigned LastReg = 0;
901 for (; i != 0; --i) {
902 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000903 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000904
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000905 // D-registers in the aligned area DPRCS2 are NOT spilled here.
906 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
907 continue;
908
Evan Cheng775ead32010-12-07 23:08:38 +0000909 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000910 // @llvm.returnaddress is called. If LR is returned for
911 // @llvm.returnaddress then it's already added to the function and
912 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000913 bool isKill = true;
914 if (Reg == ARM::LR) {
915 if (MF.getFrameInfo()->isReturnAddressTaken() &&
916 MF.getRegInfo().isLiveIn(Reg))
917 isKill = false;
918 }
919
920 if (isKill)
921 MBB.addLiveIn(Reg);
922
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000923 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000924 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000925 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000926 if (NoGap && LastReg && LastReg != Reg-1)
927 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000928 LastReg = Reg;
929 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000930 }
931
Jim Grosbach5fccad82010-12-09 18:31:13 +0000932 if (Regs.empty())
933 continue;
934 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000935 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000936 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000937 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000938 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
939 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000940 } else if (Regs.size() == 1) {
941 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
942 ARM::SP)
943 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000944 .addReg(ARM::SP).setMIFlags(MIFlags)
945 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000946 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000947 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000948 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000949
950 // Put any subsequent vpush instructions before this one: they will refer to
951 // higher register numbers so need to be pushed first in order to preserve
952 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +0000953 if (MI != MBB.begin())
954 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000955 }
Evan Cheng775ead32010-12-07 23:08:38 +0000956}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000957
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000958void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000959 MachineBasicBlock::iterator MI,
960 const std::vector<CalleeSavedInfo> &CSI,
961 unsigned LdmOpc, unsigned LdrOpc,
962 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000963 bool(*Func)(unsigned, bool),
964 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000965 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000966 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Evan Cheng775ead32010-12-07 23:08:38 +0000967 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +0000968 DebugLoc DL;
969 bool isTailCall = false;
970 bool isInterrupt = false;
971 if (MBB.end() != MI) {
972 DL = MI->getDebugLoc();
973 unsigned RetOpcode = MI->getOpcode();
974 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
975 isInterrupt =
976 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
977 }
Evan Cheng775ead32010-12-07 23:08:38 +0000978
979 SmallVector<unsigned, 4> Regs;
980 unsigned i = CSI.size();
981 while (i != 0) {
982 unsigned LastReg = 0;
983 bool DeleteRet = false;
984 for (; i != 0; --i) {
985 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000986 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +0000987
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000988 // The aligned reloads from area DPRCS2 are not inserted here.
989 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
990 continue;
991
Tim Northoverd8407452013-10-01 14:33:28 +0000992 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
993 STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +0000994 if (MBB.succ_empty()) {
995 Reg = ARM::PC;
996 DeleteRet = true;
997 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
998 } else
999 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001000 // Fold the return instruction into the LDM.
Evan Cheng775ead32010-12-07 23:08:38 +00001001 }
1002
Evan Cheng9d54ae62010-12-08 06:29:02 +00001003 // If NoGap is true, pop consecutive registers and then leave the rest
1004 // for other instructions. e.g.
1005 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1006 if (NoGap && LastReg && LastReg != Reg-1)
1007 break;
1008
Evan Cheng775ead32010-12-07 23:08:38 +00001009 LastReg = Reg;
1010 Regs.push_back(Reg);
1011 }
1012
Jim Grosbach5fccad82010-12-09 18:31:13 +00001013 if (Regs.empty())
1014 continue;
1015 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +00001016 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +00001017 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +00001018 .addReg(ARM::SP));
1019 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1020 MIB.addReg(Regs[i], getDefRegState(true));
Quentin Colombet71a71482015-07-20 21:42:14 +00001021 if (DeleteRet && MI != MBB.end()) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001022 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +00001023 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +00001024 }
Evan Cheng775ead32010-12-07 23:08:38 +00001025 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001026 } else if (Regs.size() == 1) {
1027 // If we adjusted the reg to PC from LR above, switch it back here. We
1028 // only do that for LDM.
1029 if (Regs[0] == ARM::PC)
1030 Regs[0] = ARM::LR;
1031 MachineInstrBuilder MIB =
1032 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1033 .addReg(ARM::SP, RegState::Define)
1034 .addReg(ARM::SP);
1035 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1036 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001037 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001038 MIB.addReg(0);
1039 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1040 } else
1041 MIB.addImm(4);
1042 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +00001043 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001044 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001045
1046 // Put any subsequent vpop instructions after this one: they will refer to
1047 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001048 if (MI != MBB.end())
1049 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001050 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001051}
1052
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001053/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001054/// starting from d8. Also insert stack realignment code and leave the stack
1055/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001056static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1057 MachineBasicBlock::iterator MI,
1058 unsigned NumAlignedDPRCS2Regs,
1059 const std::vector<CalleeSavedInfo> &CSI,
1060 const TargetRegisterInfo *TRI) {
1061 MachineFunction &MF = *MBB.getParent();
1062 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1063 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001064 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001065 MachineFrameInfo &MFI = *MF.getFrameInfo();
1066
1067 // Mark the D-register spill slots as properly aligned. Since MFI computes
1068 // stack slot layout backwards, this can actually mean that the d-reg stack
1069 // slot offsets can be wrong. The offset for d8 will always be correct.
1070 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1071 unsigned DNum = CSI[i].getReg() - ARM::D8;
1072 if (DNum >= 8)
1073 continue;
1074 int FI = CSI[i].getFrameIdx();
1075 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1076 // registers will be 8-byte aligned.
1077 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1078
1079 // The stack slot for D8 needs to be maximally aligned because this is
1080 // actually the point where we align the stack pointer. MachineFrameInfo
1081 // computes all offsets relative to the incoming stack pointer which is a
1082 // bit weird when realigning the stack. Any extra padding for this
1083 // over-alignment is not realized because the code inserted below adjusts
1084 // the stack pointer by numregs * 8 before aligning the stack pointer.
1085 if (DNum == 0)
1086 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1087 }
1088
1089 // Move the stack pointer to the d8 spill slot, and align it at the same
1090 // time. Leave the stack slot address in the scratch register r4.
1091 //
1092 // sub r4, sp, #numregs * 8
1093 // bic r4, r4, #align - 1
1094 // mov sp, r4
1095 //
1096 bool isThumb = AFI->isThumbFunction();
1097 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1098 AFI->setShouldRestoreSPFromFP(true);
1099
1100 // sub r4, sp, #numregs * 8
1101 // The immediate is <= 64, so it doesn't need any special encoding.
1102 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1103 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +00001104 .addReg(ARM::SP)
1105 .addImm(8 * NumAlignedDPRCS2Regs)));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001106
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001107 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001108 // We must set parameter MustBeSingleInstruction to true, since
1109 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1110 // stack alignment. Luckily, this can always be done since all ARM
1111 // architecture versions that support Neon also support the BFC
1112 // instruction.
1113 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001114
1115 // mov sp, r4
1116 // The stack pointer must be adjusted before spilling anything, otherwise
1117 // the stack slots could be clobbered by an interrupt handler.
1118 // Leave r4 live, it is used below.
1119 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1120 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1121 .addReg(ARM::R4);
1122 MIB = AddDefaultPred(MIB);
1123 if (!isThumb)
1124 AddDefaultCC(MIB);
1125
1126 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1127 // r4 holds the stack slot address.
1128 unsigned NextReg = ARM::D8;
1129
1130 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1131 // The writeback is only needed when emitting two vst1.64 instructions.
1132 if (NumAlignedDPRCS2Regs >= 6) {
1133 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001134 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001135 MBB.addLiveIn(SupReg);
1136 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1137 ARM::R4)
1138 .addReg(ARM::R4, RegState::Kill).addImm(16)
1139 .addReg(NextReg)
1140 .addReg(SupReg, RegState::ImplicitKill));
1141 NextReg += 4;
1142 NumAlignedDPRCS2Regs -= 4;
1143 }
1144
1145 // We won't modify r4 beyond this point. It currently points to the next
1146 // register to be spilled.
1147 unsigned R4BaseReg = NextReg;
1148
1149 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1150 if (NumAlignedDPRCS2Regs >= 4) {
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 MBB.addLiveIn(SupReg);
1154 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1155 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1156 .addReg(SupReg, RegState::ImplicitKill));
1157 NextReg += 4;
1158 NumAlignedDPRCS2Regs -= 4;
1159 }
1160
1161 // 16-byte aligned vst1.64 with 2 d-regs.
1162 if (NumAlignedDPRCS2Regs >= 2) {
1163 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001164 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001165 MBB.addLiveIn(SupReg);
1166 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001167 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001168 NextReg += 2;
1169 NumAlignedDPRCS2Regs -= 2;
1170 }
1171
1172 // Finally, use a vanilla vstr.64 for the odd last register.
1173 if (NumAlignedDPRCS2Regs) {
1174 MBB.addLiveIn(NextReg);
1175 // vstr.64 uses addrmode5 which has an offset scale of 4.
1176 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1177 .addReg(NextReg)
1178 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1179 }
1180
1181 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001182 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001183}
1184
1185/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1186/// iterator to the following instruction.
1187static MachineBasicBlock::iterator
1188skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1189 unsigned NumAlignedDPRCS2Regs) {
1190 // sub r4, sp, #numregs * 8
1191 // bic r4, r4, #align - 1
1192 // mov sp, r4
1193 ++MI; ++MI; ++MI;
1194 assert(MI->mayStore() && "Expecting spill instruction");
1195
1196 // These switches all fall through.
1197 switch(NumAlignedDPRCS2Regs) {
1198 case 7:
1199 ++MI;
1200 assert(MI->mayStore() && "Expecting spill instruction");
1201 default:
1202 ++MI;
1203 assert(MI->mayStore() && "Expecting spill instruction");
1204 case 1:
1205 case 2:
1206 case 4:
1207 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1208 ++MI;
1209 }
1210 return MI;
1211}
1212
1213/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1214/// starting from d8. These instructions are assumed to execute while the
1215/// stack is still aligned, unlike the code inserted by emitPopInst.
1216static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1217 MachineBasicBlock::iterator MI,
1218 unsigned NumAlignedDPRCS2Regs,
1219 const std::vector<CalleeSavedInfo> &CSI,
1220 const TargetRegisterInfo *TRI) {
1221 MachineFunction &MF = *MBB.getParent();
1222 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1223 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001224 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001225
1226 // Find the frame index assigned to d8.
1227 int D8SpillFI = 0;
1228 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1229 if (CSI[i].getReg() == ARM::D8) {
1230 D8SpillFI = CSI[i].getFrameIdx();
1231 break;
1232 }
1233
1234 // Materialize the address of the d8 spill slot into the scratch register r4.
1235 // This can be fairly complicated if the stack frame is large, so just use
1236 // the normal frame index elimination mechanism to do it. This code runs as
1237 // the initial part of the epilog where the stack and base pointers haven't
1238 // been changed yet.
1239 bool isThumb = AFI->isThumbFunction();
1240 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1241
1242 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1243 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1244 .addFrameIndex(D8SpillFI).addImm(0)));
1245
1246 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1247 unsigned NextReg = ARM::D8;
1248
1249 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1250 if (NumAlignedDPRCS2Regs >= 6) {
1251 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001252 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001253 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1254 .addReg(ARM::R4, RegState::Define)
1255 .addReg(ARM::R4, RegState::Kill).addImm(16)
1256 .addReg(SupReg, RegState::ImplicitDefine));
1257 NextReg += 4;
1258 NumAlignedDPRCS2Regs -= 4;
1259 }
1260
1261 // We won't modify r4 beyond this point. It currently points to the next
1262 // register to be spilled.
1263 unsigned R4BaseReg = NextReg;
1264
1265 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1266 if (NumAlignedDPRCS2Regs >= 4) {
1267 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001268 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001269 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1270 .addReg(ARM::R4).addImm(16)
1271 .addReg(SupReg, RegState::ImplicitDefine));
1272 NextReg += 4;
1273 NumAlignedDPRCS2Regs -= 4;
1274 }
1275
1276 // 16-byte aligned vld1.64 with 2 d-regs.
1277 if (NumAlignedDPRCS2Regs >= 2) {
1278 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001279 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001280 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1281 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001282 NextReg += 2;
1283 NumAlignedDPRCS2Regs -= 2;
1284 }
1285
1286 // Finally, use a vanilla vldr.64 for the remaining odd register.
1287 if (NumAlignedDPRCS2Regs)
1288 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1289 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1290
1291 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001292 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001293}
1294
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001295bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001296 MachineBasicBlock::iterator MI,
1297 const std::vector<CalleeSavedInfo> &CSI,
1298 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001299 if (CSI.empty())
1300 return false;
1301
1302 MachineFunction &MF = *MBB.getParent();
1303 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001304
1305 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001306 unsigned PushOneOpc = AFI->isThumbFunction() ?
1307 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001308 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001309 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1310 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001311 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001312 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001313 MachineInstr::FrameSetup);
1314 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001315 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1316
1317 // The code above does not insert spill code for the aligned DPRCS2 registers.
1318 // The stack realignment code will be inserted between the push instructions
1319 // and these spills.
1320 if (NumAlignedDPRCS2Regs)
1321 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001322
1323 return true;
1324}
1325
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001326bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001327 MachineBasicBlock::iterator MI,
1328 const std::vector<CalleeSavedInfo> &CSI,
1329 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001330 if (CSI.empty())
1331 return false;
1332
1333 MachineFunction &MF = *MBB.getParent();
1334 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001335 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001336 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1337
1338 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1339 // registers. Do that here instead.
1340 if (NumAlignedDPRCS2Regs)
1341 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001342
1343 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001344 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001345 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001346 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1347 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001348 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001349 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001350 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001351 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001352
1353 return true;
1354}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001355
1356// FIXME: Make generic?
1357static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1358 const ARMBaseInstrInfo &TII) {
1359 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001360 for (auto &MBB : MF) {
1361 for (auto &MI : MBB)
1362 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001363 }
1364 return FnSize;
1365}
1366
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001367/// estimateRSStackSizeLimit - Look at each instruction that references stack
1368/// frames and return the stack size limit beyond which some of these
1369/// instructions will require a scratch register during their expansion later.
1370// FIXME: Move to TII?
1371static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001372 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001373 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1374 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001375 for (auto &MBB : MF) {
1376 for (auto &MI : MBB) {
1377 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1378 if (!MI.getOperand(i).isFI())
1379 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001380
1381 // When using ADDri to get the address of a stack object, 255 is the
1382 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001383 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001384 Limit = std::min(Limit, (1U << 8) - 1);
1385 break;
1386 }
1387
1388 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001389 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001390 case ARMII::AddrMode3:
1391 case ARMII::AddrModeT2_i8:
1392 Limit = std::min(Limit, (1U << 8) - 1);
1393 break;
1394 case ARMII::AddrMode5:
1395 case ARMII::AddrModeT2_i8s4:
1396 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1397 break;
1398 case ARMII::AddrModeT2_i12:
1399 // i12 supports only positive offset so these will be converted to
1400 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1401 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1402 Limit = std::min(Limit, (1U << 8) - 1);
1403 break;
1404 case ARMII::AddrMode4:
1405 case ARMII::AddrMode6:
1406 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1407 // immediate offset for stack references.
1408 return 0;
1409 default:
1410 break;
1411 }
1412 break; // At most one FI per instruction
1413 }
1414 }
1415 }
1416
1417 return Limit;
1418}
1419
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001420// In functions that realign the stack, it can be an advantage to spill the
1421// callee-saved vector registers after realigning the stack. The vst1 and vld1
1422// instructions take alignment hints that can improve performance.
1423//
Matthias Braun02564862015-07-14 17:17:13 +00001424static void
1425checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001426 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1427 if (!SpillAlignedNEONRegs)
1428 return;
1429
1430 // Naked functions don't spill callee-saved registers.
Duncan P. N. Exon Smith2cff9e12015-02-14 02:24:44 +00001431 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001432 return;
1433
1434 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001435 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001436 return;
1437
1438 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001439 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001440 return;
1441
1442 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001443 if (!static_cast<const ARMBaseRegisterInfo *>(
1444 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001445 return;
1446
1447 // We always spill contiguous d-registers starting from d8. Count how many
1448 // needs spilling. The register allocator will almost always use the
1449 // callee-saved registers in order, but it can happen that there are holes in
1450 // the range. Registers above the hole will be spilled to the standard DPRCS
1451 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001452 unsigned NumSpills = 0;
1453 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001454 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001455 break;
1456
1457 // Don't do this for just one d-register. It's not worth it.
1458 if (NumSpills < 2)
1459 return;
1460
1461 // Spill the first NumSpills D-registers after realigning the stack.
1462 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1463
1464 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001465 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001466}
1467
Matthias Braun02564862015-07-14 17:17:13 +00001468void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1469 BitVector &SavedRegs,
1470 RegScavenger *RS) const {
1471 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001472 // This tells PEI to spill the FP as if it is any other callee-save register
1473 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1474 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1475 // to combine multiple loads / stores.
1476 bool CanEliminateFrame = true;
1477 bool CS1Spilled = false;
1478 bool LRSpilled = false;
1479 unsigned NumGPRSpills = 0;
1480 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1481 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001482 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001483 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001484 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001485 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001486 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1487 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001488 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001489 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1490
1491 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1492 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001493 // since it's not always possible to restore sp from fp in a single
1494 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001495 // FIXME: It will be better just to find spare register here.
1496 if (AFI->isThumb2Function() &&
1497 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001498 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001499
Evan Cheng572756a2011-01-16 05:14:33 +00001500 if (AFI->isThumb1OnlyFunction()) {
1501 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001502 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001503 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001504
Jim Grosbachdca85312011-06-13 21:18:25 +00001505 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1506 // for sure what the stack size will be, but for this, an estimate is good
1507 // enough. If there anything changes it, it'll be a spill, which implies
1508 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001509 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001510 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001511 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001512 if (MFI->hasVarSizedObjects() || StackSize > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001513 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001514 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001515
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001516 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001517 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001518
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001519 // Spill the BasePtr if it's used.
1520 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001521 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001522
1523 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001524 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001525 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001526 for (unsigned i = 0; CSRegs[i]; ++i) {
1527 unsigned Reg = CSRegs[i];
1528 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001529 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001530 Spilled = true;
1531 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001532 }
1533
Craig Topperc7242e02012-04-20 07:30:17 +00001534 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001535 continue;
1536
1537 if (Spilled) {
1538 NumGPRSpills++;
1539
Tim Northover86f60b72014-05-30 13:23:06 +00001540 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001541 if (Reg == ARM::LR)
1542 LRSpilled = true;
1543 CS1Spilled = true;
1544 continue;
1545 }
1546
1547 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1548 switch (Reg) {
1549 case ARM::LR:
1550 LRSpilled = true;
1551 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001552 case ARM::R0: case ARM::R1:
1553 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001554 case ARM::R4: case ARM::R5:
1555 case ARM::R6: case ARM::R7:
1556 CS1Spilled = true;
1557 break;
1558 default:
1559 break;
1560 }
1561 } else {
Tim Northover86f60b72014-05-30 13:23:06 +00001562 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001563 UnspilledCS1GPRs.push_back(Reg);
1564 continue;
1565 }
1566
1567 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001568 case ARM::R0: case ARM::R1:
1569 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001570 case ARM::R4: case ARM::R5:
1571 case ARM::R6: case ARM::R7:
1572 case ARM::LR:
1573 UnspilledCS1GPRs.push_back(Reg);
1574 break;
1575 default:
1576 UnspilledCS2GPRs.push_back(Reg);
1577 break;
1578 }
1579 }
1580 }
1581
1582 bool ForceLRSpill = false;
1583 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1584 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1585 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1586 // use of BL to implement far jump. If it turns out that it's not needed
1587 // then the branch fix up path will undo it.
1588 if (FnSize >= (1 << 11)) {
1589 CanEliminateFrame = false;
1590 ForceLRSpill = true;
1591 }
1592 }
1593
1594 // If any of the stack slot references may be out of range of an immediate
1595 // offset, make sure a register (or a spill slot) is available for the
1596 // register scavenger. Note that if we're indexing off the frame pointer, the
1597 // effective stack size is 4 bytes larger since the FP points to the stack
1598 // slot of the previous FP. Also, if we have variable sized objects in the
1599 // function, stack slot references will often be negative, and some of
1600 // our instructions are positive-offset only, so conservatively consider
1601 // that case to want a spill slot (or register) as well. Similarly, if
1602 // the function adjusts the stack pointer during execution and the
1603 // adjustments aren't already part of our stack size estimate, our offset
1604 // calculations may be off, so be conservative.
1605 // FIXME: We could add logic to be more precise about negative offsets
1606 // and which instructions will need a scratch register for them. Is it
1607 // worth the effort and added fragility?
1608 bool BigStack =
1609 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001610 (MFI->estimateStackSize(MF) +
1611 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001612 estimateRSStackSizeLimit(MF, this)))
1613 || MFI->hasVarSizedObjects()
1614 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1615
1616 bool ExtraCSSpill = false;
1617 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1618 AFI->setHasStackFrame(true);
1619
1620 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1621 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1622 if (!LRSpilled && CS1Spilled) {
Matthias Braun02564862015-07-14 17:17:13 +00001623 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001624 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001625 SmallVectorImpl<unsigned>::iterator LRPos;
1626 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1627 (unsigned)ARM::LR);
1628 if (LRPos != UnspilledCS1GPRs.end())
1629 UnspilledCS1GPRs.erase(LRPos);
1630
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001631 ForceLRSpill = false;
1632 ExtraCSSpill = true;
1633 }
1634
1635 if (hasFP(MF)) {
Matthias Braun02564862015-07-14 17:17:13 +00001636 SavedRegs.set(FramePtr);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001637 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1638 FramePtr);
1639 if (FPPos != UnspilledCS1GPRs.end())
1640 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001641 NumGPRSpills++;
1642 }
1643
1644 // If stack and double are 8-byte aligned and we are spilling an odd number
1645 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1646 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001647 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001648 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001649 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1650 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1651 unsigned Reg = UnspilledCS1GPRs[i];
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001652 // Don't spill high register if the function is thumb
1653 if (!AFI->isThumbFunction() ||
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001654 isARMLowRegister(Reg) || Reg == ARM::LR) {
Matthias Braun02564862015-07-14 17:17:13 +00001655 SavedRegs.set(Reg);
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001656 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001657 ExtraCSSpill = true;
1658 break;
1659 }
1660 }
1661 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1662 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00001663 SavedRegs.set(Reg);
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001664 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001665 ExtraCSSpill = true;
1666 }
1667 }
1668
1669 // Estimate if we might need to scavenge a register at some point in order
1670 // to materialize a stack offset. If so, either spill one additional
1671 // callee-saved register or reserve a special spill slot to facilitate
1672 // register scavenging. Thumb1 needs a spill slot for stack pointer
1673 // adjustments also, even when the frame itself is small.
1674 if (BigStack && !ExtraCSSpill) {
1675 // If any non-reserved CS register isn't spilled, just spill one or two
1676 // extra. That should take care of it!
1677 unsigned NumExtras = TargetAlign / 4;
1678 SmallVector<unsigned, 2> Extras;
1679 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1680 unsigned Reg = UnspilledCS1GPRs.back();
1681 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001682 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001683 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1684 Reg == ARM::LR)) {
1685 Extras.push_back(Reg);
1686 NumExtras--;
1687 }
1688 }
1689 // For non-Thumb1 functions, also check for hi-reg CS registers
1690 if (!AFI->isThumb1OnlyFunction()) {
1691 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1692 unsigned Reg = UnspilledCS2GPRs.back();
1693 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001694 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001695 Extras.push_back(Reg);
1696 NumExtras--;
1697 }
1698 }
1699 }
1700 if (Extras.size() && NumExtras == 0) {
1701 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Matthias Braun02564862015-07-14 17:17:13 +00001702 SavedRegs.set(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001703 }
1704 } else if (!AFI->isThumb1OnlyFunction()) {
1705 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1706 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001707 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001708 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001709 RC->getAlignment(),
1710 false));
1711 }
1712 }
1713 }
1714
1715 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00001716 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001717 AFI->setLRIsSpilledForFarJump(true);
1718 }
1719}
Eli Bendersky8da87162013-02-21 20:05:00 +00001720
1721
1722void ARMFrameLowering::
1723eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1724 MachineBasicBlock::iterator I) const {
1725 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001726 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001727 if (!hasReservedCallFrame(MF)) {
1728 // If we have alloca, convert as follows:
1729 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1730 // ADJCALLSTACKUP -> add, sp, sp, amount
1731 MachineInstr *Old = I;
1732 DebugLoc dl = Old->getDebugLoc();
1733 unsigned Amount = Old->getOperand(0).getImm();
1734 if (Amount != 0) {
1735 // We need to keep the stack aligned properly. To do this, we round the
1736 // amount of space needed for the outgoing arguments up to the next
1737 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00001738 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00001739
1740 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1741 assert(!AFI->isThumb1OnlyFunction() &&
1742 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1743 bool isARM = !AFI->isThumbFunction();
1744
1745 // Replace the pseudo instruction with a new instruction...
1746 unsigned Opc = Old->getOpcode();
1747 int PIdx = Old->findFirstPredOperandIdx();
1748 ARMCC::CondCodes Pred = (PIdx == -1)
1749 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1750 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1751 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1752 unsigned PredReg = Old->getOperand(2).getReg();
1753 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1754 Pred, PredReg);
1755 } else {
1756 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1757 unsigned PredReg = Old->getOperand(3).getReg();
1758 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1759 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1760 Pred, PredReg);
1761 }
1762 }
1763 }
1764 MBB.erase(I);
1765}
1766
Oliver Stannardb14c6252014-04-02 16:10:33 +00001767/// Get the minimum constant for ARM that is greater than or equal to the
1768/// argument. In ARM, constants can have any value that can be produced by
1769/// rotating an 8-bit value to the right by an even number of bits within a
1770/// 32-bit word.
1771static uint32_t alignToARMConstant(uint32_t Value) {
1772 unsigned Shifted = 0;
1773
1774 if (Value == 0)
1775 return 0;
1776
1777 while (!(Value & 0xC0000000)) {
1778 Value = Value << 2;
1779 Shifted += 2;
1780 }
1781
1782 bool Carry = (Value & 0x00FFFFFF);
1783 Value = ((Value & 0xFF000000) >> 24) + Carry;
1784
1785 if (Value & 0x0000100)
1786 Value = Value & 0x000001FC;
1787
1788 if (Shifted > 24)
1789 Value = Value >> (Shifted - 24);
1790 else
1791 Value = Value << (24 - Shifted);
1792
1793 return Value;
1794}
1795
1796// The stack limit in the TCB is set to this many bytes above the actual
1797// stack limit.
1798static const uint64_t kSplitStackAvailable = 256;
1799
1800// Adjust the function prologue to enable split stacks. This currently only
1801// supports android and linux.
1802//
1803// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1804// must be well defined in order to allow for consistent implementations of the
1805// __morestack helper function. The ABI is also not a normal ABI in that it
1806// doesn't follow the normal calling conventions because this allows the
1807// prologue of each function to be optimized further.
1808//
1809// Currently, the ABI looks like (when calling __morestack)
1810//
1811// * r4 holds the minimum stack size requested for this function call
1812// * r5 holds the stack size of the arguments to the function
1813// * the beginning of the function is 3 instructions after the call to
1814// __morestack
1815//
1816// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1817// place the arguments on to the new stack, and the 3-instruction knowledge to
1818// jump directly to the body of the function when working on the new stack.
1819//
1820// An old (and possibly no longer compatible) implementation of __morestack for
1821// ARM can be found at [1].
1822//
1823// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00001824void ARMFrameLowering::adjustForSegmentedStacks(
1825 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00001826 unsigned Opcode;
1827 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00001828 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00001829 bool Thumb = ST->isThumb();
1830
1831 // Sadly, this currently doesn't support varargs, platforms other than
1832 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1833 if (MF.getFunction()->isVarArg())
1834 report_fatal_error("Segmented stacks do not support vararg functions.");
1835 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001836 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001837
Oliver Stannardb14c6252014-04-02 16:10:33 +00001838 MachineFrameInfo *MFI = MF.getFrameInfo();
1839 MachineModuleInfo &MMI = MF.getMMI();
1840 MCContext &Context = MMI.getContext();
1841 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1842 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001843 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00001844 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1845 DebugLoc DL;
1846
Tim Northoverf9e798b2014-05-22 13:03:43 +00001847 uint64_t StackSize = MFI->getStackSize();
1848
1849 // Do not generate a prologue for functions with a stack of size zero
1850 if (StackSize == 0)
1851 return;
1852
Oliver Stannardb14c6252014-04-02 16:10:33 +00001853 // Use R4 and R5 as scratch registers.
1854 // We save R4 and R5 before use and restore them before leaving the function.
1855 unsigned ScratchReg0 = ARM::R4;
1856 unsigned ScratchReg1 = ARM::R5;
1857 uint64_t AlignedStackSize;
1858
1859 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1860 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1861 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1862 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1863 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1864
Quentin Colombet71a71482015-07-20 21:42:14 +00001865 // Grab everything that reaches PrologueMBB to update there liveness as well.
1866 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
1867 SmallVector<MachineBasicBlock *, 2> WalkList;
1868 WalkList.push_back(&PrologueMBB);
1869
1870 do {
1871 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
1872 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
1873 if (BeforePrologueRegion.insert(PredBB).second)
1874 WalkList.push_back(PredBB);
1875 }
1876 } while (!WalkList.empty());
1877
1878 // The order in that list is important.
1879 // The blocks will all be inserted before PrologueMBB using that order.
1880 // Therefore the block that should appear first in the CFG should appear
1881 // first in the list.
1882 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
1883 PostStackMBB};
1884 const int NbAddedBlocks = sizeof(AddedBlocks) / sizeof(AddedBlocks[0]);
1885
1886 for (int Idx = 0; Idx < NbAddedBlocks; ++Idx)
1887 BeforePrologueRegion.insert(AddedBlocks[Idx]);
1888
Matthias Braund9da1622015-09-09 18:08:03 +00001889 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001890 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00001891 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001892 }
1893
Quentin Colombet71a71482015-07-20 21:42:14 +00001894 // Remove the newly added blocks from the list, since we know
1895 // we do not have to do the following updates for them.
1896 for (int Idx = 0; Idx < NbAddedBlocks; ++Idx) {
1897 BeforePrologueRegion.erase(AddedBlocks[Idx]);
1898 MF.insert(&PrologueMBB, AddedBlocks[Idx]);
1899 }
1900
1901 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
1902 // Make sure the LiveIns are still sorted and unique.
1903 MBB->sortUniqueLiveIns();
1904 // Replace the edges to PrologueMBB by edges to the sequences
1905 // we are about to add.
1906 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
1907 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00001908
1909 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00001910 AlignedStackSize = alignToARMConstant(StackSize);
1911
1912 // When the frame size is less than 256 we just compare the stack
1913 // boundary directly to the value of the stack pointer, per gcc.
1914 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1915
1916 // We will use two of the callee save registers as scratch registers so we
1917 // need to save those registers onto the stack.
1918 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1919 // requested and arguments for __morestack().
1920 // SR0: Scratch Register #0
1921 // SR1: Scratch Register #1
1922 // push {SR0, SR1}
1923 if (Thumb) {
1924 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1925 .addReg(ScratchReg0).addReg(ScratchReg1);
1926 } else {
1927 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1928 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1929 .addReg(ScratchReg0).addReg(ScratchReg1);
1930 }
1931
1932 // Emit the relevant DWARF information about the change in stack pointer as
1933 // well as where to find both r4 and r5 (the callee-save registers)
1934 CFIIndex =
1935 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1936 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1937 .addCFIIndex(CFIIndex);
1938 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1939 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1940 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1941 .addCFIIndex(CFIIndex);
1942 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1943 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1944 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1945 .addCFIIndex(CFIIndex);
1946
1947 // mov SR1, sp
1948 if (Thumb) {
1949 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1950 .addReg(ARM::SP));
1951 } else if (CompareStackPointer) {
1952 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1953 .addReg(ARM::SP)).addReg(0);
1954 }
1955
1956 // sub SR1, sp, #StackSize
1957 if (!CompareStackPointer && Thumb) {
1958 AddDefaultPred(
1959 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1960 .addReg(ScratchReg1).addImm(AlignedStackSize));
1961 } else if (!CompareStackPointer) {
1962 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1963 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1964 }
1965
1966 if (Thumb && ST->isThumb1Only()) {
1967 unsigned PCLabelId = ARMFI->createPICLabelUId();
1968 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001969 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001970 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00001971 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001972
1973 // ldr SR0, [pc, offset(STACK_LIMIT)]
1974 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1975 .addConstantPoolIndex(CPI));
1976
1977 // ldr SR0, [SR0]
1978 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1979 .addReg(ScratchReg0).addImm(0));
1980 } else {
1981 // Get TLS base address from the coprocessor
1982 // mrc p15, #0, SR0, c13, c0, #3
1983 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1984 .addImm(15)
1985 .addImm(0)
1986 .addImm(13)
1987 .addImm(0)
1988 .addImm(3));
1989
1990 // Use the last tls slot on android and a private field of the TCP on linux.
1991 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1992 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1993
1994 // Get the stack limit from the right offset
1995 // ldr SR0, [sr0, #4 * TlsOffset]
1996 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1997 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1998 }
1999
2000 // Compare stack limit with stack size requested.
2001 // cmp SR0, SR1
2002 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2003 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2004 .addReg(ScratchReg0)
2005 .addReg(ScratchReg1));
2006
2007 // This jump is taken if StackLimit < SP - stack required.
2008 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2009 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2010 .addImm(ARMCC::LO)
2011 .addReg(ARM::CPSR);
2012
2013
2014 // Calling __morestack(StackSize, Size of stack arguments).
2015 // __morestack knows that the stack size requested is in SR0(r4)
2016 // and amount size of stack arguments is in SR1(r5).
2017
2018 // Pass first argument for the __morestack by Scratch Register #0.
2019 // The amount size of stack required
2020 if (Thumb) {
2021 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2022 ScratchReg0)).addImm(AlignedStackSize));
2023 } else {
2024 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2025 .addImm(AlignedStackSize)).addReg(0);
2026 }
2027 // Pass second argument for the __morestack by Scratch Register #1.
2028 // The amount size of stack consumed to save function arguments.
2029 if (Thumb) {
2030 AddDefaultPred(
2031 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2032 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2033 } else {
2034 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2035 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2036 .addReg(0);
2037 }
2038
2039 // push {lr} - Save return address of this function.
2040 if (Thumb) {
2041 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2042 .addReg(ARM::LR);
2043 } else {
2044 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2045 .addReg(ARM::SP, RegState::Define)
2046 .addReg(ARM::SP))
2047 .addReg(ARM::LR);
2048 }
2049
2050 // Emit the DWARF info about the change in stack as well as where to find the
2051 // previous link register
2052 CFIIndex =
2053 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2054 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2055 .addCFIIndex(CFIIndex);
2056 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2057 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2058 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2059 .addCFIIndex(CFIIndex);
2060
2061 // Call __morestack().
2062 if (Thumb) {
2063 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2064 .addExternalSymbol("__morestack");
2065 } else {
2066 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2067 .addExternalSymbol("__morestack");
2068 }
2069
2070 // pop {lr} - Restore return address of this original function.
2071 if (Thumb) {
2072 if (ST->isThumb1Only()) {
2073 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2074 .addReg(ScratchReg0);
2075 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2076 .addReg(ScratchReg0));
2077 } else {
2078 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2079 .addReg(ARM::LR, RegState::Define)
2080 .addReg(ARM::SP, RegState::Define)
2081 .addReg(ARM::SP)
2082 .addImm(4));
2083 }
2084 } else {
2085 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2086 .addReg(ARM::SP, RegState::Define)
2087 .addReg(ARM::SP))
2088 .addReg(ARM::LR);
2089 }
2090
2091 // Restore SR0 and SR1 in case of __morestack() was called.
2092 // __morestack() will skip PostStackMBB block so we need to restore
2093 // scratch registers from here.
2094 // pop {SR0, SR1}
2095 if (Thumb) {
2096 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2097 .addReg(ScratchReg0)
2098 .addReg(ScratchReg1);
2099 } else {
2100 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2101 .addReg(ARM::SP, RegState::Define)
2102 .addReg(ARM::SP))
2103 .addReg(ScratchReg0)
2104 .addReg(ScratchReg1);
2105 }
2106
2107 // Update the CFA offset now that we've popped
2108 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2109 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2110 .addCFIIndex(CFIIndex);
2111
2112 // bx lr - Return from this function.
2113 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2114 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2115
2116 // Restore SR0 and SR1 in case of __morestack() was not called.
2117 // pop {SR0, SR1}
2118 if (Thumb) {
2119 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2120 .addReg(ScratchReg0)
2121 .addReg(ScratchReg1);
2122 } else {
2123 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2124 .addReg(ARM::SP, RegState::Define)
2125 .addReg(ARM::SP))
2126 .addReg(ScratchReg0)
2127 .addReg(ScratchReg1);
2128 }
2129
2130 // Update the CFA offset now that we've popped
2131 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2132 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2133 .addCFIIndex(CFIIndex);
2134
2135 // Tell debuggers that r4 and r5 are now the same as they were in the
2136 // previous function, that they're the "Same Value".
2137 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2138 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2139 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2140 .addCFIIndex(CFIIndex);
2141 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2142 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2143 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2144 .addCFIIndex(CFIIndex);
2145
2146 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002147 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002148
2149 AllocMBB->addSuccessor(PostStackMBB);
2150
2151 GetMBB->addSuccessor(PostStackMBB);
2152 GetMBB->addSuccessor(AllocMBB);
2153
2154 McrMBB->addSuccessor(GetMBB);
2155
2156 PrevStackMBB->addSuccessor(McrMBB);
2157
2158#ifdef XDEBUG
2159 MF.verify();
2160#endif
2161}