blob: 830953b2b0cd43ad2e45b0d75e02b4b27e61c609 [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
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000046/// hasFP - Return true if the specified function should have a dedicated frame
47/// pointer register. This is true if the function has variable sized allocas
48/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000049bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +000050 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000051
Evan Cheng801d98b2012-01-04 01:55:04 +000052 // iOS requires FP not to be clobbered for backtracing purpose.
53 if (STI.isTargetIOS())
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000054 return true;
55
56 const MachineFrameInfo *MFI = MF.getFrameInfo();
57 // Always eliminate non-leaf frame pointers.
Nick Lewycky50f02cb2011-12-02 22:16:29 +000058 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
59 MFI->hasCalls()) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000060 RegInfo->needsStackRealignment(MF) ||
61 MFI->hasVarSizedObjects() ||
62 MFI->isFrameAddressTaken());
63}
64
Bob Wilson657f2272011-01-13 21:10:12 +000065/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
66/// not required, we reserve argument space for call sites in the function
67/// immediately on entry to the current function. This eliminates the need for
68/// add/sub sp brackets around call sites. Returns true if the call frame is
69/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000070bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000071 const MachineFrameInfo *FFI = MF.getFrameInfo();
72 unsigned CFSize = FFI->getMaxCallFrameSize();
73 // It's not always a good idea to include the call frame as part of the
74 // stack frame. ARM (especially Thumb) has small immediate offset to
75 // address the stack frame. So a large call frame can cause poor codegen
76 // and may even makes it impossible to scavenge a register.
77 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
78 return false;
79
80 return !MF.getFrameInfo()->hasVarSizedObjects();
81}
82
Bob Wilson657f2272011-01-13 21:10:12 +000083/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
84/// call frame pseudos can be simplified. Unlike most targets, having a FP
85/// is not sufficient here since we still may reference some objects via SP
86/// even when FP is available in Thumb2 mode.
87bool
88ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000089 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
90}
91
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000092static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +000094 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +000095 // Integer spill area is handled with "pop".
Tim Northover93bcc662013-11-08 17:18:07 +000096 if (isPopOpcode(MI->getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +000097 // The first two operands are predicates. The last two are
98 // imp-def and imp-use of SP. Check everything in between.
99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
101 return false;
102 return true;
103 }
Owen Anderson2aedba62011-07-26 20:54:26 +0000104 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105 MI->getOpcode() == ARM::LDR_POST_REG ||
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000106 MI->getOpcode() == ARM::t2LDR_POST) &&
107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108 MI->getOperand(1).getReg() == ARM::SP)
109 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000110
111 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000112}
113
Tim Northoverc9432eb2013-11-04 23:04:15 +0000114static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116 const ARMBaseInstrInfo &TII, unsigned DestReg,
117 unsigned SrcReg, int NumBytes,
118 unsigned MIFlags = MachineInstr::NoFlags,
119 ARMCC::CondCodes Pred = ARMCC::AL,
120 unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000121 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000123 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000124 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000126 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000127}
128
Tim Northoverc9432eb2013-11-04 23:04:15 +0000129static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131 const ARMBaseInstrInfo &TII, int NumBytes,
132 unsigned MIFlags = MachineInstr::NoFlags,
133 ARMCC::CondCodes Pred = ARMCC::AL,
134 unsigned PredReg = 0) {
135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136 MIFlags, Pred, PredReg);
137}
138
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000139static int sizeOfSPAdjustment(const MachineInstr *MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000140 int RegSize;
141 switch (MI->getOpcode()) {
142 case ARM::VSTMDDB_UPD:
143 RegSize = 8;
144 break;
145 case ARM::STMDB_UPD:
146 case ARM::t2STMDB_UPD:
147 RegSize = 4;
148 break;
149 case ARM::t2STR_PRE:
150 case ARM::STR_PRE_IMM:
151 return 4;
152 default:
153 llvm_unreachable("Unknown push or pop like instruction");
154 }
155
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000156 int count = 0;
157 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
158 // pred) so the list starts at 4.
159 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000160 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000161 return count;
162}
163
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000164static bool WindowsRequiresStackProbe(const MachineFunction &MF,
165 size_t StackSizeInBytes) {
166 const MachineFrameInfo *MFI = MF.getFrameInfo();
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000167 const Function *F = MF.getFunction();
168 unsigned StackProbeSize = (MFI->getStackProtectorIndex() > 0) ? 4080 : 4096;
169 if (F->hasFnAttribute("stack-probe-size"))
170 F->getFnAttribute("stack-probe-size")
171 .getValueAsString()
172 .getAsInteger(0, StackProbeSize);
173 return StackSizeInBytes >= StackProbeSize;
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000174}
175
Tim Northover603d3162014-11-14 22:45:33 +0000176namespace {
177struct StackAdjustingInsts {
178 struct InstInfo {
179 MachineBasicBlock::iterator I;
180 unsigned SPAdjust;
181 bool BeforeFPSet;
182 };
183
184 SmallVector<InstInfo, 4> Insts;
185
186 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
187 bool BeforeFPSet = false) {
188 InstInfo Info = {I, SPAdjust, BeforeFPSet};
189 Insts.push_back(Info);
190 }
191
192 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
193 auto Info = std::find_if(Insts.begin(), Insts.end(),
194 [&](InstInfo &Info) { return Info.I == I; });
195 assert(Info != Insts.end() && "invalid sp adjusting instruction");
196 Info->SPAdjust += ExtraBytes;
197 }
198
199 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
200 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
201 unsigned CFAOffset = 0;
202 for (auto &Info : Insts) {
203 if (HasFP && !Info.BeforeFPSet)
204 return;
205
206 CFAOffset -= Info.SPAdjust;
207 unsigned CFIIndex = MMI.addFrameInst(
208 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
209 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000210 TII.get(TargetOpcode::CFI_INSTRUCTION))
211 .addCFIIndex(CFIIndex)
212 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000213 }
214 }
215};
216}
217
Kristof Beyls933de7a2015-01-08 15:09:14 +0000218/// Emit an instruction sequence that will align the address in
219/// register Reg by zero-ing out the lower bits. For versions of the
220/// architecture that support Neon, this must be done in a single
221/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
222/// single instruction. That function only gets called when optimizing
223/// spilling of D registers on a core with the Neon instruction set
224/// present.
225static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
226 const TargetInstrInfo &TII,
227 MachineBasicBlock &MBB,
228 MachineBasicBlock::iterator MBBI,
229 DebugLoc DL, const unsigned Reg,
230 const unsigned Alignment,
231 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000232 const ARMSubtarget &AST =
233 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000234 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
235 const unsigned AlignMask = Alignment - 1;
236 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
237 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
238 if (!AFI->isThumbFunction()) {
239 // if the BFC instruction is available, use that to zero the lower
240 // bits:
241 // bfc Reg, #0, log2(Alignment)
242 // otherwise use BIC, if the mask to zero the required number of bits
243 // can be encoded in the bic immediate field
244 // bic Reg, Reg, Alignment-1
245 // otherwise, emit
246 // lsr Reg, Reg, log2(Alignment)
247 // lsl Reg, Reg, log2(Alignment)
248 if (CanUseBFC) {
249 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
250 .addReg(Reg, RegState::Kill)
251 .addImm(~AlignMask));
252 } else if (AlignMask <= 255) {
253 AddDefaultCC(
254 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
255 .addReg(Reg, RegState::Kill)
256 .addImm(AlignMask)));
257 } else {
258 assert(!MustBeSingleInstruction &&
259 "Shouldn't call emitAligningInstructions demanding a single "
260 "instruction to be emitted for large stack alignment for a target "
261 "without BFC.");
262 AddDefaultCC(AddDefaultPred(
263 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
264 .addReg(Reg, RegState::Kill)
265 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))));
266 AddDefaultCC(AddDefaultPred(
267 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
268 .addReg(Reg, RegState::Kill)
269 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))));
270 }
271 } else {
272 // Since this is only reached for Thumb-2 targets, the BFC instruction
273 // should always be available.
274 assert(CanUseBFC);
275 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
276 .addReg(Reg, RegState::Kill)
277 .addImm(~AlignMask));
278 }
279}
280
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000281void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000282 MachineBasicBlock &MBB = MF.front();
283 MachineBasicBlock::iterator MBBI = MBB.begin();
284 MachineFrameInfo *MFI = MF.getFrameInfo();
285 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000286 MachineModuleInfo &MMI = MF.getMMI();
287 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000288 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000289 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000290 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
291 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000292 assert(!AFI->isThumb1OnlyFunction() &&
293 "This emitPrologue does not support Thumb1!");
294 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000295 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover8cda34f2015-03-11 18:54:22 +0000296 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000297 unsigned NumBytes = MFI->getStackSize();
298 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
299 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
300 unsigned FramePtr = RegInfo->getFrameRegister(MF);
301
302 // Determine the sizes of each callee-save spill areas and record which frame
303 // belongs to which callee-save spill areas.
304 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
305 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000306 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000307
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000308 // All calls are tail calls in GHC calling conv, and functions have no
309 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000310 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
311 return;
312
Tim Northover603d3162014-11-14 22:45:33 +0000313 StackAdjustingInsts DefCFAOffsetCandidates;
314
Oliver Stannardd55e1152014-03-05 15:25:27 +0000315 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000316 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000317 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000318 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000319 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000320 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000321
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000322 if (!AFI->hasStackFrame() &&
323 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000324 if (NumBytes - ArgRegsSaveSize != 0) {
325 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000326 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000327 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
328 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000329 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000330 return;
331 }
332
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000333 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000334 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
335 unsigned Reg = CSI[i].getReg();
336 int FI = CSI[i].getFrameIdx();
337 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000338 case ARM::R8:
339 case ARM::R9:
340 case ARM::R10:
341 case ARM::R11:
342 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000343 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000344 GPRCS2Size += 4;
345 break;
346 }
347 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000348 case ARM::R0:
349 case ARM::R1:
350 case ARM::R2:
351 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000352 case ARM::R4:
353 case ARM::R5:
354 case ARM::R6:
355 case ARM::R7:
356 case ARM::LR:
357 if (Reg == FramePtr)
358 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000359 GPRCS1Size += 4;
360 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000361 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000362 // This is a DPR. Exclude the aligned DPRCS2 spills.
363 if (Reg == ARM::D8)
364 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000365 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000366 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000367 }
368 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000369
Eric Christopherb006fc92010-11-18 19:40:05 +0000370 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000371 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
372 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000373 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000374 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
375 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000376
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000377 // Determine starting offsets of spill areas.
Tim Northoverc9432eb2013-11-04 23:04:15 +0000378 bool HasFP = hasFP(MF);
Tim Northover228c9432014-11-05 00:27:13 +0000379 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
380 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
381 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
382 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
383 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000384 int FramePtrOffsetInPush = 0;
385 if (HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000386 FramePtrOffsetInPush =
387 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000388 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
389 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000390 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000391 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
392 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
393 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
394
Tim Northoverc9432eb2013-11-04 23:04:15 +0000395 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000396 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000397 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000398 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
399 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000400
Tim Northover228c9432014-11-05 00:27:13 +0000401 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
402 // .cfi_offset operations will reflect that.
403 if (DPRGapSize) {
404 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Tim Northover603d3162014-11-14 22:45:33 +0000405 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
406 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
407 else {
Tim Northover228c9432014-11-05 00:27:13 +0000408 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
409 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000410 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
411 }
Tim Northover228c9432014-11-05 00:27:13 +0000412 }
413
Eric Christopherb006fc92010-11-18 19:40:05 +0000414 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000415 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000416 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000417 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000418 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
419 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000420 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000421 }
Evan Cheng70d29632011-02-25 00:24:46 +0000422 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000423
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000424 // Move past the aligned DPRCS2 area.
425 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
426 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
427 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
428 // leaves the stack pointer pointing to the DPRCS2 area.
429 //
430 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
431 NumBytes += MFI->getObjectOffset(D8SpillFI);
432 } else
433 NumBytes = DPRCSOffset;
434
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000435 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
436 uint32_t NumWords = NumBytes >> 2;
437
438 if (NumWords < 65536)
439 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000440 .addImm(NumWords)
441 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000442 else
443 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000444 .addImm(NumWords)
445 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000446
447 switch (TM.getCodeModel()) {
448 case CodeModel::Small:
449 case CodeModel::Medium:
450 case CodeModel::Default:
451 case CodeModel::Kernel:
452 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
453 .addImm((unsigned)ARMCC::AL).addReg(0)
454 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000455 .addReg(ARM::R4, RegState::Implicit)
456 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000457 break;
458 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000459 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000460 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000461 .addExternalSymbol("__chkstk")
462 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000463
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000464 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
465 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000466 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000467 .addReg(ARM::R4, RegState::Implicit)
468 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000469 break;
470 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000471
472 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
473 ARM::SP)
474 .addReg(ARM::SP, RegState::Define)
475 .addReg(ARM::R4, RegState::Kill)
476 .setMIFlags(MachineInstr::FrameSetup)));
477 NumBytes = 0;
478 }
479
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000480 if (NumBytes) {
481 // Adjust SP after all the callee-save spills.
Tim Northover603d3162014-11-14 22:45:33 +0000482 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
483 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
484 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000485 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
486 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000487 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
488 }
Tim Northover93bcc662013-11-08 17:18:07 +0000489
Evan Chengeb56dca2010-11-22 18:12:04 +0000490 if (HasFP && isARM)
491 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
492 // Note it's not safe to do this in Thumb2 mode because it would have
493 // taken two instructions:
494 // mov sp, r7
495 // sub sp, #24
496 // If an interrupt is taken between the two instructions, then sp is in
497 // an inconsistent state (pointing to the middle of callee-saved area).
498 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000499 AFI->setShouldRestoreSPFromFP(true);
500 }
501
Tim Northover603d3162014-11-14 22:45:33 +0000502 // Set FP to point to the stack slot that contains the previous FP.
503 // For iOS, FP is R7, which has now been stored in spill area 1.
504 // Otherwise, if this is not iOS, all the callee-saved registers go
505 // into spill area 1, including the FP in R11. In either case, it
506 // is in area one and the adjustment needs to take place just after
507 // that push.
508 if (HasFP) {
509 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
510 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
511 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
512 dl, TII, FramePtr, ARM::SP,
513 PushSize + FramePtrOffsetInPush,
514 MachineInstr::FrameSetup);
515 if (FramePtrOffsetInPush + PushSize != 0) {
516 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
517 nullptr, MRI->getDwarfRegNum(FramePtr, true),
518 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
519 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000520 .addCFIIndex(CFIIndex)
521 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000522 } else {
523 unsigned CFIIndex =
524 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
525 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
526 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000527 .addCFIIndex(CFIIndex)
528 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000529 }
530 }
531
532 // Now that the prologue's actual instructions are finalised, we can insert
533 // the necessary DWARF cf instructions to describe the situation. Start by
534 // recording where each register ended up:
535 if (GPRCS1Size > 0) {
536 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
537 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000538 for (const auto &Entry : CSI) {
539 unsigned Reg = Entry.getReg();
540 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000541 switch (Reg) {
542 case ARM::R8:
543 case ARM::R9:
544 case ARM::R10:
545 case ARM::R11:
546 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000547 if (STI.isTargetDarwin())
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000548 break;
549 // fallthrough
550 case ARM::R0:
551 case ARM::R1:
552 case ARM::R2:
553 case ARM::R3:
554 case ARM::R4:
555 case ARM::R5:
556 case ARM::R6:
557 case ARM::R7:
558 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000559 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
560 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
561 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000562 .addCFIIndex(CFIIndex)
563 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000564 break;
565 }
566 }
567 }
568
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000569 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000570 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000571 for (const auto &Entry : CSI) {
572 unsigned Reg = Entry.getReg();
573 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000574 switch (Reg) {
575 case ARM::R8:
576 case ARM::R9:
577 case ARM::R10:
578 case ARM::R11:
579 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000580 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000581 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000582 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000583 unsigned CFIIndex = MMI.addFrameInst(
584 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
585 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000586 .addCFIIndex(CFIIndex)
587 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000588 }
589 break;
590 }
591 }
592 }
593
594 if (DPRCSSize > 0) {
595 // Since vpush register list cannot have gaps, there may be multiple vpush
596 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000597 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000598 for (const auto &Entry : CSI) {
599 unsigned Reg = Entry.getReg();
600 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000601 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
602 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
603 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
604 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000605 unsigned CFIIndex = MMI.addFrameInst(
606 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000607 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000608 .addCFIIndex(CFIIndex)
609 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000610 }
611 }
612 }
613
Tim Northover603d3162014-11-14 22:45:33 +0000614 // Now we can emit descriptions of where the canonical frame address was
615 // throughout the process. If we have a frame pointer, it takes over the job
616 // half-way through, so only the first few .cfi_def_cfa_offset instructions
617 // actually get emitted.
618 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000619
Evan Chengeb56dca2010-11-22 18:12:04 +0000620 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000621 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
622 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000623
624 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
625 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000626 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000627 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
628
629 // If we need dynamic stack realignment, do it here. Be paranoid and make
630 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000631 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000632 // realigned.
633 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000634 unsigned MaxAlign = MFI->getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000635 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000636 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000637 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
638 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000639 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000640 // We cannot use sp as source/dest register here, thus we're using r4 to
641 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000642 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000643 // -- use emitAligningInstructions to produce best sequence to zero
644 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000645 // mov sp, r4
646 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000647 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000648 .addReg(ARM::SP, RegState::Kill));
649 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
650 false);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000651 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Kristof Beyls933de7a2015-01-08 15:09:14 +0000652 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000653 }
654
655 AFI->setShouldRestoreSPFromFP(true);
656 }
657
658 // If we need a base pointer, set it up here. It's whatever the value
659 // of the stack pointer is at this point. Any variable size objects
660 // will be allocated after this, so we can still use the base pointer
661 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000662 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000663 if (RegInfo->hasBasePointer(MF)) {
664 if (isARM)
665 BuildMI(MBB, MBBI, dl,
666 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
667 .addReg(ARM::SP)
668 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
669 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000670 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000671 RegInfo->getBaseRegister())
672 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000673 }
674
675 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000676 // the sp from fp. We can assume there's an FP here since hasFP already
677 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000678 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000679 AFI->setShouldRestoreSPFromFP(true);
680}
681
Tim Northover3024b552014-12-01 17:46:39 +0000682// Resolve TCReturn pseudo-instruction
683void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
684 MachineBasicBlock &MBB) const {
685 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
686 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
687 unsigned RetOpcode = MBBI->getOpcode();
688 DebugLoc dl = MBBI->getDebugLoc();
689 const ARMBaseInstrInfo &TII =
690 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
691
692 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
693 return;
694
695 // Tail call return: adjust the stack pointer and jump to callee.
696 MBBI = MBB.getLastNonDebugInstr();
697 MachineOperand &JumpTarget = MBBI->getOperand(0);
698
699 // Jump to label or value in register.
700 if (RetOpcode == ARM::TCRETURNdi) {
701 unsigned TCOpcode = STI.isThumb() ?
702 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
703 ARM::TAILJMPd;
704 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
705 if (JumpTarget.isGlobal())
706 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
707 JumpTarget.getTargetFlags());
708 else {
709 assert(JumpTarget.isSymbol());
710 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
711 JumpTarget.getTargetFlags());
712 }
713
714 // Add the default predicate in Thumb mode.
715 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
716 } else if (RetOpcode == ARM::TCRETURNri) {
717 BuildMI(MBB, MBBI, dl,
718 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
719 addReg(JumpTarget.getReg(), RegState::Kill);
720 }
721
722 MachineInstr *NewMI = std::prev(MBBI);
723 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
724 NewMI->addOperand(MBBI->getOperand(i));
725
726 // Delete the pseudo instruction TCRETURN.
727 MBB.erase(MBBI);
728 MBBI = NewMI;
729}
730
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000731void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000732 MachineBasicBlock &MBB) const {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000733 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000734 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000735 DebugLoc dl = MBBI->getDebugLoc();
736 MachineFrameInfo *MFI = MF.getFrameInfo();
737 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000738 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000739 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000740 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000741 assert(!AFI->isThumb1OnlyFunction() &&
742 "This emitEpilogue does not support Thumb1!");
743 bool isARM = !AFI->isThumbFunction();
744
Tim Northover8cda34f2015-03-11 18:54:22 +0000745 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000746 int NumBytes = (int)MFI->getStackSize();
747 unsigned FramePtr = RegInfo->getFrameRegister(MF);
748
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000749 // All calls are tail calls in GHC calling conv, and functions have no
750 // prologue/epilogue.
Tim Northover3024b552014-12-01 17:46:39 +0000751 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
752 fixTCReturn(MF, MBB);
Eric Christopherb3322362012-08-03 00:05:53 +0000753 return;
Tim Northover3024b552014-12-01 17:46:39 +0000754 }
Eric Christopherb3322362012-08-03 00:05:53 +0000755
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000756 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000757 if (NumBytes - ArgRegsSaveSize != 0)
758 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000759 } else {
760 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000761 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000762 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000763 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000764 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000765 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000766 if (!isCSRestore(MBBI, TII, CSRegs))
767 ++MBBI;
768 }
769
770 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000771 NumBytes -= (ArgRegsSaveSize +
772 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000773 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000774 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000775 AFI->getDPRCalleeSavedAreaSize());
776
777 // Reset SP based on frame pointer only if the stack frame extends beyond
778 // frame pointer stack slot or target is ELF and the function has FP.
779 if (AFI->shouldRestoreSPFromFP()) {
780 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
781 if (NumBytes) {
782 if (isARM)
783 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
784 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000785 else {
786 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000787 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000788 // mov sp, r7
789 // sub sp, #24
790 // This is bad, if an interrupt is taken after the mov, sp is in an
791 // inconsistent state.
792 // Use the first callee-saved register as a scratch register.
Kaelyn Uhrain271fbb62012-10-26 23:28:41 +0000793 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000794 "No scratch register to restore SP from FP!");
795 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000796 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000797 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000798 ARM::SP)
799 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000800 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000801 } else {
802 // Thumb2 or ARM.
803 if (isARM)
804 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
805 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
806 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000807 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000808 ARM::SP)
809 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000810 }
Tim Northoverdee86042013-12-02 14:46:26 +0000811 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000812 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000813 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000814
Eric Christopherb006fc92010-11-18 19:40:05 +0000815 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000816 if (AFI->getDPRCalleeSavedAreaSize()) {
817 MBBI++;
818 // Since vpop register list cannot have gaps, there may be multiple vpop
819 // instructions in the epilogue.
820 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
821 MBBI++;
822 }
Tim Northover228c9432014-11-05 00:27:13 +0000823 if (AFI->getDPRCalleeSavedGapSize()) {
824 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
825 "unexpected DPR alignment gap");
826 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
827 }
828
Eric Christopherb006fc92010-11-18 19:40:05 +0000829 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
830 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000831 }
832
Tim Northover3024b552014-12-01 17:46:39 +0000833 fixTCReturn(MF, MBB);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000834
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000835 if (ArgRegsSaveSize)
836 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000837}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000838
Bob Wilson657f2272011-01-13 21:10:12 +0000839/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
840/// debug info. It's the same as what we use for resolving the code-gen
841/// references for now. FIXME: This can go wrong when references are
842/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000843int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000844ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000845 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000846 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
847}
848
849int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000850ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000851 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000852 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000853 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000854 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000855 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000856 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
857 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
858 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
859 bool isFixed = MFI->isFixedObjectIndex(FI);
860
861 FrameReg = ARM::SP;
862 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000863
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000864 // SP can move around if there are allocas. We may also lose track of SP
865 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000866 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000867
Anton Korobeynikov46877782010-11-20 15:59:32 +0000868 // When dynamically realigning the stack, use the frame pointer for
869 // parameters, and the stack/base pointer for locals.
870 if (RegInfo->needsStackRealignment(MF)) {
871 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
872 if (isFixed) {
873 FrameReg = RegInfo->getFrameRegister(MF);
874 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000875 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000876 assert(RegInfo->hasBasePointer(MF) &&
877 "VLAs and dynamic stack alignment, but missing base pointer!");
878 FrameReg = RegInfo->getBaseRegister();
879 }
880 return Offset;
881 }
882
883 // If there is a frame pointer, use it when we can.
884 if (hasFP(MF) && AFI->hasStackFrame()) {
885 // Use frame pointer to reference fixed objects. Use it for locals if
886 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000887 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000888 FrameReg = RegInfo->getFrameRegister(MF);
889 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000890 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000891 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000892 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000893 // Try to use the frame pointer if we can, else use the base pointer
894 // since it's available. This is handy for the emergency spill slot, in
895 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000896 if (FPOffset >= -255 && FPOffset < 0) {
897 FrameReg = RegInfo->getFrameRegister(MF);
898 return FPOffset;
899 }
Evan Chengc0d20042011-04-22 01:42:52 +0000900 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000901 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000902 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000903 // ldr <rd>, [sp, #<imm8>]
904 // if at all possible to save space.
905 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
906 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000907 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000908 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000909 if (FPOffset >= -255 && FPOffset < 0) {
910 FrameReg = RegInfo->getFrameRegister(MF);
911 return FPOffset;
912 }
913 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
914 // Otherwise, use SP or FP, whichever is closer to the stack slot.
915 FrameReg = RegInfo->getFrameRegister(MF);
916 return FPOffset;
917 }
918 }
919 // Use the base pointer if we have one.
920 if (RegInfo->hasBasePointer(MF))
921 FrameReg = RegInfo->getBaseRegister();
922 return Offset;
923}
924
Bob Wilson657f2272011-01-13 21:10:12 +0000925int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
926 int FI) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000927 unsigned FrameReg;
928 return getFrameIndexReference(MF, FI, FrameReg);
929}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000930
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000931void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000932 MachineBasicBlock::iterator MI,
933 const std::vector<CalleeSavedInfo> &CSI,
934 unsigned StmOpc, unsigned StrOpc,
935 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000936 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000937 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000938 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000939 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000940 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000941
942 DebugLoc DL;
943 if (MI != MBB.end()) DL = MI->getDebugLoc();
944
Evan Chengc27c9562010-12-07 19:59:34 +0000945 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000946 unsigned i = CSI.size();
947 while (i != 0) {
948 unsigned LastReg = 0;
949 for (; i != 0; --i) {
950 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000951 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000952
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000953 // D-registers in the aligned area DPRCS2 are NOT spilled here.
954 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
955 continue;
956
Evan Cheng775ead32010-12-07 23:08:38 +0000957 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000958 // @llvm.returnaddress is called. If LR is returned for
959 // @llvm.returnaddress then it's already added to the function and
960 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000961 bool isKill = true;
962 if (Reg == ARM::LR) {
963 if (MF.getFrameInfo()->isReturnAddressTaken() &&
964 MF.getRegInfo().isLiveIn(Reg))
965 isKill = false;
966 }
967
968 if (isKill)
969 MBB.addLiveIn(Reg);
970
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000971 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000972 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000973 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000974 if (NoGap && LastReg && LastReg != Reg-1)
975 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000976 LastReg = Reg;
977 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000978 }
979
Jim Grosbach5fccad82010-12-09 18:31:13 +0000980 if (Regs.empty())
981 continue;
982 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000983 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000984 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000985 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000986 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
987 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000988 } else if (Regs.size() == 1) {
989 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
990 ARM::SP)
991 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000992 .addReg(ARM::SP).setMIFlags(MIFlags)
993 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000994 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000995 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000996 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000997
998 // Put any subsequent vpush instructions before this one: they will refer to
999 // higher register numbers so need to be pushed first in order to preserve
1000 // monotonicity.
1001 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001002 }
Evan Cheng775ead32010-12-07 23:08:38 +00001003}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001004
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001005void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001006 MachineBasicBlock::iterator MI,
1007 const std::vector<CalleeSavedInfo> &CSI,
1008 unsigned LdmOpc, unsigned LdrOpc,
1009 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001010 bool(*Func)(unsigned, bool),
1011 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +00001012 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001013 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Evan Cheng775ead32010-12-07 23:08:38 +00001014 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1015 DebugLoc DL = MI->getDebugLoc();
Evan Chengd6093ff2011-01-25 01:28:33 +00001016 unsigned RetOpcode = MI->getOpcode();
1017 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +00001018 RetOpcode == ARM::TCRETURNri);
Tim Northoverd8407452013-10-01 14:33:28 +00001019 bool isInterrupt =
1020 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Evan Cheng775ead32010-12-07 23:08:38 +00001021
1022 SmallVector<unsigned, 4> Regs;
1023 unsigned i = CSI.size();
1024 while (i != 0) {
1025 unsigned LastReg = 0;
1026 bool DeleteRet = false;
1027 for (; i != 0; --i) {
1028 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +00001029 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001030
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001031 // The aligned reloads from area DPRCS2 are not inserted here.
1032 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1033 continue;
1034
Tim Northoverd8407452013-10-01 14:33:28 +00001035 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1036 STI.hasV5TOps()) {
Evan Cheng775ead32010-12-07 23:08:38 +00001037 Reg = ARM::PC;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001038 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Evan Cheng775ead32010-12-07 23:08:38 +00001039 // Fold the return instruction into the LDM.
1040 DeleteRet = true;
1041 }
1042
Evan Cheng9d54ae62010-12-08 06:29:02 +00001043 // If NoGap is true, pop consecutive registers and then leave the rest
1044 // for other instructions. e.g.
1045 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1046 if (NoGap && LastReg && LastReg != Reg-1)
1047 break;
1048
Evan Cheng775ead32010-12-07 23:08:38 +00001049 LastReg = Reg;
1050 Regs.push_back(Reg);
1051 }
1052
Jim Grosbach5fccad82010-12-09 18:31:13 +00001053 if (Regs.empty())
1054 continue;
1055 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +00001056 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +00001057 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +00001058 .addReg(ARM::SP));
1059 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1060 MIB.addReg(Regs[i], getDefRegState(true));
Andrew Trick6446bf72011-08-25 17:50:53 +00001061 if (DeleteRet) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001062 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +00001063 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +00001064 }
Evan Cheng775ead32010-12-07 23:08:38 +00001065 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001066 } else if (Regs.size() == 1) {
1067 // If we adjusted the reg to PC from LR above, switch it back here. We
1068 // only do that for LDM.
1069 if (Regs[0] == ARM::PC)
1070 Regs[0] = ARM::LR;
1071 MachineInstrBuilder MIB =
1072 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1073 .addReg(ARM::SP, RegState::Define)
1074 .addReg(ARM::SP);
1075 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1076 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001077 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001078 MIB.addReg(0);
1079 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1080 } else
1081 MIB.addImm(4);
1082 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +00001083 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001084 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001085
1086 // Put any subsequent vpop instructions after this one: they will refer to
1087 // higher register numbers so need to be popped afterwards.
1088 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001089 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001090}
1091
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001092/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001093/// starting from d8. Also insert stack realignment code and leave the stack
1094/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001095static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1096 MachineBasicBlock::iterator MI,
1097 unsigned NumAlignedDPRCS2Regs,
1098 const std::vector<CalleeSavedInfo> &CSI,
1099 const TargetRegisterInfo *TRI) {
1100 MachineFunction &MF = *MBB.getParent();
1101 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1102 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001103 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001104 MachineFrameInfo &MFI = *MF.getFrameInfo();
1105
1106 // Mark the D-register spill slots as properly aligned. Since MFI computes
1107 // stack slot layout backwards, this can actually mean that the d-reg stack
1108 // slot offsets can be wrong. The offset for d8 will always be correct.
1109 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1110 unsigned DNum = CSI[i].getReg() - ARM::D8;
1111 if (DNum >= 8)
1112 continue;
1113 int FI = CSI[i].getFrameIdx();
1114 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1115 // registers will be 8-byte aligned.
1116 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1117
1118 // The stack slot for D8 needs to be maximally aligned because this is
1119 // actually the point where we align the stack pointer. MachineFrameInfo
1120 // computes all offsets relative to the incoming stack pointer which is a
1121 // bit weird when realigning the stack. Any extra padding for this
1122 // over-alignment is not realized because the code inserted below adjusts
1123 // the stack pointer by numregs * 8 before aligning the stack pointer.
1124 if (DNum == 0)
1125 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1126 }
1127
1128 // Move the stack pointer to the d8 spill slot, and align it at the same
1129 // time. Leave the stack slot address in the scratch register r4.
1130 //
1131 // sub r4, sp, #numregs * 8
1132 // bic r4, r4, #align - 1
1133 // mov sp, r4
1134 //
1135 bool isThumb = AFI->isThumbFunction();
1136 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1137 AFI->setShouldRestoreSPFromFP(true);
1138
1139 // sub r4, sp, #numregs * 8
1140 // The immediate is <= 64, so it doesn't need any special encoding.
1141 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1142 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
Kristof Beyls933de7a2015-01-08 15:09:14 +00001143 .addReg(ARM::SP)
1144 .addImm(8 * NumAlignedDPRCS2Regs)));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001145
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001146 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001147 // We must set parameter MustBeSingleInstruction to true, since
1148 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1149 // stack alignment. Luckily, this can always be done since all ARM
1150 // architecture versions that support Neon also support the BFC
1151 // instruction.
1152 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001153
1154 // mov sp, r4
1155 // The stack pointer must be adjusted before spilling anything, otherwise
1156 // the stack slots could be clobbered by an interrupt handler.
1157 // Leave r4 live, it is used below.
1158 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1159 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1160 .addReg(ARM::R4);
1161 MIB = AddDefaultPred(MIB);
1162 if (!isThumb)
1163 AddDefaultCC(MIB);
1164
1165 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1166 // r4 holds the stack slot address.
1167 unsigned NextReg = ARM::D8;
1168
1169 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1170 // The writeback is only needed when emitting two vst1.64 instructions.
1171 if (NumAlignedDPRCS2Regs >= 6) {
1172 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001173 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001174 MBB.addLiveIn(SupReg);
1175 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1176 ARM::R4)
1177 .addReg(ARM::R4, RegState::Kill).addImm(16)
1178 .addReg(NextReg)
1179 .addReg(SupReg, RegState::ImplicitKill));
1180 NextReg += 4;
1181 NumAlignedDPRCS2Regs -= 4;
1182 }
1183
1184 // We won't modify r4 beyond this point. It currently points to the next
1185 // register to be spilled.
1186 unsigned R4BaseReg = NextReg;
1187
1188 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1189 if (NumAlignedDPRCS2Regs >= 4) {
1190 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001191 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001192 MBB.addLiveIn(SupReg);
1193 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1194 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1195 .addReg(SupReg, RegState::ImplicitKill));
1196 NextReg += 4;
1197 NumAlignedDPRCS2Regs -= 4;
1198 }
1199
1200 // 16-byte aligned vst1.64 with 2 d-regs.
1201 if (NumAlignedDPRCS2Regs >= 2) {
1202 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001203 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001204 MBB.addLiveIn(SupReg);
1205 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001206 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001207 NextReg += 2;
1208 NumAlignedDPRCS2Regs -= 2;
1209 }
1210
1211 // Finally, use a vanilla vstr.64 for the odd last register.
1212 if (NumAlignedDPRCS2Regs) {
1213 MBB.addLiveIn(NextReg);
1214 // vstr.64 uses addrmode5 which has an offset scale of 4.
1215 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1216 .addReg(NextReg)
1217 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1218 }
1219
1220 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001221 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001222}
1223
1224/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1225/// iterator to the following instruction.
1226static MachineBasicBlock::iterator
1227skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1228 unsigned NumAlignedDPRCS2Regs) {
1229 // sub r4, sp, #numregs * 8
1230 // bic r4, r4, #align - 1
1231 // mov sp, r4
1232 ++MI; ++MI; ++MI;
1233 assert(MI->mayStore() && "Expecting spill instruction");
1234
1235 // These switches all fall through.
1236 switch(NumAlignedDPRCS2Regs) {
1237 case 7:
1238 ++MI;
1239 assert(MI->mayStore() && "Expecting spill instruction");
1240 default:
1241 ++MI;
1242 assert(MI->mayStore() && "Expecting spill instruction");
1243 case 1:
1244 case 2:
1245 case 4:
1246 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1247 ++MI;
1248 }
1249 return MI;
1250}
1251
1252/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1253/// starting from d8. These instructions are assumed to execute while the
1254/// stack is still aligned, unlike the code inserted by emitPopInst.
1255static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1256 MachineBasicBlock::iterator MI,
1257 unsigned NumAlignedDPRCS2Regs,
1258 const std::vector<CalleeSavedInfo> &CSI,
1259 const TargetRegisterInfo *TRI) {
1260 MachineFunction &MF = *MBB.getParent();
1261 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1262 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001263 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001264
1265 // Find the frame index assigned to d8.
1266 int D8SpillFI = 0;
1267 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1268 if (CSI[i].getReg() == ARM::D8) {
1269 D8SpillFI = CSI[i].getFrameIdx();
1270 break;
1271 }
1272
1273 // Materialize the address of the d8 spill slot into the scratch register r4.
1274 // This can be fairly complicated if the stack frame is large, so just use
1275 // the normal frame index elimination mechanism to do it. This code runs as
1276 // the initial part of the epilog where the stack and base pointers haven't
1277 // been changed yet.
1278 bool isThumb = AFI->isThumbFunction();
1279 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1280
1281 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1282 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1283 .addFrameIndex(D8SpillFI).addImm(0)));
1284
1285 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1286 unsigned NextReg = ARM::D8;
1287
1288 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1289 if (NumAlignedDPRCS2Regs >= 6) {
1290 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001291 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001292 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1293 .addReg(ARM::R4, RegState::Define)
1294 .addReg(ARM::R4, RegState::Kill).addImm(16)
1295 .addReg(SupReg, RegState::ImplicitDefine));
1296 NextReg += 4;
1297 NumAlignedDPRCS2Regs -= 4;
1298 }
1299
1300 // We won't modify r4 beyond this point. It currently points to the next
1301 // register to be spilled.
1302 unsigned R4BaseReg = NextReg;
1303
1304 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1305 if (NumAlignedDPRCS2Regs >= 4) {
1306 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001307 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001308 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1309 .addReg(ARM::R4).addImm(16)
1310 .addReg(SupReg, RegState::ImplicitDefine));
1311 NextReg += 4;
1312 NumAlignedDPRCS2Regs -= 4;
1313 }
1314
1315 // 16-byte aligned vld1.64 with 2 d-regs.
1316 if (NumAlignedDPRCS2Regs >= 2) {
1317 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001318 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001319 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1320 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001321 NextReg += 2;
1322 NumAlignedDPRCS2Regs -= 2;
1323 }
1324
1325 // Finally, use a vanilla vldr.64 for the remaining odd register.
1326 if (NumAlignedDPRCS2Regs)
1327 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1328 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1329
1330 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001331 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001332}
1333
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001334bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001335 MachineBasicBlock::iterator MI,
1336 const std::vector<CalleeSavedInfo> &CSI,
1337 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001338 if (CSI.empty())
1339 return false;
1340
1341 MachineFunction &MF = *MBB.getParent();
1342 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001343
1344 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001345 unsigned PushOneOpc = AFI->isThumbFunction() ?
1346 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001347 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001348 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1349 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001350 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001351 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001352 MachineInstr::FrameSetup);
1353 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001354 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1355
1356 // The code above does not insert spill code for the aligned DPRCS2 registers.
1357 // The stack realignment code will be inserted between the push instructions
1358 // and these spills.
1359 if (NumAlignedDPRCS2Regs)
1360 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001361
1362 return true;
1363}
1364
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001365bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001366 MachineBasicBlock::iterator MI,
1367 const std::vector<CalleeSavedInfo> &CSI,
1368 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001369 if (CSI.empty())
1370 return false;
1371
1372 MachineFunction &MF = *MBB.getParent();
1373 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001374 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001375 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1376
1377 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1378 // registers. Do that here instead.
1379 if (NumAlignedDPRCS2Regs)
1380 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001381
1382 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001383 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001384 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001385 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1386 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001387 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001388 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001389 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001390 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001391
1392 return true;
1393}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001394
1395// FIXME: Make generic?
1396static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1397 const ARMBaseInstrInfo &TII) {
1398 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001399 for (auto &MBB : MF) {
1400 for (auto &MI : MBB)
1401 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001402 }
1403 return FnSize;
1404}
1405
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001406/// estimateRSStackSizeLimit - Look at each instruction that references stack
1407/// frames and return the stack size limit beyond which some of these
1408/// instructions will require a scratch register during their expansion later.
1409// FIXME: Move to TII?
1410static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001411 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001412 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1413 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001414 for (auto &MBB : MF) {
1415 for (auto &MI : MBB) {
1416 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1417 if (!MI.getOperand(i).isFI())
1418 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001419
1420 // When using ADDri to get the address of a stack object, 255 is the
1421 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001422 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001423 Limit = std::min(Limit, (1U << 8) - 1);
1424 break;
1425 }
1426
1427 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001428 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001429 case ARMII::AddrMode3:
1430 case ARMII::AddrModeT2_i8:
1431 Limit = std::min(Limit, (1U << 8) - 1);
1432 break;
1433 case ARMII::AddrMode5:
1434 case ARMII::AddrModeT2_i8s4:
1435 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1436 break;
1437 case ARMII::AddrModeT2_i12:
1438 // i12 supports only positive offset so these will be converted to
1439 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1440 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1441 Limit = std::min(Limit, (1U << 8) - 1);
1442 break;
1443 case ARMII::AddrMode4:
1444 case ARMII::AddrMode6:
1445 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1446 // immediate offset for stack references.
1447 return 0;
1448 default:
1449 break;
1450 }
1451 break; // At most one FI per instruction
1452 }
1453 }
1454 }
1455
1456 return Limit;
1457}
1458
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001459// In functions that realign the stack, it can be an advantage to spill the
1460// callee-saved vector registers after realigning the stack. The vst1 and vld1
1461// instructions take alignment hints that can improve performance.
1462//
1463static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1464 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1465 if (!SpillAlignedNEONRegs)
1466 return;
1467
1468 // Naked functions don't spill callee-saved registers.
Duncan P. N. Exon Smith2cff9e12015-02-14 02:24:44 +00001469 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001470 return;
1471
1472 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001473 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001474 return;
1475
1476 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001477 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001478 return;
1479
1480 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001481 if (!static_cast<const ARMBaseRegisterInfo *>(
1482 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001483 return;
1484
1485 // We always spill contiguous d-registers starting from d8. Count how many
1486 // needs spilling. The register allocator will almost always use the
1487 // callee-saved registers in order, but it can happen that there are holes in
1488 // the range. Registers above the hole will be spilled to the standard DPRCS
1489 // area.
1490 MachineRegisterInfo &MRI = MF.getRegInfo();
1491 unsigned NumSpills = 0;
1492 for (; NumSpills < 8; ++NumSpills)
Jakob Stoklund Olesen07364422012-10-17 18:44:18 +00001493 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001494 break;
1495
1496 // Don't do this for just one d-register. It's not worth it.
1497 if (NumSpills < 2)
1498 return;
1499
1500 // Spill the first NumSpills D-registers after realigning the stack.
1501 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1502
1503 // A scratch register is required for the vst1 / vld1 instructions.
1504 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1505}
1506
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001507void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001508ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +00001509 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001510 // This tells PEI to spill the FP as if it is any other callee-save register
1511 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1512 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1513 // to combine multiple loads / stores.
1514 bool CanEliminateFrame = true;
1515 bool CS1Spilled = false;
1516 bool LRSpilled = false;
1517 unsigned NumGPRSpills = 0;
1518 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1519 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001520 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001521 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001522 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001523 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001524 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1525 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001526 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001527 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1528
1529 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1530 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001531 // since it's not always possible to restore sp from fp in a single
1532 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001533 // FIXME: It will be better just to find spare register here.
1534 if (AFI->isThumb2Function() &&
1535 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001536 MRI.setPhysRegUsed(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001537
Evan Cheng572756a2011-01-16 05:14:33 +00001538 if (AFI->isThumb1OnlyFunction()) {
1539 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001540 if (AFI->getArgRegsSaveSize() > 0)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001541 MRI.setPhysRegUsed(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001542
Jim Grosbachdca85312011-06-13 21:18:25 +00001543 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1544 // for sure what the stack size will be, but for this, an estimate is good
1545 // enough. If there anything changes it, it'll be a spill, which implies
1546 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001547 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001548 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001549 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001550 if (MFI->hasVarSizedObjects() || StackSize > 508)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001551 MRI.setPhysRegUsed(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001552 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001553
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001554 // See if we can spill vector registers to aligned stack.
1555 checkNumAlignedDPRCS2Regs(MF);
1556
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001557 // Spill the BasePtr if it's used.
1558 if (RegInfo->hasBasePointer(MF))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001559 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001560
1561 // Don't spill FP if the frame can be eliminated. This is determined
1562 // by scanning the callee-save registers to see if any is used.
Craig Topper840beec2014-04-04 05:16:06 +00001563 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001564 for (unsigned i = 0; CSRegs[i]; ++i) {
1565 unsigned Reg = CSRegs[i];
1566 bool Spilled = false;
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001567 if (MRI.isPhysRegUsed(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001568 Spilled = true;
1569 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001570 }
1571
Craig Topperc7242e02012-04-20 07:30:17 +00001572 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001573 continue;
1574
1575 if (Spilled) {
1576 NumGPRSpills++;
1577
Tim Northover86f60b72014-05-30 13:23:06 +00001578 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001579 if (Reg == ARM::LR)
1580 LRSpilled = true;
1581 CS1Spilled = true;
1582 continue;
1583 }
1584
1585 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1586 switch (Reg) {
1587 case ARM::LR:
1588 LRSpilled = true;
1589 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001590 case ARM::R0: case ARM::R1:
1591 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001592 case ARM::R4: case ARM::R5:
1593 case ARM::R6: case ARM::R7:
1594 CS1Spilled = true;
1595 break;
1596 default:
1597 break;
1598 }
1599 } else {
Tim Northover86f60b72014-05-30 13:23:06 +00001600 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001601 UnspilledCS1GPRs.push_back(Reg);
1602 continue;
1603 }
1604
1605 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001606 case ARM::R0: case ARM::R1:
1607 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001608 case ARM::R4: case ARM::R5:
1609 case ARM::R6: case ARM::R7:
1610 case ARM::LR:
1611 UnspilledCS1GPRs.push_back(Reg);
1612 break;
1613 default:
1614 UnspilledCS2GPRs.push_back(Reg);
1615 break;
1616 }
1617 }
1618 }
1619
1620 bool ForceLRSpill = false;
1621 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1622 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1623 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1624 // use of BL to implement far jump. If it turns out that it's not needed
1625 // then the branch fix up path will undo it.
1626 if (FnSize >= (1 << 11)) {
1627 CanEliminateFrame = false;
1628 ForceLRSpill = true;
1629 }
1630 }
1631
1632 // If any of the stack slot references may be out of range of an immediate
1633 // offset, make sure a register (or a spill slot) is available for the
1634 // register scavenger. Note that if we're indexing off the frame pointer, the
1635 // effective stack size is 4 bytes larger since the FP points to the stack
1636 // slot of the previous FP. Also, if we have variable sized objects in the
1637 // function, stack slot references will often be negative, and some of
1638 // our instructions are positive-offset only, so conservatively consider
1639 // that case to want a spill slot (or register) as well. Similarly, if
1640 // the function adjusts the stack pointer during execution and the
1641 // adjustments aren't already part of our stack size estimate, our offset
1642 // calculations may be off, so be conservative.
1643 // FIXME: We could add logic to be more precise about negative offsets
1644 // and which instructions will need a scratch register for them. Is it
1645 // worth the effort and added fragility?
1646 bool BigStack =
1647 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001648 (MFI->estimateStackSize(MF) +
1649 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001650 estimateRSStackSizeLimit(MF, this)))
1651 || MFI->hasVarSizedObjects()
1652 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1653
1654 bool ExtraCSSpill = false;
1655 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1656 AFI->setHasStackFrame(true);
1657
1658 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1659 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1660 if (!LRSpilled && CS1Spilled) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001661 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001662 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001663 SmallVectorImpl<unsigned>::iterator LRPos;
1664 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1665 (unsigned)ARM::LR);
1666 if (LRPos != UnspilledCS1GPRs.end())
1667 UnspilledCS1GPRs.erase(LRPos);
1668
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001669 ForceLRSpill = false;
1670 ExtraCSSpill = true;
1671 }
1672
1673 if (hasFP(MF)) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001674 MRI.setPhysRegUsed(FramePtr);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001675 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1676 FramePtr);
1677 if (FPPos != UnspilledCS1GPRs.end())
1678 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001679 NumGPRSpills++;
1680 }
1681
1682 // If stack and double are 8-byte aligned and we are spilling an odd number
1683 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1684 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001685 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001686 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001687 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1688 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1689 unsigned Reg = UnspilledCS1GPRs[i];
1690 // Don't spill high register if the function is thumb1
1691 if (!AFI->isThumb1OnlyFunction() ||
1692 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001693 MRI.setPhysRegUsed(Reg);
1694 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001695 ExtraCSSpill = true;
1696 break;
1697 }
1698 }
1699 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1700 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001701 MRI.setPhysRegUsed(Reg);
1702 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001703 ExtraCSSpill = true;
1704 }
1705 }
1706
1707 // Estimate if we might need to scavenge a register at some point in order
1708 // to materialize a stack offset. If so, either spill one additional
1709 // callee-saved register or reserve a special spill slot to facilitate
1710 // register scavenging. Thumb1 needs a spill slot for stack pointer
1711 // adjustments also, even when the frame itself is small.
1712 if (BigStack && !ExtraCSSpill) {
1713 // If any non-reserved CS register isn't spilled, just spill one or two
1714 // extra. That should take care of it!
1715 unsigned NumExtras = TargetAlign / 4;
1716 SmallVector<unsigned, 2> Extras;
1717 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1718 unsigned Reg = UnspilledCS1GPRs.back();
1719 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001720 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001721 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1722 Reg == ARM::LR)) {
1723 Extras.push_back(Reg);
1724 NumExtras--;
1725 }
1726 }
1727 // For non-Thumb1 functions, also check for hi-reg CS registers
1728 if (!AFI->isThumb1OnlyFunction()) {
1729 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1730 unsigned Reg = UnspilledCS2GPRs.back();
1731 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001732 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001733 Extras.push_back(Reg);
1734 NumExtras--;
1735 }
1736 }
1737 }
1738 if (Extras.size() && NumExtras == 0) {
1739 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001740 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001741 }
1742 } else if (!AFI->isThumb1OnlyFunction()) {
1743 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1744 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001745 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001746 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001747 RC->getAlignment(),
1748 false));
1749 }
1750 }
1751 }
1752
1753 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001754 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001755 AFI->setLRIsSpilledForFarJump(true);
1756 }
1757}
Eli Bendersky8da87162013-02-21 20:05:00 +00001758
1759
1760void ARMFrameLowering::
1761eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1762 MachineBasicBlock::iterator I) const {
1763 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001764 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001765 if (!hasReservedCallFrame(MF)) {
1766 // If we have alloca, convert as follows:
1767 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1768 // ADJCALLSTACKUP -> add, sp, sp, amount
1769 MachineInstr *Old = I;
1770 DebugLoc dl = Old->getDebugLoc();
1771 unsigned Amount = Old->getOperand(0).getImm();
1772 if (Amount != 0) {
1773 // We need to keep the stack aligned properly. To do this, we round the
1774 // amount of space needed for the outgoing arguments up to the next
1775 // alignment boundary.
1776 unsigned Align = getStackAlignment();
1777 Amount = (Amount+Align-1)/Align*Align;
1778
1779 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1780 assert(!AFI->isThumb1OnlyFunction() &&
1781 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1782 bool isARM = !AFI->isThumbFunction();
1783
1784 // Replace the pseudo instruction with a new instruction...
1785 unsigned Opc = Old->getOpcode();
1786 int PIdx = Old->findFirstPredOperandIdx();
1787 ARMCC::CondCodes Pred = (PIdx == -1)
1788 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1789 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1790 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1791 unsigned PredReg = Old->getOperand(2).getReg();
1792 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1793 Pred, PredReg);
1794 } else {
1795 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1796 unsigned PredReg = Old->getOperand(3).getReg();
1797 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1798 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1799 Pred, PredReg);
1800 }
1801 }
1802 }
1803 MBB.erase(I);
1804}
1805
Oliver Stannardb14c6252014-04-02 16:10:33 +00001806/// Get the minimum constant for ARM that is greater than or equal to the
1807/// argument. In ARM, constants can have any value that can be produced by
1808/// rotating an 8-bit value to the right by an even number of bits within a
1809/// 32-bit word.
1810static uint32_t alignToARMConstant(uint32_t Value) {
1811 unsigned Shifted = 0;
1812
1813 if (Value == 0)
1814 return 0;
1815
1816 while (!(Value & 0xC0000000)) {
1817 Value = Value << 2;
1818 Shifted += 2;
1819 }
1820
1821 bool Carry = (Value & 0x00FFFFFF);
1822 Value = ((Value & 0xFF000000) >> 24) + Carry;
1823
1824 if (Value & 0x0000100)
1825 Value = Value & 0x000001FC;
1826
1827 if (Shifted > 24)
1828 Value = Value >> (Shifted - 24);
1829 else
1830 Value = Value << (24 - Shifted);
1831
1832 return Value;
1833}
1834
1835// The stack limit in the TCB is set to this many bytes above the actual
1836// stack limit.
1837static const uint64_t kSplitStackAvailable = 256;
1838
1839// Adjust the function prologue to enable split stacks. This currently only
1840// supports android and linux.
1841//
1842// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1843// must be well defined in order to allow for consistent implementations of the
1844// __morestack helper function. The ABI is also not a normal ABI in that it
1845// doesn't follow the normal calling conventions because this allows the
1846// prologue of each function to be optimized further.
1847//
1848// Currently, the ABI looks like (when calling __morestack)
1849//
1850// * r4 holds the minimum stack size requested for this function call
1851// * r5 holds the stack size of the arguments to the function
1852// * the beginning of the function is 3 instructions after the call to
1853// __morestack
1854//
1855// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1856// place the arguments on to the new stack, and the 3-instruction knowledge to
1857// jump directly to the body of the function when working on the new stack.
1858//
1859// An old (and possibly no longer compatible) implementation of __morestack for
1860// ARM can be found at [1].
1861//
1862// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1863void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1864 unsigned Opcode;
1865 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00001866 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00001867 bool Thumb = ST->isThumb();
1868
1869 // Sadly, this currently doesn't support varargs, platforms other than
1870 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1871 if (MF.getFunction()->isVarArg())
1872 report_fatal_error("Segmented stacks do not support vararg functions.");
1873 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001874 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001875
1876 MachineBasicBlock &prologueMBB = MF.front();
1877 MachineFrameInfo *MFI = MF.getFrameInfo();
1878 MachineModuleInfo &MMI = MF.getMMI();
1879 MCContext &Context = MMI.getContext();
1880 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1881 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001882 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00001883 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1884 DebugLoc DL;
1885
Tim Northoverf9e798b2014-05-22 13:03:43 +00001886 uint64_t StackSize = MFI->getStackSize();
1887
1888 // Do not generate a prologue for functions with a stack of size zero
1889 if (StackSize == 0)
1890 return;
1891
Oliver Stannardb14c6252014-04-02 16:10:33 +00001892 // Use R4 and R5 as scratch registers.
1893 // We save R4 and R5 before use and restore them before leaving the function.
1894 unsigned ScratchReg0 = ARM::R4;
1895 unsigned ScratchReg1 = ARM::R5;
1896 uint64_t AlignedStackSize;
1897
1898 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1899 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1900 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1901 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1902 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1903
1904 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1905 e = prologueMBB.livein_end();
1906 i != e; ++i) {
1907 AllocMBB->addLiveIn(*i);
1908 GetMBB->addLiveIn(*i);
1909 McrMBB->addLiveIn(*i);
1910 PrevStackMBB->addLiveIn(*i);
1911 PostStackMBB->addLiveIn(*i);
1912 }
1913
1914 MF.push_front(PostStackMBB);
1915 MF.push_front(AllocMBB);
1916 MF.push_front(GetMBB);
1917 MF.push_front(McrMBB);
1918 MF.push_front(PrevStackMBB);
1919
1920 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00001921 AlignedStackSize = alignToARMConstant(StackSize);
1922
1923 // When the frame size is less than 256 we just compare the stack
1924 // boundary directly to the value of the stack pointer, per gcc.
1925 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1926
1927 // We will use two of the callee save registers as scratch registers so we
1928 // need to save those registers onto the stack.
1929 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1930 // requested and arguments for __morestack().
1931 // SR0: Scratch Register #0
1932 // SR1: Scratch Register #1
1933 // push {SR0, SR1}
1934 if (Thumb) {
1935 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1936 .addReg(ScratchReg0).addReg(ScratchReg1);
1937 } else {
1938 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1939 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1940 .addReg(ScratchReg0).addReg(ScratchReg1);
1941 }
1942
1943 // Emit the relevant DWARF information about the change in stack pointer as
1944 // well as where to find both r4 and r5 (the callee-save registers)
1945 CFIIndex =
1946 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1947 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1948 .addCFIIndex(CFIIndex);
1949 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1950 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1951 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1952 .addCFIIndex(CFIIndex);
1953 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1954 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1955 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1956 .addCFIIndex(CFIIndex);
1957
1958 // mov SR1, sp
1959 if (Thumb) {
1960 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1961 .addReg(ARM::SP));
1962 } else if (CompareStackPointer) {
1963 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1964 .addReg(ARM::SP)).addReg(0);
1965 }
1966
1967 // sub SR1, sp, #StackSize
1968 if (!CompareStackPointer && Thumb) {
1969 AddDefaultPred(
1970 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1971 .addReg(ScratchReg1).addImm(AlignedStackSize));
1972 } else if (!CompareStackPointer) {
1973 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1974 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1975 }
1976
1977 if (Thumb && ST->isThumb1Only()) {
1978 unsigned PCLabelId = ARMFI->createPICLabelUId();
1979 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001980 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001981 MachineConstantPool *MCP = MF.getConstantPool();
1982 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1983
1984 // ldr SR0, [pc, offset(STACK_LIMIT)]
1985 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1986 .addConstantPoolIndex(CPI));
1987
1988 // ldr SR0, [SR0]
1989 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1990 .addReg(ScratchReg0).addImm(0));
1991 } else {
1992 // Get TLS base address from the coprocessor
1993 // mrc p15, #0, SR0, c13, c0, #3
1994 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1995 .addImm(15)
1996 .addImm(0)
1997 .addImm(13)
1998 .addImm(0)
1999 .addImm(3));
2000
2001 // Use the last tls slot on android and a private field of the TCP on linux.
2002 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2003 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2004
2005 // Get the stack limit from the right offset
2006 // ldr SR0, [sr0, #4 * TlsOffset]
2007 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2008 .addReg(ScratchReg0).addImm(4 * TlsOffset));
2009 }
2010
2011 // Compare stack limit with stack size requested.
2012 // cmp SR0, SR1
2013 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2014 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2015 .addReg(ScratchReg0)
2016 .addReg(ScratchReg1));
2017
2018 // This jump is taken if StackLimit < SP - stack required.
2019 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2020 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2021 .addImm(ARMCC::LO)
2022 .addReg(ARM::CPSR);
2023
2024
2025 // Calling __morestack(StackSize, Size of stack arguments).
2026 // __morestack knows that the stack size requested is in SR0(r4)
2027 // and amount size of stack arguments is in SR1(r5).
2028
2029 // Pass first argument for the __morestack by Scratch Register #0.
2030 // The amount size of stack required
2031 if (Thumb) {
2032 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2033 ScratchReg0)).addImm(AlignedStackSize));
2034 } else {
2035 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2036 .addImm(AlignedStackSize)).addReg(0);
2037 }
2038 // Pass second argument for the __morestack by Scratch Register #1.
2039 // The amount size of stack consumed to save function arguments.
2040 if (Thumb) {
2041 AddDefaultPred(
2042 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2043 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2044 } else {
2045 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2046 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2047 .addReg(0);
2048 }
2049
2050 // push {lr} - Save return address of this function.
2051 if (Thumb) {
2052 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2053 .addReg(ARM::LR);
2054 } else {
2055 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2056 .addReg(ARM::SP, RegState::Define)
2057 .addReg(ARM::SP))
2058 .addReg(ARM::LR);
2059 }
2060
2061 // Emit the DWARF info about the change in stack as well as where to find the
2062 // previous link register
2063 CFIIndex =
2064 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2065 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2066 .addCFIIndex(CFIIndex);
2067 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2068 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2069 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2070 .addCFIIndex(CFIIndex);
2071
2072 // Call __morestack().
2073 if (Thumb) {
2074 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2075 .addExternalSymbol("__morestack");
2076 } else {
2077 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2078 .addExternalSymbol("__morestack");
2079 }
2080
2081 // pop {lr} - Restore return address of this original function.
2082 if (Thumb) {
2083 if (ST->isThumb1Only()) {
2084 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2085 .addReg(ScratchReg0);
2086 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2087 .addReg(ScratchReg0));
2088 } else {
2089 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2090 .addReg(ARM::LR, RegState::Define)
2091 .addReg(ARM::SP, RegState::Define)
2092 .addReg(ARM::SP)
2093 .addImm(4));
2094 }
2095 } else {
2096 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2097 .addReg(ARM::SP, RegState::Define)
2098 .addReg(ARM::SP))
2099 .addReg(ARM::LR);
2100 }
2101
2102 // Restore SR0 and SR1 in case of __morestack() was called.
2103 // __morestack() will skip PostStackMBB block so we need to restore
2104 // scratch registers from here.
2105 // pop {SR0, SR1}
2106 if (Thumb) {
2107 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2108 .addReg(ScratchReg0)
2109 .addReg(ScratchReg1);
2110 } else {
2111 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2112 .addReg(ARM::SP, RegState::Define)
2113 .addReg(ARM::SP))
2114 .addReg(ScratchReg0)
2115 .addReg(ScratchReg1);
2116 }
2117
2118 // Update the CFA offset now that we've popped
2119 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2120 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2121 .addCFIIndex(CFIIndex);
2122
2123 // bx lr - Return from this function.
2124 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2125 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2126
2127 // Restore SR0 and SR1 in case of __morestack() was not called.
2128 // pop {SR0, SR1}
2129 if (Thumb) {
2130 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2131 .addReg(ScratchReg0)
2132 .addReg(ScratchReg1);
2133 } else {
2134 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2135 .addReg(ARM::SP, RegState::Define)
2136 .addReg(ARM::SP))
2137 .addReg(ScratchReg0)
2138 .addReg(ScratchReg1);
2139 }
2140
2141 // Update the CFA offset now that we've popped
2142 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2143 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2144 .addCFIIndex(CFIIndex);
2145
2146 // Tell debuggers that r4 and r5 are now the same as they were in the
2147 // previous function, that they're the "Same Value".
2148 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2149 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2150 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2151 .addCFIIndex(CFIIndex);
2152 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2153 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2154 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2155 .addCFIIndex(CFIIndex);
2156
2157 // Organizing MBB lists
2158 PostStackMBB->addSuccessor(&prologueMBB);
2159
2160 AllocMBB->addSuccessor(PostStackMBB);
2161
2162 GetMBB->addSuccessor(PostStackMBB);
2163 GetMBB->addSuccessor(AllocMBB);
2164
2165 McrMBB->addSuccessor(GetMBB);
2166
2167 PrevStackMBB->addSuccessor(McrMBB);
2168
2169#ifdef XDEBUG
2170 MF.verify();
2171#endif
2172}