blob: 831c2eb7984099e09dcb4c511075e9baed73df9e [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();
167 if (MFI->getStackProtectorIndex() > 0)
168 return StackSizeInBytes >= 4080;
169 return StackSizeInBytes >= 4096;
170}
171
Tim Northover603d3162014-11-14 22:45:33 +0000172namespace {
173struct StackAdjustingInsts {
174 struct InstInfo {
175 MachineBasicBlock::iterator I;
176 unsigned SPAdjust;
177 bool BeforeFPSet;
178 };
179
180 SmallVector<InstInfo, 4> Insts;
181
182 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
183 bool BeforeFPSet = false) {
184 InstInfo Info = {I, SPAdjust, BeforeFPSet};
185 Insts.push_back(Info);
186 }
187
188 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
189 auto Info = std::find_if(Insts.begin(), Insts.end(),
190 [&](InstInfo &Info) { return Info.I == I; });
191 assert(Info != Insts.end() && "invalid sp adjusting instruction");
192 Info->SPAdjust += ExtraBytes;
193 }
194
195 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
196 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
197 unsigned CFAOffset = 0;
198 for (auto &Info : Insts) {
199 if (HasFP && !Info.BeforeFPSet)
200 return;
201
202 CFAOffset -= Info.SPAdjust;
203 unsigned CFIIndex = MMI.addFrameInst(
204 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
205 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000206 TII.get(TargetOpcode::CFI_INSTRUCTION))
207 .addCFIIndex(CFIIndex)
208 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000209 }
210 }
211};
212}
213
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000214void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000215 MachineBasicBlock &MBB = MF.front();
216 MachineBasicBlock::iterator MBBI = MBB.begin();
217 MachineFrameInfo *MFI = MF.getFrameInfo();
218 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000219 MachineModuleInfo &MMI = MF.getMMI();
220 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000221 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000222 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000223 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
224 TM.getSubtargetImpl()->getRegisterInfo());
225 const ARMBaseInstrInfo &TII = *static_cast<const ARMBaseInstrInfo *>(
226 TM.getSubtargetImpl()->getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000227 assert(!AFI->isThumb1OnlyFunction() &&
228 "This emitPrologue does not support Thumb1!");
229 bool isARM = !AFI->isThumbFunction();
Eric Christopherd9134482014-08-04 21:25:23 +0000230 unsigned Align =
231 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000232 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000233 unsigned NumBytes = MFI->getStackSize();
234 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
235 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
236 unsigned FramePtr = RegInfo->getFrameRegister(MF);
237
238 // Determine the sizes of each callee-save spill areas and record which frame
239 // belongs to which callee-save spill areas.
240 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
241 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000242 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000243
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000244 // All calls are tail calls in GHC calling conv, and functions have no
245 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000246 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
247 return;
248
Tim Northover603d3162014-11-14 22:45:33 +0000249 StackAdjustingInsts DefCFAOffsetCandidates;
250
Oliver Stannardd55e1152014-03-05 15:25:27 +0000251 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000252 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000253 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000254 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000255 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000256 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000257
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000258 if (!AFI->hasStackFrame() &&
259 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000260 if (NumBytes - ArgRegsSaveSize != 0) {
261 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000262 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000263 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
264 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000265 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000266 return;
267 }
268
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000269 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000270 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
271 unsigned Reg = CSI[i].getReg();
272 int FI = CSI[i].getFrameIdx();
273 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000274 case ARM::R8:
275 case ARM::R9:
276 case ARM::R10:
277 case ARM::R11:
278 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000279 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000280 GPRCS2Size += 4;
281 break;
282 }
283 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000284 case ARM::R0:
285 case ARM::R1:
286 case ARM::R2:
287 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000288 case ARM::R4:
289 case ARM::R5:
290 case ARM::R6:
291 case ARM::R7:
292 case ARM::LR:
293 if (Reg == FramePtr)
294 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000295 GPRCS1Size += 4;
296 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000297 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000298 // This is a DPR. Exclude the aligned DPRCS2 spills.
299 if (Reg == ARM::D8)
300 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000301 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000302 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000303 }
304 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000305
Eric Christopherb006fc92010-11-18 19:40:05 +0000306 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000307 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
308 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000309 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000310 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
311 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000312
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000313 // Determine starting offsets of spill areas.
Tim Northoverc9432eb2013-11-04 23:04:15 +0000314 bool HasFP = hasFP(MF);
Tim Northover228c9432014-11-05 00:27:13 +0000315 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
316 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
317 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
318 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
319 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000320 int FramePtrOffsetInPush = 0;
321 if (HasFP) {
Tim Northover603d3162014-11-14 22:45:33 +0000322 FramePtrOffsetInPush =
323 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000324 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
325 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000326 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000327 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
328 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
329 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
330
Tim Northoverc9432eb2013-11-04 23:04:15 +0000331 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000332 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000333 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000334 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
335 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000336
Tim Northover228c9432014-11-05 00:27:13 +0000337 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
338 // .cfi_offset operations will reflect that.
339 if (DPRGapSize) {
340 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Tim Northover603d3162014-11-14 22:45:33 +0000341 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
342 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
343 else {
Tim Northover228c9432014-11-05 00:27:13 +0000344 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
345 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000346 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
347 }
Tim Northover228c9432014-11-05 00:27:13 +0000348 }
349
Eric Christopherb006fc92010-11-18 19:40:05 +0000350 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000351 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000352 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000353 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000354 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
355 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000356 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000357 }
Evan Cheng70d29632011-02-25 00:24:46 +0000358 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000359
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000360 // Move past the aligned DPRCS2 area.
361 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
362 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
363 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
364 // leaves the stack pointer pointing to the DPRCS2 area.
365 //
366 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
367 NumBytes += MFI->getObjectOffset(D8SpillFI);
368 } else
369 NumBytes = DPRCSOffset;
370
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000371 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
372 uint32_t NumWords = NumBytes >> 2;
373
374 if (NumWords < 65536)
375 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000376 .addImm(NumWords)
377 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000378 else
379 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000380 .addImm(NumWords)
381 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000382
383 switch (TM.getCodeModel()) {
384 case CodeModel::Small:
385 case CodeModel::Medium:
386 case CodeModel::Default:
387 case CodeModel::Kernel:
388 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
389 .addImm((unsigned)ARMCC::AL).addReg(0)
390 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000391 .addReg(ARM::R4, RegState::Implicit)
392 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000393 break;
394 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000395 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000396 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000397 .addExternalSymbol("__chkstk")
398 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000399
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000400 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
401 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000402 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000403 .addReg(ARM::R4, RegState::Implicit)
404 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000405 break;
406 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000407
408 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
409 ARM::SP)
410 .addReg(ARM::SP, RegState::Define)
411 .addReg(ARM::R4, RegState::Kill)
412 .setMIFlags(MachineInstr::FrameSetup)));
413 NumBytes = 0;
414 }
415
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000416 if (NumBytes) {
417 // Adjust SP after all the callee-save spills.
Tim Northover603d3162014-11-14 22:45:33 +0000418 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
419 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
420 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000421 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
422 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000423 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
424 }
Tim Northover93bcc662013-11-08 17:18:07 +0000425
Evan Chengeb56dca2010-11-22 18:12:04 +0000426 if (HasFP && isARM)
427 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
428 // Note it's not safe to do this in Thumb2 mode because it would have
429 // taken two instructions:
430 // mov sp, r7
431 // sub sp, #24
432 // If an interrupt is taken between the two instructions, then sp is in
433 // an inconsistent state (pointing to the middle of callee-saved area).
434 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000435 AFI->setShouldRestoreSPFromFP(true);
436 }
437
Tim Northover603d3162014-11-14 22:45:33 +0000438 // Set FP to point to the stack slot that contains the previous FP.
439 // For iOS, FP is R7, which has now been stored in spill area 1.
440 // Otherwise, if this is not iOS, all the callee-saved registers go
441 // into spill area 1, including the FP in R11. In either case, it
442 // is in area one and the adjustment needs to take place just after
443 // that push.
444 if (HasFP) {
445 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
446 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
447 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
448 dl, TII, FramePtr, ARM::SP,
449 PushSize + FramePtrOffsetInPush,
450 MachineInstr::FrameSetup);
451 if (FramePtrOffsetInPush + PushSize != 0) {
452 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
453 nullptr, MRI->getDwarfRegNum(FramePtr, true),
454 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
455 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000456 .addCFIIndex(CFIIndex)
457 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000458 } else {
459 unsigned CFIIndex =
460 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
461 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
462 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000463 .addCFIIndex(CFIIndex)
464 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000465 }
466 }
467
468 // Now that the prologue's actual instructions are finalised, we can insert
469 // the necessary DWARF cf instructions to describe the situation. Start by
470 // recording where each register ended up:
471 if (GPRCS1Size > 0) {
472 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
473 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000474 for (const auto &Entry : CSI) {
475 unsigned Reg = Entry.getReg();
476 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000477 switch (Reg) {
478 case ARM::R8:
479 case ARM::R9:
480 case ARM::R10:
481 case ARM::R11:
482 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000483 if (STI.isTargetDarwin())
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000484 break;
485 // fallthrough
486 case ARM::R0:
487 case ARM::R1:
488 case ARM::R2:
489 case ARM::R3:
490 case ARM::R4:
491 case ARM::R5:
492 case ARM::R6:
493 case ARM::R7:
494 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000495 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
496 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
497 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000498 .addCFIIndex(CFIIndex)
499 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000500 break;
501 }
502 }
503 }
504
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000505 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000506 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000507 for (const auto &Entry : CSI) {
508 unsigned Reg = Entry.getReg();
509 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000510 switch (Reg) {
511 case ARM::R8:
512 case ARM::R9:
513 case ARM::R10:
514 case ARM::R11:
515 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000516 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000517 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000518 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000519 unsigned CFIIndex = MMI.addFrameInst(
520 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
521 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000522 .addCFIIndex(CFIIndex)
523 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000524 }
525 break;
526 }
527 }
528 }
529
530 if (DPRCSSize > 0) {
531 // Since vpush register list cannot have gaps, there may be multiple vpush
532 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000533 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000534 for (const auto &Entry : CSI) {
535 unsigned Reg = Entry.getReg();
536 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000537 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
538 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
539 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
540 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000541 unsigned CFIIndex = MMI.addFrameInst(
542 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000543 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000544 .addCFIIndex(CFIIndex)
545 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000546 }
547 }
548 }
549
Tim Northover603d3162014-11-14 22:45:33 +0000550 // Now we can emit descriptions of where the canonical frame address was
551 // throughout the process. If we have a frame pointer, it takes over the job
552 // half-way through, so only the first few .cfi_def_cfa_offset instructions
553 // actually get emitted.
554 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000555
Evan Chengeb56dca2010-11-22 18:12:04 +0000556 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000557 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
558 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000559
560 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
561 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000562 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000563 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
564
565 // If we need dynamic stack realignment, do it here. Be paranoid and make
566 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000567 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000568 // realigned.
569 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000570 unsigned MaxAlign = MFI->getMaxAlignment();
571 assert (!AFI->isThumb1OnlyFunction());
572 if (!AFI->isThumbFunction()) {
573 // Emit bic sp, sp, MaxAlign
574 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
575 TII.get(ARM::BICri), ARM::SP)
576 .addReg(ARM::SP, RegState::Kill)
577 .addImm(MaxAlign-1)));
578 } else {
579 // We cannot use sp as source/dest register here, thus we're emitting the
580 // following sequence:
581 // mov r4, sp
582 // bic r4, r4, MaxAlign
583 // mov sp, r4
584 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000585 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000586 .addReg(ARM::SP, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000587 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
588 TII.get(ARM::t2BICri), ARM::R4)
589 .addReg(ARM::R4, RegState::Kill)
590 .addImm(MaxAlign-1)));
Jim Grosbache9cc9012011-06-30 23:38:17 +0000591 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000592 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000593 }
594
595 AFI->setShouldRestoreSPFromFP(true);
596 }
597
598 // If we need a base pointer, set it up here. It's whatever the value
599 // of the stack pointer is at this point. Any variable size objects
600 // will be allocated after this, so we can still use the base pointer
601 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000602 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000603 if (RegInfo->hasBasePointer(MF)) {
604 if (isARM)
605 BuildMI(MBB, MBBI, dl,
606 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
607 .addReg(ARM::SP)
608 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
609 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000610 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000611 RegInfo->getBaseRegister())
612 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000613 }
614
615 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000616 // the sp from fp. We can assume there's an FP here since hasFP already
617 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000618 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000619 AFI->setShouldRestoreSPFromFP(true);
620}
621
Tim Northover3024b552014-12-01 17:46:39 +0000622// Resolve TCReturn pseudo-instruction
623void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
624 MachineBasicBlock &MBB) const {
625 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
626 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
627 unsigned RetOpcode = MBBI->getOpcode();
628 DebugLoc dl = MBBI->getDebugLoc();
629 const ARMBaseInstrInfo &TII =
630 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
631
632 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
633 return;
634
635 // Tail call return: adjust the stack pointer and jump to callee.
636 MBBI = MBB.getLastNonDebugInstr();
637 MachineOperand &JumpTarget = MBBI->getOperand(0);
638
639 // Jump to label or value in register.
640 if (RetOpcode == ARM::TCRETURNdi) {
641 unsigned TCOpcode = STI.isThumb() ?
642 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
643 ARM::TAILJMPd;
644 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
645 if (JumpTarget.isGlobal())
646 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
647 JumpTarget.getTargetFlags());
648 else {
649 assert(JumpTarget.isSymbol());
650 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
651 JumpTarget.getTargetFlags());
652 }
653
654 // Add the default predicate in Thumb mode.
655 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
656 } else if (RetOpcode == ARM::TCRETURNri) {
657 BuildMI(MBB, MBBI, dl,
658 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
659 addReg(JumpTarget.getReg(), RegState::Kill);
660 }
661
662 MachineInstr *NewMI = std::prev(MBBI);
663 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
664 NewMI->addOperand(MBBI->getOperand(i));
665
666 // Delete the pseudo instruction TCRETURN.
667 MBB.erase(MBBI);
668 MBBI = NewMI;
669}
670
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000671void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000672 MachineBasicBlock &MBB) const {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000673 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000674 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000675 DebugLoc dl = MBBI->getDebugLoc();
676 MachineFrameInfo *MFI = MF.getFrameInfo();
677 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000678 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000679 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000680 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000681 assert(!AFI->isThumb1OnlyFunction() &&
682 "This emitEpilogue does not support Thumb1!");
683 bool isARM = !AFI->isThumbFunction();
684
Eric Christopherd9134482014-08-04 21:25:23 +0000685 unsigned Align = MF.getTarget()
686 .getSubtargetImpl()
687 ->getFrameLowering()
688 ->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000689 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000690 int NumBytes = (int)MFI->getStackSize();
691 unsigned FramePtr = RegInfo->getFrameRegister(MF);
692
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000693 // All calls are tail calls in GHC calling conv, and functions have no
694 // prologue/epilogue.
Tim Northover3024b552014-12-01 17:46:39 +0000695 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
696 fixTCReturn(MF, MBB);
Eric Christopherb3322362012-08-03 00:05:53 +0000697 return;
Tim Northover3024b552014-12-01 17:46:39 +0000698 }
Eric Christopherb3322362012-08-03 00:05:53 +0000699
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000700 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000701 if (NumBytes - ArgRegsSaveSize != 0)
702 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000703 } else {
704 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000705 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000706 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000707 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000708 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000709 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000710 if (!isCSRestore(MBBI, TII, CSRegs))
711 ++MBBI;
712 }
713
714 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000715 NumBytes -= (ArgRegsSaveSize +
716 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000717 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000718 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000719 AFI->getDPRCalleeSavedAreaSize());
720
721 // Reset SP based on frame pointer only if the stack frame extends beyond
722 // frame pointer stack slot or target is ELF and the function has FP.
723 if (AFI->shouldRestoreSPFromFP()) {
724 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
725 if (NumBytes) {
726 if (isARM)
727 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
728 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000729 else {
730 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000731 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000732 // mov sp, r7
733 // sub sp, #24
734 // This is bad, if an interrupt is taken after the mov, sp is in an
735 // inconsistent state.
736 // Use the first callee-saved register as a scratch register.
Kaelyn Uhrain271fbb62012-10-26 23:28:41 +0000737 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000738 "No scratch register to restore SP from FP!");
739 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000740 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000741 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000742 ARM::SP)
743 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000744 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000745 } else {
746 // Thumb2 or ARM.
747 if (isARM)
748 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
749 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
750 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000751 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000752 ARM::SP)
753 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000754 }
Tim Northoverdee86042013-12-02 14:46:26 +0000755 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000756 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000757 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000758
Eric Christopherb006fc92010-11-18 19:40:05 +0000759 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000760 if (AFI->getDPRCalleeSavedAreaSize()) {
761 MBBI++;
762 // Since vpop register list cannot have gaps, there may be multiple vpop
763 // instructions in the epilogue.
764 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
765 MBBI++;
766 }
Tim Northover228c9432014-11-05 00:27:13 +0000767 if (AFI->getDPRCalleeSavedGapSize()) {
768 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
769 "unexpected DPR alignment gap");
770 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
771 }
772
Eric Christopherb006fc92010-11-18 19:40:05 +0000773 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
774 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000775 }
776
Tim Northover3024b552014-12-01 17:46:39 +0000777 fixTCReturn(MF, MBB);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000778
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000779 if (ArgRegsSaveSize)
780 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000781}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000782
Bob Wilson657f2272011-01-13 21:10:12 +0000783/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
784/// debug info. It's the same as what we use for resolving the code-gen
785/// references for now. FIXME: This can go wrong when references are
786/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000787int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000788ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000789 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000790 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
791}
792
793int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000794ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000795 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000796 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000797 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000798 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000799 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000800 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
801 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
802 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
803 bool isFixed = MFI->isFixedObjectIndex(FI);
804
805 FrameReg = ARM::SP;
806 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000807
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000808 // SP can move around if there are allocas. We may also lose track of SP
809 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000810 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000811
Anton Korobeynikov46877782010-11-20 15:59:32 +0000812 // When dynamically realigning the stack, use the frame pointer for
813 // parameters, and the stack/base pointer for locals.
814 if (RegInfo->needsStackRealignment(MF)) {
815 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
816 if (isFixed) {
817 FrameReg = RegInfo->getFrameRegister(MF);
818 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000819 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000820 assert(RegInfo->hasBasePointer(MF) &&
821 "VLAs and dynamic stack alignment, but missing base pointer!");
822 FrameReg = RegInfo->getBaseRegister();
823 }
824 return Offset;
825 }
826
827 // If there is a frame pointer, use it when we can.
828 if (hasFP(MF) && AFI->hasStackFrame()) {
829 // Use frame pointer to reference fixed objects. Use it for locals if
830 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000831 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000832 FrameReg = RegInfo->getFrameRegister(MF);
833 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000834 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000835 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000836 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000837 // Try to use the frame pointer if we can, else use the base pointer
838 // since it's available. This is handy for the emergency spill slot, in
839 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000840 if (FPOffset >= -255 && FPOffset < 0) {
841 FrameReg = RegInfo->getFrameRegister(MF);
842 return FPOffset;
843 }
Evan Chengc0d20042011-04-22 01:42:52 +0000844 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000845 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000846 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000847 // ldr <rd>, [sp, #<imm8>]
848 // if at all possible to save space.
849 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
850 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000851 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000852 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000853 if (FPOffset >= -255 && FPOffset < 0) {
854 FrameReg = RegInfo->getFrameRegister(MF);
855 return FPOffset;
856 }
857 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
858 // Otherwise, use SP or FP, whichever is closer to the stack slot.
859 FrameReg = RegInfo->getFrameRegister(MF);
860 return FPOffset;
861 }
862 }
863 // Use the base pointer if we have one.
864 if (RegInfo->hasBasePointer(MF))
865 FrameReg = RegInfo->getBaseRegister();
866 return Offset;
867}
868
Bob Wilson657f2272011-01-13 21:10:12 +0000869int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
870 int FI) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000871 unsigned FrameReg;
872 return getFrameIndexReference(MF, FI, FrameReg);
873}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000874
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000875void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000876 MachineBasicBlock::iterator MI,
877 const std::vector<CalleeSavedInfo> &CSI,
878 unsigned StmOpc, unsigned StrOpc,
879 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000880 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000881 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000882 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000883 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000884 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000885
886 DebugLoc DL;
887 if (MI != MBB.end()) DL = MI->getDebugLoc();
888
Evan Chengc27c9562010-12-07 19:59:34 +0000889 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000890 unsigned i = CSI.size();
891 while (i != 0) {
892 unsigned LastReg = 0;
893 for (; i != 0; --i) {
894 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000895 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000896
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000897 // D-registers in the aligned area DPRCS2 are NOT spilled here.
898 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
899 continue;
900
Evan Cheng775ead32010-12-07 23:08:38 +0000901 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000902 // @llvm.returnaddress is called. If LR is returned for
903 // @llvm.returnaddress then it's already added to the function and
904 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000905 bool isKill = true;
906 if (Reg == ARM::LR) {
907 if (MF.getFrameInfo()->isReturnAddressTaken() &&
908 MF.getRegInfo().isLiveIn(Reg))
909 isKill = false;
910 }
911
912 if (isKill)
913 MBB.addLiveIn(Reg);
914
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000915 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000916 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000917 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000918 if (NoGap && LastReg && LastReg != Reg-1)
919 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000920 LastReg = Reg;
921 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000922 }
923
Jim Grosbach5fccad82010-12-09 18:31:13 +0000924 if (Regs.empty())
925 continue;
926 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000927 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000928 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000929 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000930 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
931 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000932 } else if (Regs.size() == 1) {
933 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
934 ARM::SP)
935 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000936 .addReg(ARM::SP).setMIFlags(MIFlags)
937 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000938 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000939 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000940 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000941
942 // Put any subsequent vpush instructions before this one: they will refer to
943 // higher register numbers so need to be pushed first in order to preserve
944 // monotonicity.
945 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000946 }
Evan Cheng775ead32010-12-07 23:08:38 +0000947}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000948
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000949void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000950 MachineBasicBlock::iterator MI,
951 const std::vector<CalleeSavedInfo> &CSI,
952 unsigned LdmOpc, unsigned LdrOpc,
953 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000954 bool(*Func)(unsigned, bool),
955 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000956 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000957 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Evan Cheng775ead32010-12-07 23:08:38 +0000958 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
959 DebugLoc DL = MI->getDebugLoc();
Evan Chengd6093ff2011-01-25 01:28:33 +0000960 unsigned RetOpcode = MI->getOpcode();
961 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000962 RetOpcode == ARM::TCRETURNri);
Tim Northoverd8407452013-10-01 14:33:28 +0000963 bool isInterrupt =
964 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Evan Cheng775ead32010-12-07 23:08:38 +0000965
966 SmallVector<unsigned, 4> Regs;
967 unsigned i = CSI.size();
968 while (i != 0) {
969 unsigned LastReg = 0;
970 bool DeleteRet = false;
971 for (; i != 0; --i) {
972 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000973 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +0000974
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000975 // The aligned reloads from area DPRCS2 are not inserted here.
976 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
977 continue;
978
Tim Northoverd8407452013-10-01 14:33:28 +0000979 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
980 STI.hasV5TOps()) {
Evan Cheng775ead32010-12-07 23:08:38 +0000981 Reg = ARM::PC;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000982 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Evan Cheng775ead32010-12-07 23:08:38 +0000983 // Fold the return instruction into the LDM.
984 DeleteRet = true;
985 }
986
Evan Cheng9d54ae62010-12-08 06:29:02 +0000987 // If NoGap is true, pop consecutive registers and then leave the rest
988 // for other instructions. e.g.
989 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
990 if (NoGap && LastReg && LastReg != Reg-1)
991 break;
992
Evan Cheng775ead32010-12-07 23:08:38 +0000993 LastReg = Reg;
994 Regs.push_back(Reg);
995 }
996
Jim Grosbach5fccad82010-12-09 18:31:13 +0000997 if (Regs.empty())
998 continue;
999 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +00001000 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +00001001 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +00001002 .addReg(ARM::SP));
1003 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1004 MIB.addReg(Regs[i], getDefRegState(true));
Andrew Trick6446bf72011-08-25 17:50:53 +00001005 if (DeleteRet) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001006 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +00001007 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +00001008 }
Evan Cheng775ead32010-12-07 23:08:38 +00001009 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001010 } else if (Regs.size() == 1) {
1011 // If we adjusted the reg to PC from LR above, switch it back here. We
1012 // only do that for LDM.
1013 if (Regs[0] == ARM::PC)
1014 Regs[0] = ARM::LR;
1015 MachineInstrBuilder MIB =
1016 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1017 .addReg(ARM::SP, RegState::Define)
1018 .addReg(ARM::SP);
1019 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1020 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001021 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001022 MIB.addReg(0);
1023 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1024 } else
1025 MIB.addImm(4);
1026 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +00001027 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001028 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001029
1030 // Put any subsequent vpop instructions after this one: they will refer to
1031 // higher register numbers so need to be popped afterwards.
1032 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001033 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001034}
1035
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001036/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001037/// starting from d8. Also insert stack realignment code and leave the stack
1038/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001039static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1040 MachineBasicBlock::iterator MI,
1041 unsigned NumAlignedDPRCS2Regs,
1042 const std::vector<CalleeSavedInfo> &CSI,
1043 const TargetRegisterInfo *TRI) {
1044 MachineFunction &MF = *MBB.getParent();
1045 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1046 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001047 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001048 MachineFrameInfo &MFI = *MF.getFrameInfo();
1049
1050 // Mark the D-register spill slots as properly aligned. Since MFI computes
1051 // stack slot layout backwards, this can actually mean that the d-reg stack
1052 // slot offsets can be wrong. The offset for d8 will always be correct.
1053 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1054 unsigned DNum = CSI[i].getReg() - ARM::D8;
1055 if (DNum >= 8)
1056 continue;
1057 int FI = CSI[i].getFrameIdx();
1058 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1059 // registers will be 8-byte aligned.
1060 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1061
1062 // The stack slot for D8 needs to be maximally aligned because this is
1063 // actually the point where we align the stack pointer. MachineFrameInfo
1064 // computes all offsets relative to the incoming stack pointer which is a
1065 // bit weird when realigning the stack. Any extra padding for this
1066 // over-alignment is not realized because the code inserted below adjusts
1067 // the stack pointer by numregs * 8 before aligning the stack pointer.
1068 if (DNum == 0)
1069 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1070 }
1071
1072 // Move the stack pointer to the d8 spill slot, and align it at the same
1073 // time. Leave the stack slot address in the scratch register r4.
1074 //
1075 // sub r4, sp, #numregs * 8
1076 // bic r4, r4, #align - 1
1077 // mov sp, r4
1078 //
1079 bool isThumb = AFI->isThumbFunction();
1080 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1081 AFI->setShouldRestoreSPFromFP(true);
1082
1083 // sub r4, sp, #numregs * 8
1084 // The immediate is <= 64, so it doesn't need any special encoding.
1085 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1086 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1087 .addReg(ARM::SP)
1088 .addImm(8 * NumAlignedDPRCS2Regs)));
1089
1090 // bic r4, r4, #align-1
1091 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1092 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1093 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1094 .addReg(ARM::R4, RegState::Kill)
1095 .addImm(MaxAlign - 1)));
1096
1097 // mov sp, r4
1098 // The stack pointer must be adjusted before spilling anything, otherwise
1099 // the stack slots could be clobbered by an interrupt handler.
1100 // Leave r4 live, it is used below.
1101 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1102 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1103 .addReg(ARM::R4);
1104 MIB = AddDefaultPred(MIB);
1105 if (!isThumb)
1106 AddDefaultCC(MIB);
1107
1108 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1109 // r4 holds the stack slot address.
1110 unsigned NextReg = ARM::D8;
1111
1112 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1113 // The writeback is only needed when emitting two vst1.64 instructions.
1114 if (NumAlignedDPRCS2Regs >= 6) {
1115 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001116 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001117 MBB.addLiveIn(SupReg);
1118 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1119 ARM::R4)
1120 .addReg(ARM::R4, RegState::Kill).addImm(16)
1121 .addReg(NextReg)
1122 .addReg(SupReg, RegState::ImplicitKill));
1123 NextReg += 4;
1124 NumAlignedDPRCS2Regs -= 4;
1125 }
1126
1127 // We won't modify r4 beyond this point. It currently points to the next
1128 // register to be spilled.
1129 unsigned R4BaseReg = NextReg;
1130
1131 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1132 if (NumAlignedDPRCS2Regs >= 4) {
1133 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001134 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001135 MBB.addLiveIn(SupReg);
1136 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1137 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1138 .addReg(SupReg, RegState::ImplicitKill));
1139 NextReg += 4;
1140 NumAlignedDPRCS2Regs -= 4;
1141 }
1142
1143 // 16-byte aligned vst1.64 with 2 d-regs.
1144 if (NumAlignedDPRCS2Regs >= 2) {
1145 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001146 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001147 MBB.addLiveIn(SupReg);
1148 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001149 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001150 NextReg += 2;
1151 NumAlignedDPRCS2Regs -= 2;
1152 }
1153
1154 // Finally, use a vanilla vstr.64 for the odd last register.
1155 if (NumAlignedDPRCS2Regs) {
1156 MBB.addLiveIn(NextReg);
1157 // vstr.64 uses addrmode5 which has an offset scale of 4.
1158 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1159 .addReg(NextReg)
1160 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1161 }
1162
1163 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001164 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001165}
1166
1167/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1168/// iterator to the following instruction.
1169static MachineBasicBlock::iterator
1170skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1171 unsigned NumAlignedDPRCS2Regs) {
1172 // sub r4, sp, #numregs * 8
1173 // bic r4, r4, #align - 1
1174 // mov sp, r4
1175 ++MI; ++MI; ++MI;
1176 assert(MI->mayStore() && "Expecting spill instruction");
1177
1178 // These switches all fall through.
1179 switch(NumAlignedDPRCS2Regs) {
1180 case 7:
1181 ++MI;
1182 assert(MI->mayStore() && "Expecting spill instruction");
1183 default:
1184 ++MI;
1185 assert(MI->mayStore() && "Expecting spill instruction");
1186 case 1:
1187 case 2:
1188 case 4:
1189 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1190 ++MI;
1191 }
1192 return MI;
1193}
1194
1195/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1196/// starting from d8. These instructions are assumed to execute while the
1197/// stack is still aligned, unlike the code inserted by emitPopInst.
1198static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1199 MachineBasicBlock::iterator MI,
1200 unsigned NumAlignedDPRCS2Regs,
1201 const std::vector<CalleeSavedInfo> &CSI,
1202 const TargetRegisterInfo *TRI) {
1203 MachineFunction &MF = *MBB.getParent();
1204 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1205 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001206 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001207
1208 // Find the frame index assigned to d8.
1209 int D8SpillFI = 0;
1210 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1211 if (CSI[i].getReg() == ARM::D8) {
1212 D8SpillFI = CSI[i].getFrameIdx();
1213 break;
1214 }
1215
1216 // Materialize the address of the d8 spill slot into the scratch register r4.
1217 // This can be fairly complicated if the stack frame is large, so just use
1218 // the normal frame index elimination mechanism to do it. This code runs as
1219 // the initial part of the epilog where the stack and base pointers haven't
1220 // been changed yet.
1221 bool isThumb = AFI->isThumbFunction();
1222 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1223
1224 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1225 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1226 .addFrameIndex(D8SpillFI).addImm(0)));
1227
1228 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1229 unsigned NextReg = ARM::D8;
1230
1231 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1232 if (NumAlignedDPRCS2Regs >= 6) {
1233 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001234 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001235 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1236 .addReg(ARM::R4, RegState::Define)
1237 .addReg(ARM::R4, RegState::Kill).addImm(16)
1238 .addReg(SupReg, RegState::ImplicitDefine));
1239 NextReg += 4;
1240 NumAlignedDPRCS2Regs -= 4;
1241 }
1242
1243 // We won't modify r4 beyond this point. It currently points to the next
1244 // register to be spilled.
1245 unsigned R4BaseReg = NextReg;
1246
1247 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1248 if (NumAlignedDPRCS2Regs >= 4) {
1249 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001250 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001251 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1252 .addReg(ARM::R4).addImm(16)
1253 .addReg(SupReg, RegState::ImplicitDefine));
1254 NextReg += 4;
1255 NumAlignedDPRCS2Regs -= 4;
1256 }
1257
1258 // 16-byte aligned vld1.64 with 2 d-regs.
1259 if (NumAlignedDPRCS2Regs >= 2) {
1260 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001261 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001262 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1263 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001264 NextReg += 2;
1265 NumAlignedDPRCS2Regs -= 2;
1266 }
1267
1268 // Finally, use a vanilla vldr.64 for the remaining odd register.
1269 if (NumAlignedDPRCS2Regs)
1270 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1271 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1272
1273 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001274 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001275}
1276
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001277bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001278 MachineBasicBlock::iterator MI,
1279 const std::vector<CalleeSavedInfo> &CSI,
1280 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001281 if (CSI.empty())
1282 return false;
1283
1284 MachineFunction &MF = *MBB.getParent();
1285 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001286
1287 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001288 unsigned PushOneOpc = AFI->isThumbFunction() ?
1289 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001290 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001291 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1292 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001293 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001294 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001295 MachineInstr::FrameSetup);
1296 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001297 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1298
1299 // The code above does not insert spill code for the aligned DPRCS2 registers.
1300 // The stack realignment code will be inserted between the push instructions
1301 // and these spills.
1302 if (NumAlignedDPRCS2Regs)
1303 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001304
1305 return true;
1306}
1307
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001308bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001309 MachineBasicBlock::iterator MI,
1310 const std::vector<CalleeSavedInfo> &CSI,
1311 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001312 if (CSI.empty())
1313 return false;
1314
1315 MachineFunction &MF = *MBB.getParent();
1316 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001317 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001318 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1319
1320 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1321 // registers. Do that here instead.
1322 if (NumAlignedDPRCS2Regs)
1323 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001324
1325 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001326 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001327 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001328 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1329 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001330 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001331 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001332 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001333 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001334
1335 return true;
1336}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001337
1338// FIXME: Make generic?
1339static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1340 const ARMBaseInstrInfo &TII) {
1341 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001342 for (auto &MBB : MF) {
1343 for (auto &MI : MBB)
1344 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001345 }
1346 return FnSize;
1347}
1348
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001349/// estimateRSStackSizeLimit - Look at each instruction that references stack
1350/// frames and return the stack size limit beyond which some of these
1351/// instructions will require a scratch register during their expansion later.
1352// FIXME: Move to TII?
1353static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001354 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001355 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1356 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001357 for (auto &MBB : MF) {
1358 for (auto &MI : MBB) {
1359 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1360 if (!MI.getOperand(i).isFI())
1361 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001362
1363 // When using ADDri to get the address of a stack object, 255 is the
1364 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001365 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001366 Limit = std::min(Limit, (1U << 8) - 1);
1367 break;
1368 }
1369
1370 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001371 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001372 case ARMII::AddrMode3:
1373 case ARMII::AddrModeT2_i8:
1374 Limit = std::min(Limit, (1U << 8) - 1);
1375 break;
1376 case ARMII::AddrMode5:
1377 case ARMII::AddrModeT2_i8s4:
1378 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1379 break;
1380 case ARMII::AddrModeT2_i12:
1381 // i12 supports only positive offset so these will be converted to
1382 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1383 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1384 Limit = std::min(Limit, (1U << 8) - 1);
1385 break;
1386 case ARMII::AddrMode4:
1387 case ARMII::AddrMode6:
1388 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1389 // immediate offset for stack references.
1390 return 0;
1391 default:
1392 break;
1393 }
1394 break; // At most one FI per instruction
1395 }
1396 }
1397 }
1398
1399 return Limit;
1400}
1401
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001402// In functions that realign the stack, it can be an advantage to spill the
1403// callee-saved vector registers after realigning the stack. The vst1 and vld1
1404// instructions take alignment hints that can improve performance.
1405//
1406static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1407 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1408 if (!SpillAlignedNEONRegs)
1409 return;
1410
1411 // Naked functions don't spill callee-saved registers.
Bill Wendling698e84f2012-12-30 10:32:01 +00001412 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1413 Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001414 return;
1415
1416 // We are planning to use NEON instructions vst1 / vld1.
1417 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1418 return;
1419
1420 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopherd9134482014-08-04 21:25:23 +00001421 if (MF.getTarget()
1422 .getSubtargetImpl()
1423 ->getFrameLowering()
1424 ->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001425 return;
1426
1427 // Aligned spills require stack realignment.
Eric Christopherd9134482014-08-04 21:25:23 +00001428 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001429 MF.getSubtarget().getRegisterInfo());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001430 if (!RegInfo->canRealignStack(MF))
1431 return;
1432
1433 // We always spill contiguous d-registers starting from d8. Count how many
1434 // needs spilling. The register allocator will almost always use the
1435 // callee-saved registers in order, but it can happen that there are holes in
1436 // the range. Registers above the hole will be spilled to the standard DPRCS
1437 // area.
1438 MachineRegisterInfo &MRI = MF.getRegInfo();
1439 unsigned NumSpills = 0;
1440 for (; NumSpills < 8; ++NumSpills)
Jakob Stoklund Olesen07364422012-10-17 18:44:18 +00001441 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001442 break;
1443
1444 // Don't do this for just one d-register. It's not worth it.
1445 if (NumSpills < 2)
1446 return;
1447
1448 // Spill the first NumSpills D-registers after realigning the stack.
1449 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1450
1451 // A scratch register is required for the vst1 / vld1 instructions.
1452 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1453}
1454
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001455void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001456ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +00001457 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001458 // This tells PEI to spill the FP as if it is any other callee-save register
1459 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1460 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1461 // to combine multiple loads / stores.
1462 bool CanEliminateFrame = true;
1463 bool CS1Spilled = false;
1464 bool LRSpilled = false;
1465 unsigned NumGPRSpills = 0;
1466 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1467 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001468 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001469 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001470 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001471 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001472 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1473 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001474 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001475 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1476
1477 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1478 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001479 // since it's not always possible to restore sp from fp in a single
1480 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001481 // FIXME: It will be better just to find spare register here.
1482 if (AFI->isThumb2Function() &&
1483 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001484 MRI.setPhysRegUsed(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001485
Evan Cheng572756a2011-01-16 05:14:33 +00001486 if (AFI->isThumb1OnlyFunction()) {
1487 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001488 if (AFI->getArgRegsSaveSize() > 0)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001489 MRI.setPhysRegUsed(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001490
Jim Grosbachdca85312011-06-13 21:18:25 +00001491 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1492 // for sure what the stack size will be, but for this, an estimate is good
1493 // enough. If there anything changes it, it'll be a spill, which implies
1494 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001495 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001496 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001497 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001498 if (MFI->hasVarSizedObjects() || StackSize > 508)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001499 MRI.setPhysRegUsed(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001500 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001501
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001502 // See if we can spill vector registers to aligned stack.
1503 checkNumAlignedDPRCS2Regs(MF);
1504
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001505 // Spill the BasePtr if it's used.
1506 if (RegInfo->hasBasePointer(MF))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001507 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001508
1509 // Don't spill FP if the frame can be eliminated. This is determined
1510 // by scanning the callee-save registers to see if any is used.
Craig Topper840beec2014-04-04 05:16:06 +00001511 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001512 for (unsigned i = 0; CSRegs[i]; ++i) {
1513 unsigned Reg = CSRegs[i];
1514 bool Spilled = false;
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001515 if (MRI.isPhysRegUsed(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001516 Spilled = true;
1517 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001518 }
1519
Craig Topperc7242e02012-04-20 07:30:17 +00001520 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001521 continue;
1522
1523 if (Spilled) {
1524 NumGPRSpills++;
1525
Tim Northover86f60b72014-05-30 13:23:06 +00001526 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001527 if (Reg == ARM::LR)
1528 LRSpilled = true;
1529 CS1Spilled = true;
1530 continue;
1531 }
1532
1533 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1534 switch (Reg) {
1535 case ARM::LR:
1536 LRSpilled = true;
1537 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001538 case ARM::R0: case ARM::R1:
1539 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001540 case ARM::R4: case ARM::R5:
1541 case ARM::R6: case ARM::R7:
1542 CS1Spilled = true;
1543 break;
1544 default:
1545 break;
1546 }
1547 } else {
Tim Northover86f60b72014-05-30 13:23:06 +00001548 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001549 UnspilledCS1GPRs.push_back(Reg);
1550 continue;
1551 }
1552
1553 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001554 case ARM::R0: case ARM::R1:
1555 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001556 case ARM::R4: case ARM::R5:
1557 case ARM::R6: case ARM::R7:
1558 case ARM::LR:
1559 UnspilledCS1GPRs.push_back(Reg);
1560 break;
1561 default:
1562 UnspilledCS2GPRs.push_back(Reg);
1563 break;
1564 }
1565 }
1566 }
1567
1568 bool ForceLRSpill = false;
1569 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1570 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1571 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1572 // use of BL to implement far jump. If it turns out that it's not needed
1573 // then the branch fix up path will undo it.
1574 if (FnSize >= (1 << 11)) {
1575 CanEliminateFrame = false;
1576 ForceLRSpill = true;
1577 }
1578 }
1579
1580 // If any of the stack slot references may be out of range of an immediate
1581 // offset, make sure a register (or a spill slot) is available for the
1582 // register scavenger. Note that if we're indexing off the frame pointer, the
1583 // effective stack size is 4 bytes larger since the FP points to the stack
1584 // slot of the previous FP. Also, if we have variable sized objects in the
1585 // function, stack slot references will often be negative, and some of
1586 // our instructions are positive-offset only, so conservatively consider
1587 // that case to want a spill slot (or register) as well. Similarly, if
1588 // the function adjusts the stack pointer during execution and the
1589 // adjustments aren't already part of our stack size estimate, our offset
1590 // calculations may be off, so be conservative.
1591 // FIXME: We could add logic to be more precise about negative offsets
1592 // and which instructions will need a scratch register for them. Is it
1593 // worth the effort and added fragility?
1594 bool BigStack =
1595 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001596 (MFI->estimateStackSize(MF) +
1597 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001598 estimateRSStackSizeLimit(MF, this)))
1599 || MFI->hasVarSizedObjects()
1600 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1601
1602 bool ExtraCSSpill = false;
1603 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1604 AFI->setHasStackFrame(true);
1605
1606 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1607 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1608 if (!LRSpilled && CS1Spilled) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001609 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001610 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001611 SmallVectorImpl<unsigned>::iterator LRPos;
1612 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1613 (unsigned)ARM::LR);
1614 if (LRPos != UnspilledCS1GPRs.end())
1615 UnspilledCS1GPRs.erase(LRPos);
1616
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001617 ForceLRSpill = false;
1618 ExtraCSSpill = true;
1619 }
1620
1621 if (hasFP(MF)) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001622 MRI.setPhysRegUsed(FramePtr);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001623 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1624 FramePtr);
1625 if (FPPos != UnspilledCS1GPRs.end())
1626 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001627 NumGPRSpills++;
1628 }
1629
1630 // If stack and double are 8-byte aligned and we are spilling an odd number
1631 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1632 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001633 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001634 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001635 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1636 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1637 unsigned Reg = UnspilledCS1GPRs[i];
1638 // Don't spill high register if the function is thumb1
1639 if (!AFI->isThumb1OnlyFunction() ||
1640 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001641 MRI.setPhysRegUsed(Reg);
1642 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001643 ExtraCSSpill = true;
1644 break;
1645 }
1646 }
1647 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1648 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001649 MRI.setPhysRegUsed(Reg);
1650 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001651 ExtraCSSpill = true;
1652 }
1653 }
1654
1655 // Estimate if we might need to scavenge a register at some point in order
1656 // to materialize a stack offset. If so, either spill one additional
1657 // callee-saved register or reserve a special spill slot to facilitate
1658 // register scavenging. Thumb1 needs a spill slot for stack pointer
1659 // adjustments also, even when the frame itself is small.
1660 if (BigStack && !ExtraCSSpill) {
1661 // If any non-reserved CS register isn't spilled, just spill one or two
1662 // extra. That should take care of it!
1663 unsigned NumExtras = TargetAlign / 4;
1664 SmallVector<unsigned, 2> Extras;
1665 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1666 unsigned Reg = UnspilledCS1GPRs.back();
1667 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001668 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001669 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1670 Reg == ARM::LR)) {
1671 Extras.push_back(Reg);
1672 NumExtras--;
1673 }
1674 }
1675 // For non-Thumb1 functions, also check for hi-reg CS registers
1676 if (!AFI->isThumb1OnlyFunction()) {
1677 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1678 unsigned Reg = UnspilledCS2GPRs.back();
1679 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001680 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001681 Extras.push_back(Reg);
1682 NumExtras--;
1683 }
1684 }
1685 }
1686 if (Extras.size() && NumExtras == 0) {
1687 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001688 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001689 }
1690 } else if (!AFI->isThumb1OnlyFunction()) {
1691 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1692 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001693 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001694 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001695 RC->getAlignment(),
1696 false));
1697 }
1698 }
1699 }
1700
1701 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001702 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001703 AFI->setLRIsSpilledForFarJump(true);
1704 }
1705}
Eli Bendersky8da87162013-02-21 20:05:00 +00001706
1707
1708void ARMFrameLowering::
1709eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1710 MachineBasicBlock::iterator I) const {
1711 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001712 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001713 if (!hasReservedCallFrame(MF)) {
1714 // If we have alloca, convert as follows:
1715 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1716 // ADJCALLSTACKUP -> add, sp, sp, amount
1717 MachineInstr *Old = I;
1718 DebugLoc dl = Old->getDebugLoc();
1719 unsigned Amount = Old->getOperand(0).getImm();
1720 if (Amount != 0) {
1721 // We need to keep the stack aligned properly. To do this, we round the
1722 // amount of space needed for the outgoing arguments up to the next
1723 // alignment boundary.
1724 unsigned Align = getStackAlignment();
1725 Amount = (Amount+Align-1)/Align*Align;
1726
1727 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1728 assert(!AFI->isThumb1OnlyFunction() &&
1729 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1730 bool isARM = !AFI->isThumbFunction();
1731
1732 // Replace the pseudo instruction with a new instruction...
1733 unsigned Opc = Old->getOpcode();
1734 int PIdx = Old->findFirstPredOperandIdx();
1735 ARMCC::CondCodes Pred = (PIdx == -1)
1736 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1737 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1738 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1739 unsigned PredReg = Old->getOperand(2).getReg();
1740 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1741 Pred, PredReg);
1742 } else {
1743 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1744 unsigned PredReg = Old->getOperand(3).getReg();
1745 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1746 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1747 Pred, PredReg);
1748 }
1749 }
1750 }
1751 MBB.erase(I);
1752}
1753
Oliver Stannardb14c6252014-04-02 16:10:33 +00001754/// Get the minimum constant for ARM that is greater than or equal to the
1755/// argument. In ARM, constants can have any value that can be produced by
1756/// rotating an 8-bit value to the right by an even number of bits within a
1757/// 32-bit word.
1758static uint32_t alignToARMConstant(uint32_t Value) {
1759 unsigned Shifted = 0;
1760
1761 if (Value == 0)
1762 return 0;
1763
1764 while (!(Value & 0xC0000000)) {
1765 Value = Value << 2;
1766 Shifted += 2;
1767 }
1768
1769 bool Carry = (Value & 0x00FFFFFF);
1770 Value = ((Value & 0xFF000000) >> 24) + Carry;
1771
1772 if (Value & 0x0000100)
1773 Value = Value & 0x000001FC;
1774
1775 if (Shifted > 24)
1776 Value = Value >> (Shifted - 24);
1777 else
1778 Value = Value << (24 - Shifted);
1779
1780 return Value;
1781}
1782
1783// The stack limit in the TCB is set to this many bytes above the actual
1784// stack limit.
1785static const uint64_t kSplitStackAvailable = 256;
1786
1787// Adjust the function prologue to enable split stacks. This currently only
1788// supports android and linux.
1789//
1790// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1791// must be well defined in order to allow for consistent implementations of the
1792// __morestack helper function. The ABI is also not a normal ABI in that it
1793// doesn't follow the normal calling conventions because this allows the
1794// prologue of each function to be optimized further.
1795//
1796// Currently, the ABI looks like (when calling __morestack)
1797//
1798// * r4 holds the minimum stack size requested for this function call
1799// * r5 holds the stack size of the arguments to the function
1800// * the beginning of the function is 3 instructions after the call to
1801// __morestack
1802//
1803// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1804// place the arguments on to the new stack, and the 3-instruction knowledge to
1805// jump directly to the body of the function when working on the new stack.
1806//
1807// An old (and possibly no longer compatible) implementation of __morestack for
1808// ARM can be found at [1].
1809//
1810// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1811void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1812 unsigned Opcode;
1813 unsigned CFIIndex;
1814 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1815 bool Thumb = ST->isThumb();
1816
1817 // Sadly, this currently doesn't support varargs, platforms other than
1818 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1819 if (MF.getFunction()->isVarArg())
1820 report_fatal_error("Segmented stacks do not support vararg functions.");
1821 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001822 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001823
1824 MachineBasicBlock &prologueMBB = MF.front();
1825 MachineFrameInfo *MFI = MF.getFrameInfo();
1826 MachineModuleInfo &MMI = MF.getMMI();
1827 MCContext &Context = MMI.getContext();
1828 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1829 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001830 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00001831 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1832 DebugLoc DL;
1833
Tim Northoverf9e798b2014-05-22 13:03:43 +00001834 uint64_t StackSize = MFI->getStackSize();
1835
1836 // Do not generate a prologue for functions with a stack of size zero
1837 if (StackSize == 0)
1838 return;
1839
Oliver Stannardb14c6252014-04-02 16:10:33 +00001840 // Use R4 and R5 as scratch registers.
1841 // We save R4 and R5 before use and restore them before leaving the function.
1842 unsigned ScratchReg0 = ARM::R4;
1843 unsigned ScratchReg1 = ARM::R5;
1844 uint64_t AlignedStackSize;
1845
1846 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1847 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1848 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1849 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1850 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1851
1852 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1853 e = prologueMBB.livein_end();
1854 i != e; ++i) {
1855 AllocMBB->addLiveIn(*i);
1856 GetMBB->addLiveIn(*i);
1857 McrMBB->addLiveIn(*i);
1858 PrevStackMBB->addLiveIn(*i);
1859 PostStackMBB->addLiveIn(*i);
1860 }
1861
1862 MF.push_front(PostStackMBB);
1863 MF.push_front(AllocMBB);
1864 MF.push_front(GetMBB);
1865 MF.push_front(McrMBB);
1866 MF.push_front(PrevStackMBB);
1867
1868 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00001869 AlignedStackSize = alignToARMConstant(StackSize);
1870
1871 // When the frame size is less than 256 we just compare the stack
1872 // boundary directly to the value of the stack pointer, per gcc.
1873 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1874
1875 // We will use two of the callee save registers as scratch registers so we
1876 // need to save those registers onto the stack.
1877 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1878 // requested and arguments for __morestack().
1879 // SR0: Scratch Register #0
1880 // SR1: Scratch Register #1
1881 // push {SR0, SR1}
1882 if (Thumb) {
1883 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1884 .addReg(ScratchReg0).addReg(ScratchReg1);
1885 } else {
1886 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1887 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1888 .addReg(ScratchReg0).addReg(ScratchReg1);
1889 }
1890
1891 // Emit the relevant DWARF information about the change in stack pointer as
1892 // well as where to find both r4 and r5 (the callee-save registers)
1893 CFIIndex =
1894 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1895 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1896 .addCFIIndex(CFIIndex);
1897 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1898 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1899 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1900 .addCFIIndex(CFIIndex);
1901 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1902 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1903 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1904 .addCFIIndex(CFIIndex);
1905
1906 // mov SR1, sp
1907 if (Thumb) {
1908 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1909 .addReg(ARM::SP));
1910 } else if (CompareStackPointer) {
1911 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1912 .addReg(ARM::SP)).addReg(0);
1913 }
1914
1915 // sub SR1, sp, #StackSize
1916 if (!CompareStackPointer && Thumb) {
1917 AddDefaultPred(
1918 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1919 .addReg(ScratchReg1).addImm(AlignedStackSize));
1920 } else if (!CompareStackPointer) {
1921 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1922 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1923 }
1924
1925 if (Thumb && ST->isThumb1Only()) {
1926 unsigned PCLabelId = ARMFI->createPICLabelUId();
1927 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001928 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001929 MachineConstantPool *MCP = MF.getConstantPool();
1930 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1931
1932 // ldr SR0, [pc, offset(STACK_LIMIT)]
1933 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1934 .addConstantPoolIndex(CPI));
1935
1936 // ldr SR0, [SR0]
1937 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1938 .addReg(ScratchReg0).addImm(0));
1939 } else {
1940 // Get TLS base address from the coprocessor
1941 // mrc p15, #0, SR0, c13, c0, #3
1942 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1943 .addImm(15)
1944 .addImm(0)
1945 .addImm(13)
1946 .addImm(0)
1947 .addImm(3));
1948
1949 // Use the last tls slot on android and a private field of the TCP on linux.
1950 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1951 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1952
1953 // Get the stack limit from the right offset
1954 // ldr SR0, [sr0, #4 * TlsOffset]
1955 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1956 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1957 }
1958
1959 // Compare stack limit with stack size requested.
1960 // cmp SR0, SR1
1961 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1962 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1963 .addReg(ScratchReg0)
1964 .addReg(ScratchReg1));
1965
1966 // This jump is taken if StackLimit < SP - stack required.
1967 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1968 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1969 .addImm(ARMCC::LO)
1970 .addReg(ARM::CPSR);
1971
1972
1973 // Calling __morestack(StackSize, Size of stack arguments).
1974 // __morestack knows that the stack size requested is in SR0(r4)
1975 // and amount size of stack arguments is in SR1(r5).
1976
1977 // Pass first argument for the __morestack by Scratch Register #0.
1978 // The amount size of stack required
1979 if (Thumb) {
1980 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1981 ScratchReg0)).addImm(AlignedStackSize));
1982 } else {
1983 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1984 .addImm(AlignedStackSize)).addReg(0);
1985 }
1986 // Pass second argument for the __morestack by Scratch Register #1.
1987 // The amount size of stack consumed to save function arguments.
1988 if (Thumb) {
1989 AddDefaultPred(
1990 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1991 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1992 } else {
1993 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1994 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1995 .addReg(0);
1996 }
1997
1998 // push {lr} - Save return address of this function.
1999 if (Thumb) {
2000 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2001 .addReg(ARM::LR);
2002 } else {
2003 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2004 .addReg(ARM::SP, RegState::Define)
2005 .addReg(ARM::SP))
2006 .addReg(ARM::LR);
2007 }
2008
2009 // Emit the DWARF info about the change in stack as well as where to find the
2010 // previous link register
2011 CFIIndex =
2012 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2013 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2014 .addCFIIndex(CFIIndex);
2015 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2016 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2017 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2018 .addCFIIndex(CFIIndex);
2019
2020 // Call __morestack().
2021 if (Thumb) {
2022 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2023 .addExternalSymbol("__morestack");
2024 } else {
2025 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2026 .addExternalSymbol("__morestack");
2027 }
2028
2029 // pop {lr} - Restore return address of this original function.
2030 if (Thumb) {
2031 if (ST->isThumb1Only()) {
2032 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2033 .addReg(ScratchReg0);
2034 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2035 .addReg(ScratchReg0));
2036 } else {
2037 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2038 .addReg(ARM::LR, RegState::Define)
2039 .addReg(ARM::SP, RegState::Define)
2040 .addReg(ARM::SP)
2041 .addImm(4));
2042 }
2043 } else {
2044 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2045 .addReg(ARM::SP, RegState::Define)
2046 .addReg(ARM::SP))
2047 .addReg(ARM::LR);
2048 }
2049
2050 // Restore SR0 and SR1 in case of __morestack() was called.
2051 // __morestack() will skip PostStackMBB block so we need to restore
2052 // scratch registers from here.
2053 // pop {SR0, SR1}
2054 if (Thumb) {
2055 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2056 .addReg(ScratchReg0)
2057 .addReg(ScratchReg1);
2058 } else {
2059 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2060 .addReg(ARM::SP, RegState::Define)
2061 .addReg(ARM::SP))
2062 .addReg(ScratchReg0)
2063 .addReg(ScratchReg1);
2064 }
2065
2066 // Update the CFA offset now that we've popped
2067 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2068 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2069 .addCFIIndex(CFIIndex);
2070
2071 // bx lr - Return from this function.
2072 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2073 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2074
2075 // Restore SR0 and SR1 in case of __morestack() was not called.
2076 // pop {SR0, SR1}
2077 if (Thumb) {
2078 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2079 .addReg(ScratchReg0)
2080 .addReg(ScratchReg1);
2081 } else {
2082 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2083 .addReg(ARM::SP, RegState::Define)
2084 .addReg(ARM::SP))
2085 .addReg(ScratchReg0)
2086 .addReg(ScratchReg1);
2087 }
2088
2089 // Update the CFA offset now that we've popped
2090 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2091 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2092 .addCFIIndex(CFIIndex);
2093
2094 // Tell debuggers that r4 and r5 are now the same as they were in the
2095 // previous function, that they're the "Same Value".
2096 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2097 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2098 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2099 .addCFIIndex(CFIIndex);
2100 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2101 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2102 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2103 .addCFIIndex(CFIIndex);
2104
2105 // Organizing MBB lists
2106 PostStackMBB->addSuccessor(&prologueMBB);
2107
2108 AllocMBB->addSuccessor(PostStackMBB);
2109
2110 GetMBB->addSuccessor(PostStackMBB);
2111 GetMBB->addSuccessor(AllocMBB);
2112
2113 McrMBB->addSuccessor(GetMBB);
2114
2115 PrevStackMBB->addSuccessor(McrMBB);
2116
2117#ifdef XDEBUG
2118 MF.verify();
2119#endif
2120}