blob: 74f686507df5fb8257f1bf41abad9e77b37b271c [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) {
140 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
141 int count = 0;
142 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
143 // pred) so the list starts at 4.
144 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
145 count += 8;
146 return count;
147}
148
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000149static bool WindowsRequiresStackProbe(const MachineFunction &MF,
150 size_t StackSizeInBytes) {
151 const MachineFrameInfo *MFI = MF.getFrameInfo();
152 if (MFI->getStackProtectorIndex() > 0)
153 return StackSizeInBytes >= 4080;
154 return StackSizeInBytes >= 4096;
155}
156
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000157void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000158 MachineBasicBlock &MBB = MF.front();
159 MachineBasicBlock::iterator MBBI = MBB.begin();
160 MachineFrameInfo *MFI = MF.getFrameInfo();
161 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000162 MachineModuleInfo &MMI = MF.getMMI();
163 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000164 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000165 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000166 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
167 TM.getSubtargetImpl()->getRegisterInfo());
168 const ARMBaseInstrInfo &TII = *static_cast<const ARMBaseInstrInfo *>(
169 TM.getSubtargetImpl()->getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000170 assert(!AFI->isThumb1OnlyFunction() &&
171 "This emitPrologue does not support Thumb1!");
172 bool isARM = !AFI->isThumbFunction();
Eric Christopherd9134482014-08-04 21:25:23 +0000173 unsigned Align =
174 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000175 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000176 unsigned NumBytes = MFI->getStackSize();
177 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
178 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
179 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000180 int CFAOffset = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000181
182 // Determine the sizes of each callee-save spill areas and record which frame
183 // belongs to which callee-save spill areas.
184 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
185 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000186 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000187
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000188 // All calls are tail calls in GHC calling conv, and functions have no
189 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000190 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
191 return;
192
Oliver Stannardd55e1152014-03-05 15:25:27 +0000193 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000194 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000195 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000196 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000197 CFAOffset -= ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000198 unsigned CFIIndex = MMI.addFrameInst(
199 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
200 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
201 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000202 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000203
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000204 if (!AFI->hasStackFrame() &&
205 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000206 if (NumBytes - ArgRegsSaveSize != 0) {
207 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000208 MachineInstr::FrameSetup);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000209 CFAOffset -= NumBytes - ArgRegsSaveSize;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000210 unsigned CFIIndex = MMI.addFrameInst(
211 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
212 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
213 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000214 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000215 return;
216 }
217
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000218 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000219 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
220 unsigned Reg = CSI[i].getReg();
221 int FI = CSI[i].getFrameIdx();
222 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000223 case ARM::R8:
224 case ARM::R9:
225 case ARM::R10:
226 case ARM::R11:
227 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000228 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000229 GPRCS2Size += 4;
230 break;
231 }
232 // fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +0000233 case ARM::R0:
234 case ARM::R1:
235 case ARM::R2:
236 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000237 case ARM::R4:
238 case ARM::R5:
239 case ARM::R6:
240 case ARM::R7:
241 case ARM::LR:
242 if (Reg == FramePtr)
243 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000244 GPRCS1Size += 4;
245 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000246 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000247 // This is a DPR. Exclude the aligned DPRCS2 spills.
248 if (Reg == ARM::D8)
249 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000250 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000251 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000252 }
253 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000254
Eric Christopherb006fc92010-11-18 19:40:05 +0000255 // Move past area 1.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000256 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
257 DPRCSPush;
Tim Northover93bcc662013-11-08 17:18:07 +0000258 if (GPRCS1Size > 0)
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000259 GPRCS1Push = LastPush = MBBI++;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000260
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000261 // Determine starting offsets of spill areas.
Tim Northoverc9432eb2013-11-04 23:04:15 +0000262 bool HasFP = hasFP(MF);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000263 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
264 + GPRCS2Size + DPRCSSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000265 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
266 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
Tim Northover93bcc662013-11-08 17:18:07 +0000267 int FramePtrOffsetInPush = 0;
268 if (HasFP) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000269 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
270 + GPRCS1Size + ArgRegsSaveSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000271 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
272 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000273 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000274 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
275 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
276 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
277
Tim Northoverc9432eb2013-11-04 23:04:15 +0000278 // Move past area 2.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000279 if (GPRCS2Size > 0)
280 GPRCS2Push = LastPush = MBBI++;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000281
Eric Christopherb006fc92010-11-18 19:40:05 +0000282 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000283 if (DPRCSSize > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000284 DPRCSPush = MBBI;
Evan Cheng70d29632011-02-25 00:24:46 +0000285 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000286 // instructions in the prologue.
Evan Cheng70d29632011-02-25 00:24:46 +0000287 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
Tim Northover93bcc662013-11-08 17:18:07 +0000288 LastPush = MBBI++;
Evan Cheng70d29632011-02-25 00:24:46 +0000289 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000290
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000291 // Move past the aligned DPRCS2 area.
292 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
293 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
294 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
295 // leaves the stack pointer pointing to the DPRCS2 area.
296 //
297 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
298 NumBytes += MFI->getObjectOffset(D8SpillFI);
299 } else
300 NumBytes = DPRCSOffset;
301
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000302 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
303 uint32_t NumWords = NumBytes >> 2;
304
305 if (NumWords < 65536)
306 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000307 .addImm(NumWords)
308 .setMIFlags(MachineInstr::FrameSetup));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000309 else
310 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000311 .addImm(NumWords)
312 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000313
314 switch (TM.getCodeModel()) {
315 case CodeModel::Small:
316 case CodeModel::Medium:
317 case CodeModel::Default:
318 case CodeModel::Kernel:
319 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
320 .addImm((unsigned)ARMCC::AL).addReg(0)
321 .addExternalSymbol("__chkstk")
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000322 .addReg(ARM::R4, RegState::Implicit)
323 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000324 break;
325 case CodeModel::Large:
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000326 case CodeModel::JITDefault:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000327 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000328 .addExternalSymbol("__chkstk")
329 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000330
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000331 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
332 .addImm((unsigned)ARMCC::AL).addReg(0)
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000333 .addReg(ARM::R12, RegState::Kill)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000334 .addReg(ARM::R4, RegState::Implicit)
335 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000336 break;
337 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000338
339 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
340 ARM::SP)
341 .addReg(ARM::SP, RegState::Define)
342 .addReg(ARM::R4, RegState::Kill)
343 .setMIFlags(MachineInstr::FrameSetup)));
344 NumBytes = 0;
345 }
346
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000347 unsigned adjustedGPRCS1Size = GPRCS1Size;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000348 if (NumBytes) {
349 // Adjust SP after all the callee-save spills.
Tim Northovera4173712013-12-08 15:56:50 +0000350 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000351 if (LastPush == GPRCS1Push) {
Tim Northovera4173712013-12-08 15:56:50 +0000352 FramePtrOffsetInPush += NumBytes;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000353 adjustedGPRCS1Size += NumBytes;
354 NumBytes = 0;
355 }
Tim Northovera4173712013-12-08 15:56:50 +0000356 } else
Tim Northover93bcc662013-11-08 17:18:07 +0000357 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
358 MachineInstr::FrameSetup);
359
Evan Chengeb56dca2010-11-22 18:12:04 +0000360 if (HasFP && isARM)
361 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
362 // Note it's not safe to do this in Thumb2 mode because it would have
363 // taken two instructions:
364 // mov sp, r7
365 // sub sp, #24
366 // If an interrupt is taken between the two instructions, then sp is in
367 // an inconsistent state (pointing to the middle of callee-saved area).
368 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000369 AFI->setShouldRestoreSPFromFP(true);
370 }
371
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000372 if (adjustedGPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000373 CFAOffset -= adjustedGPRCS1Size;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000374 unsigned CFIIndex = MMI.addFrameInst(
375 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
376 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
377 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
378 .addCFIIndex(CFIIndex);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000379 for (const auto &Entry : CSI) {
380 unsigned Reg = Entry.getReg();
381 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000382 switch (Reg) {
383 case ARM::R8:
384 case ARM::R9:
385 case ARM::R10:
386 case ARM::R11:
387 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000388 if (STI.isTargetDarwin())
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000389 break;
390 // fallthrough
391 case ARM::R0:
392 case ARM::R1:
393 case ARM::R2:
394 case ARM::R3:
395 case ARM::R4:
396 case ARM::R5:
397 case ARM::R6:
398 case ARM::R7:
399 case ARM::LR:
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000400 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
401 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
402 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
403 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000404 break;
405 }
406 }
407 }
408
Tim Northover93bcc662013-11-08 17:18:07 +0000409 // Set FP to point to the stack slot that contains the previous FP.
410 // For iOS, FP is R7, which has now been stored in spill area 1.
411 // Otherwise, if this is not iOS, all the callee-saved registers go
412 // into spill area 1, including the FP in R11. In either case, it
413 // is in area one and the adjustment needs to take place just after
414 // that push.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000415 if (HasFP) {
416 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
Tim Northover93bcc662013-11-08 17:18:07 +0000417 FramePtr, ARM::SP, FramePtrOffsetInPush,
418 MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000419 if (FramePtrOffsetInPush) {
420 CFAOffset += FramePtrOffsetInPush;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000421 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
422 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
423 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
424 .addCFIIndex(CFIIndex);
425
426 } else {
427 unsigned CFIIndex =
428 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
429 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
430 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
431 .addCFIIndex(CFIIndex);
432 }
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000433 }
Tim Northover93bcc662013-11-08 17:18:07 +0000434
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000435 if (GPRCS2Size > 0) {
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000436 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000437 if (!HasFP) {
438 CFAOffset -= GPRCS2Size;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000439 unsigned CFIIndex = MMI.addFrameInst(
440 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
441 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
442 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000443 }
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000444 for (const auto &Entry : CSI) {
445 unsigned Reg = Entry.getReg();
446 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000447 switch (Reg) {
448 case ARM::R8:
449 case ARM::R9:
450 case ARM::R10:
451 case ARM::R11:
452 case ARM::R12:
Tim Northover86f60b72014-05-30 13:23:06 +0000453 if (STI.isTargetDarwin()) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000454 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Oliver Stannardd55e1152014-03-05 15:25:27 +0000455 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000456 unsigned CFIIndex = MMI.addFrameInst(
457 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
458 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
459 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000460 }
461 break;
462 }
463 }
464 }
465
466 if (DPRCSSize > 0) {
467 // Since vpush register list cannot have gaps, there may be multiple vpush
468 // instructions in the prologue.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000469 do {
470 MachineBasicBlock::iterator Push = DPRCSPush++;
471 if (!HasFP) {
Alp Toker98444342014-04-19 23:56:35 +0000472 CFAOffset -= sizeOfSPAdjustment(Push);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000473 unsigned CFIIndex = MMI.addFrameInst(
474 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
475 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
476 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000477 }
478 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
479
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000480 for (const auto &Entry : CSI) {
481 unsigned Reg = Entry.getReg();
482 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000483 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
484 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
485 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
486 unsigned Offset = MFI->getObjectOffset(FI);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000487 unsigned CFIIndex = MMI.addFrameInst(
488 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
489 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
490 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000491 }
492 }
493 }
494
495 if (NumBytes) {
496 if (!HasFP) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000497 CFAOffset -= NumBytes;
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000498 unsigned CFIIndex = MMI.addFrameInst(
499 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
500 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
501 .addCFIIndex(CFIIndex);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000502 }
503 }
Tim Northover93bcc662013-11-08 17:18:07 +0000504
Evan Chengeb56dca2010-11-22 18:12:04 +0000505 if (STI.isTargetELF() && hasFP(MF))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000506 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
507 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000508
509 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
510 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
511 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
512
513 // If we need dynamic stack realignment, do it here. Be paranoid and make
514 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000515 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000516 // realigned.
517 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000518 unsigned MaxAlign = MFI->getMaxAlignment();
519 assert (!AFI->isThumb1OnlyFunction());
520 if (!AFI->isThumbFunction()) {
521 // Emit bic sp, sp, MaxAlign
522 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
523 TII.get(ARM::BICri), ARM::SP)
524 .addReg(ARM::SP, RegState::Kill)
525 .addImm(MaxAlign-1)));
526 } else {
527 // We cannot use sp as source/dest register here, thus we're emitting the
528 // following sequence:
529 // mov r4, sp
530 // bic r4, r4, MaxAlign
531 // mov sp, r4
532 // FIXME: It will be better just to find spare register here.
Jim Grosbache9cc9012011-06-30 23:38:17 +0000533 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000534 .addReg(ARM::SP, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000535 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
536 TII.get(ARM::t2BICri), ARM::R4)
537 .addReg(ARM::R4, RegState::Kill)
538 .addImm(MaxAlign-1)));
Jim Grosbache9cc9012011-06-30 23:38:17 +0000539 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
Jim Grosbachb98ab912011-06-30 22:10:46 +0000540 .addReg(ARM::R4, RegState::Kill));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000541 }
542
543 AFI->setShouldRestoreSPFromFP(true);
544 }
545
546 // If we need a base pointer, set it up here. It's whatever the value
547 // of the stack pointer is at this point. Any variable size objects
548 // will be allocated after this, so we can still use the base pointer
549 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000550 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000551 if (RegInfo->hasBasePointer(MF)) {
552 if (isARM)
553 BuildMI(MBB, MBBI, dl,
554 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
555 .addReg(ARM::SP)
556 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
557 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000558 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000559 RegInfo->getBaseRegister())
560 .addReg(ARM::SP));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000561 }
562
563 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000564 // the sp from fp. We can assume there's an FP here since hasFP already
565 // checks for hasVarSizedObjects.
Evan Chengeb56dca2010-11-22 18:12:04 +0000566 if (MFI->hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000567 AFI->setShouldRestoreSPFromFP(true);
568}
569
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000570void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000571 MachineBasicBlock &MBB) const {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000572 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
Evan Cheng7f8e5632011-12-07 07:15:52 +0000573 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000574 unsigned RetOpcode = MBBI->getOpcode();
575 DebugLoc dl = MBBI->getDebugLoc();
576 MachineFrameInfo *MFI = MF.getFrameInfo();
577 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000578 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000579 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000580 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000581 assert(!AFI->isThumb1OnlyFunction() &&
582 "This emitEpilogue does not support Thumb1!");
583 bool isARM = !AFI->isThumbFunction();
584
Eric Christopherd9134482014-08-04 21:25:23 +0000585 unsigned Align = MF.getTarget()
586 .getSubtargetImpl()
587 ->getFrameLowering()
588 ->getStackAlignment();
Stepan Dyatkovskiyd0e34a22013-05-20 08:01:34 +0000589 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000590 int NumBytes = (int)MFI->getStackSize();
591 unsigned FramePtr = RegInfo->getFrameRegister(MF);
592
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000593 // All calls are tail calls in GHC calling conv, and functions have no
594 // prologue/epilogue.
Eric Christopherb3322362012-08-03 00:05:53 +0000595 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
596 return;
597
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000598 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000599 if (NumBytes - ArgRegsSaveSize != 0)
600 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000601 } else {
602 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000603 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000604 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000605 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000606 --MBBI;
Tim Northover93bcc662013-11-08 17:18:07 +0000607 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000608 if (!isCSRestore(MBBI, TII, CSRegs))
609 ++MBBI;
610 }
611
612 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000613 NumBytes -= (ArgRegsSaveSize +
614 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000615 AFI->getGPRCalleeSavedArea2Size() +
616 AFI->getDPRCalleeSavedAreaSize());
617
618 // Reset SP based on frame pointer only if the stack frame extends beyond
619 // frame pointer stack slot or target is ELF and the function has FP.
620 if (AFI->shouldRestoreSPFromFP()) {
621 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
622 if (NumBytes) {
623 if (isARM)
624 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
625 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000626 else {
627 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000628 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000629 // mov sp, r7
630 // sub sp, #24
631 // This is bad, if an interrupt is taken after the mov, sp is in an
632 // inconsistent state.
633 // Use the first callee-saved register as a scratch register.
Kaelyn Uhrain271fbb62012-10-26 23:28:41 +0000634 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000635 "No scratch register to restore SP from FP!");
636 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000637 ARMCC::AL, 0, TII);
Jim Grosbache9cc9012011-06-30 23:38:17 +0000638 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000639 ARM::SP)
640 .addReg(ARM::R4));
Evan Chengeb56dca2010-11-22 18:12:04 +0000641 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000642 } else {
643 // Thumb2 or ARM.
644 if (isARM)
645 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
646 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
647 else
Jim Grosbache9cc9012011-06-30 23:38:17 +0000648 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
Jim Grosbachb98ab912011-06-30 22:10:46 +0000649 ARM::SP)
650 .addReg(FramePtr));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000651 }
Tim Northoverdee86042013-12-02 14:46:26 +0000652 } else if (NumBytes &&
Tim Northovere4def5e2013-12-05 11:02:02 +0000653 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
Tim Northover93bcc662013-11-08 17:18:07 +0000654 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000655
Eric Christopherb006fc92010-11-18 19:40:05 +0000656 // Increment past our save areas.
Evan Cheng70d29632011-02-25 00:24:46 +0000657 if (AFI->getDPRCalleeSavedAreaSize()) {
658 MBBI++;
659 // Since vpop register list cannot have gaps, there may be multiple vpop
660 // instructions in the epilogue.
661 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
662 MBBI++;
663 }
Eric Christopherb006fc92010-11-18 19:40:05 +0000664 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
665 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000666 }
667
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000668 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000669 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000670 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000671 MachineOperand &JumpTarget = MBBI->getOperand(0);
672
673 // Jump to label or value in register.
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000674 if (RetOpcode == ARM::TCRETURNdi) {
675 unsigned TCOpcode = STI.isThumb() ?
Tim Northoverd6a729b2014-01-06 14:28:05 +0000676 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000677 ARM::TAILJMPd;
Evan Chengd4b08732010-11-30 23:55:39 +0000678 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
679 if (JumpTarget.isGlobal())
680 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
681 JumpTarget.getTargetFlags());
682 else {
683 assert(JumpTarget.isSymbol());
684 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
685 JumpTarget.getTargetFlags());
686 }
Owen Anderson29cfe6c2011-09-09 21:48:23 +0000687
688 // Add the default predicate in Thumb mode.
689 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000690 } else if (RetOpcode == ARM::TCRETURNri) {
Jim Grosbach3af6fe62011-03-15 00:30:40 +0000691 BuildMI(MBB, MBBI, dl,
692 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000693 addReg(JumpTarget.getReg(), RegState::Kill);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000694 }
695
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000696 MachineInstr *NewMI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000697 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
698 NewMI->addOperand(MBBI->getOperand(i));
699
700 // Delete the pseudo instruction TCRETURN.
701 MBB.erase(MBBI);
Cameron Zwarich033026f2011-06-17 02:16:43 +0000702 MBBI = NewMI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000703 }
704
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000705 if (ArgRegsSaveSize)
706 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000707}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000708
Bob Wilson657f2272011-01-13 21:10:12 +0000709/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
710/// debug info. It's the same as what we use for resolving the code-gen
711/// references for now. FIXME: This can go wrong when references are
712/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000713int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000714ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000715 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000716 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
717}
718
719int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000720ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000721 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000722 int SPAdj) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000723 const MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000724 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000725 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000726 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
727 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
728 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
729 bool isFixed = MFI->isFixedObjectIndex(FI);
730
731 FrameReg = ARM::SP;
732 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000733
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000734 // SP can move around if there are allocas. We may also lose track of SP
735 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000736 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000737
Anton Korobeynikov46877782010-11-20 15:59:32 +0000738 // When dynamically realigning the stack, use the frame pointer for
739 // parameters, and the stack/base pointer for locals.
740 if (RegInfo->needsStackRealignment(MF)) {
741 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
742 if (isFixed) {
743 FrameReg = RegInfo->getFrameRegister(MF);
744 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000745 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000746 assert(RegInfo->hasBasePointer(MF) &&
747 "VLAs and dynamic stack alignment, but missing base pointer!");
748 FrameReg = RegInfo->getBaseRegister();
749 }
750 return Offset;
751 }
752
753 // If there is a frame pointer, use it when we can.
754 if (hasFP(MF) && AFI->hasStackFrame()) {
755 // Use frame pointer to reference fixed objects. Use it for locals if
756 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000757 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000758 FrameReg = RegInfo->getFrameRegister(MF);
759 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000760 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000761 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000762 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000763 // Try to use the frame pointer if we can, else use the base pointer
764 // since it's available. This is handy for the emergency spill slot, in
765 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000766 if (FPOffset >= -255 && FPOffset < 0) {
767 FrameReg = RegInfo->getFrameRegister(MF);
768 return FPOffset;
769 }
Evan Chengc0d20042011-04-22 01:42:52 +0000770 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000771 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000772 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000773 // ldr <rd>, [sp, #<imm8>]
774 // if at all possible to save space.
775 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
776 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000777 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000778 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000779 if (FPOffset >= -255 && FPOffset < 0) {
780 FrameReg = RegInfo->getFrameRegister(MF);
781 return FPOffset;
782 }
783 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
784 // Otherwise, use SP or FP, whichever is closer to the stack slot.
785 FrameReg = RegInfo->getFrameRegister(MF);
786 return FPOffset;
787 }
788 }
789 // Use the base pointer if we have one.
790 if (RegInfo->hasBasePointer(MF))
791 FrameReg = RegInfo->getBaseRegister();
792 return Offset;
793}
794
Bob Wilson657f2272011-01-13 21:10:12 +0000795int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
796 int FI) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000797 unsigned FrameReg;
798 return getFrameIndexReference(MF, FI, FrameReg);
799}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000800
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000801void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000802 MachineBasicBlock::iterator MI,
803 const std::vector<CalleeSavedInfo> &CSI,
804 unsigned StmOpc, unsigned StrOpc,
805 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000806 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000807 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000808 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000809 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000810 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000811
812 DebugLoc DL;
813 if (MI != MBB.end()) DL = MI->getDebugLoc();
814
Evan Chengc27c9562010-12-07 19:59:34 +0000815 SmallVector<std::pair<unsigned,bool>, 4> Regs;
Evan Cheng775ead32010-12-07 23:08:38 +0000816 unsigned i = CSI.size();
817 while (i != 0) {
818 unsigned LastReg = 0;
819 for (; i != 0; --i) {
820 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000821 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000822
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000823 // D-registers in the aligned area DPRCS2 are NOT spilled here.
824 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
825 continue;
826
Evan Cheng775ead32010-12-07 23:08:38 +0000827 // Add the callee-saved register as live-in unless it's LR and
Jim Grosbachc0b669f2010-12-09 16:14:46 +0000828 // @llvm.returnaddress is called. If LR is returned for
829 // @llvm.returnaddress then it's already added to the function and
830 // entry block live-in sets.
Evan Cheng775ead32010-12-07 23:08:38 +0000831 bool isKill = true;
832 if (Reg == ARM::LR) {
833 if (MF.getFrameInfo()->isReturnAddressTaken() &&
834 MF.getRegInfo().isLiveIn(Reg))
835 isKill = false;
836 }
837
838 if (isKill)
839 MBB.addLiveIn(Reg);
840
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000841 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000842 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000843 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000844 if (NoGap && LastReg && LastReg != Reg-1)
845 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000846 LastReg = Reg;
847 Regs.push_back(std::make_pair(Reg, isKill));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000848 }
849
Jim Grosbach5fccad82010-12-09 18:31:13 +0000850 if (Regs.empty())
851 continue;
852 if (Regs.size() > 1 || StrOpc== 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000853 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000854 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000855 .addReg(ARM::SP).setMIFlags(MIFlags));
Evan Cheng775ead32010-12-07 23:08:38 +0000856 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
857 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +0000858 } else if (Regs.size() == 1) {
859 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
860 ARM::SP)
861 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
Jim Grosbachf0c95ca2011-08-05 20:35:44 +0000862 .addReg(ARM::SP).setMIFlags(MIFlags)
863 .addImm(-4);
Jim Grosbach5fccad82010-12-09 18:31:13 +0000864 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000865 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000866 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000867
868 // Put any subsequent vpush instructions before this one: they will refer to
869 // higher register numbers so need to be pushed first in order to preserve
870 // monotonicity.
871 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000872 }
Evan Cheng775ead32010-12-07 23:08:38 +0000873}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000874
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000875void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000876 MachineBasicBlock::iterator MI,
877 const std::vector<CalleeSavedInfo> &CSI,
878 unsigned LdmOpc, unsigned LdrOpc,
879 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000880 bool(*Func)(unsigned, bool),
881 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +0000882 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +0000883 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Evan Cheng775ead32010-12-07 23:08:38 +0000884 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
885 DebugLoc DL = MI->getDebugLoc();
Evan Chengd6093ff2011-01-25 01:28:33 +0000886 unsigned RetOpcode = MI->getOpcode();
887 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
Jakob Stoklund Olesenb4bd3882012-04-06 21:17:42 +0000888 RetOpcode == ARM::TCRETURNri);
Tim Northoverd8407452013-10-01 14:33:28 +0000889 bool isInterrupt =
890 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Evan Cheng775ead32010-12-07 23:08:38 +0000891
892 SmallVector<unsigned, 4> Regs;
893 unsigned i = CSI.size();
894 while (i != 0) {
895 unsigned LastReg = 0;
896 bool DeleteRet = false;
897 for (; i != 0; --i) {
898 unsigned Reg = CSI[i-1].getReg();
Tim Northover86f60b72014-05-30 13:23:06 +0000899 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
Evan Cheng775ead32010-12-07 23:08:38 +0000900
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000901 // The aligned reloads from area DPRCS2 are not inserted here.
902 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
903 continue;
904
Tim Northoverd8407452013-10-01 14:33:28 +0000905 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
906 STI.hasV5TOps()) {
Evan Cheng775ead32010-12-07 23:08:38 +0000907 Reg = ARM::PC;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000908 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Evan Cheng775ead32010-12-07 23:08:38 +0000909 // Fold the return instruction into the LDM.
910 DeleteRet = true;
911 }
912
Evan Cheng9d54ae62010-12-08 06:29:02 +0000913 // If NoGap is true, pop consecutive registers and then leave the rest
914 // for other instructions. e.g.
915 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
916 if (NoGap && LastReg && LastReg != Reg-1)
917 break;
918
Evan Cheng775ead32010-12-07 23:08:38 +0000919 LastReg = Reg;
920 Regs.push_back(Reg);
921 }
922
Jim Grosbach5fccad82010-12-09 18:31:13 +0000923 if (Regs.empty())
924 continue;
925 if (Regs.size() > 1 || LdrOpc == 0) {
Evan Cheng775ead32010-12-07 23:08:38 +0000926 MachineInstrBuilder MIB =
Jim Grosbach5fccad82010-12-09 18:31:13 +0000927 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
Evan Cheng775ead32010-12-07 23:08:38 +0000928 .addReg(ARM::SP));
929 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
930 MIB.addReg(Regs[i], getDefRegState(true));
Andrew Trick6446bf72011-08-25 17:50:53 +0000931 if (DeleteRet) {
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +0000932 MIB.copyImplicitOps(&*MI);
Evan Cheng775ead32010-12-07 23:08:38 +0000933 MI->eraseFromParent();
Andrew Trick6446bf72011-08-25 17:50:53 +0000934 }
Evan Cheng775ead32010-12-07 23:08:38 +0000935 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +0000936 } else if (Regs.size() == 1) {
937 // If we adjusted the reg to PC from LR above, switch it back here. We
938 // only do that for LDM.
939 if (Regs[0] == ARM::PC)
940 Regs[0] = ARM::LR;
941 MachineInstrBuilder MIB =
942 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
943 .addReg(ARM::SP, RegState::Define)
944 .addReg(ARM::SP);
945 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
946 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +0000947 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +0000948 MIB.addReg(0);
949 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
950 } else
951 MIB.addImm(4);
952 AddDefaultPred(MIB);
Evan Cheng775ead32010-12-07 23:08:38 +0000953 }
Jim Grosbach5fccad82010-12-09 18:31:13 +0000954 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +0000955
956 // Put any subsequent vpop instructions after this one: they will refer to
957 // higher register numbers so need to be popped afterwards.
958 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +0000959 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000960}
961
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000962/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000963/// starting from d8. Also insert stack realignment code and leave the stack
964/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000965static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
966 MachineBasicBlock::iterator MI,
967 unsigned NumAlignedDPRCS2Regs,
968 const std::vector<CalleeSavedInfo> &CSI,
969 const TargetRegisterInfo *TRI) {
970 MachineFunction &MF = *MBB.getParent();
971 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
972 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +0000973 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000974 MachineFrameInfo &MFI = *MF.getFrameInfo();
975
976 // Mark the D-register spill slots as properly aligned. Since MFI computes
977 // stack slot layout backwards, this can actually mean that the d-reg stack
978 // slot offsets can be wrong. The offset for d8 will always be correct.
979 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
980 unsigned DNum = CSI[i].getReg() - ARM::D8;
981 if (DNum >= 8)
982 continue;
983 int FI = CSI[i].getFrameIdx();
984 // The even-numbered registers will be 16-byte aligned, the odd-numbered
985 // registers will be 8-byte aligned.
986 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
987
988 // The stack slot for D8 needs to be maximally aligned because this is
989 // actually the point where we align the stack pointer. MachineFrameInfo
990 // computes all offsets relative to the incoming stack pointer which is a
991 // bit weird when realigning the stack. Any extra padding for this
992 // over-alignment is not realized because the code inserted below adjusts
993 // the stack pointer by numregs * 8 before aligning the stack pointer.
994 if (DNum == 0)
995 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
996 }
997
998 // Move the stack pointer to the d8 spill slot, and align it at the same
999 // time. Leave the stack slot address in the scratch register r4.
1000 //
1001 // sub r4, sp, #numregs * 8
1002 // bic r4, r4, #align - 1
1003 // mov sp, r4
1004 //
1005 bool isThumb = AFI->isThumbFunction();
1006 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1007 AFI->setShouldRestoreSPFromFP(true);
1008
1009 // sub r4, sp, #numregs * 8
1010 // The immediate is <= 64, so it doesn't need any special encoding.
1011 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1012 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1013 .addReg(ARM::SP)
1014 .addImm(8 * NumAlignedDPRCS2Regs)));
1015
1016 // bic r4, r4, #align-1
1017 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1018 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1019 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1020 .addReg(ARM::R4, RegState::Kill)
1021 .addImm(MaxAlign - 1)));
1022
1023 // mov sp, r4
1024 // The stack pointer must be adjusted before spilling anything, otherwise
1025 // the stack slots could be clobbered by an interrupt handler.
1026 // Leave r4 live, it is used below.
1027 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1028 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1029 .addReg(ARM::R4);
1030 MIB = AddDefaultPred(MIB);
1031 if (!isThumb)
1032 AddDefaultCC(MIB);
1033
1034 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1035 // r4 holds the stack slot address.
1036 unsigned NextReg = ARM::D8;
1037
1038 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1039 // The writeback is only needed when emitting two vst1.64 instructions.
1040 if (NumAlignedDPRCS2Regs >= 6) {
1041 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001042 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001043 MBB.addLiveIn(SupReg);
1044 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1045 ARM::R4)
1046 .addReg(ARM::R4, RegState::Kill).addImm(16)
1047 .addReg(NextReg)
1048 .addReg(SupReg, RegState::ImplicitKill));
1049 NextReg += 4;
1050 NumAlignedDPRCS2Regs -= 4;
1051 }
1052
1053 // We won't modify r4 beyond this point. It currently points to the next
1054 // register to be spilled.
1055 unsigned R4BaseReg = NextReg;
1056
1057 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1058 if (NumAlignedDPRCS2Regs >= 4) {
1059 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001060 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001061 MBB.addLiveIn(SupReg);
1062 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1063 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1064 .addReg(SupReg, RegState::ImplicitKill));
1065 NextReg += 4;
1066 NumAlignedDPRCS2Regs -= 4;
1067 }
1068
1069 // 16-byte aligned vst1.64 with 2 d-regs.
1070 if (NumAlignedDPRCS2Regs >= 2) {
1071 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001072 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001073 MBB.addLiveIn(SupReg);
1074 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001075 .addReg(ARM::R4).addImm(16).addReg(SupReg));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001076 NextReg += 2;
1077 NumAlignedDPRCS2Regs -= 2;
1078 }
1079
1080 // Finally, use a vanilla vstr.64 for the odd last register.
1081 if (NumAlignedDPRCS2Regs) {
1082 MBB.addLiveIn(NextReg);
1083 // vstr.64 uses addrmode5 which has an offset scale of 4.
1084 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1085 .addReg(NextReg)
1086 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1087 }
1088
1089 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001090 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001091}
1092
1093/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1094/// iterator to the following instruction.
1095static MachineBasicBlock::iterator
1096skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1097 unsigned NumAlignedDPRCS2Regs) {
1098 // sub r4, sp, #numregs * 8
1099 // bic r4, r4, #align - 1
1100 // mov sp, r4
1101 ++MI; ++MI; ++MI;
1102 assert(MI->mayStore() && "Expecting spill instruction");
1103
1104 // These switches all fall through.
1105 switch(NumAlignedDPRCS2Regs) {
1106 case 7:
1107 ++MI;
1108 assert(MI->mayStore() && "Expecting spill instruction");
1109 default:
1110 ++MI;
1111 assert(MI->mayStore() && "Expecting spill instruction");
1112 case 1:
1113 case 2:
1114 case 4:
1115 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1116 ++MI;
1117 }
1118 return MI;
1119}
1120
1121/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1122/// starting from d8. These instructions are assumed to execute while the
1123/// stack is still aligned, unlike the code inserted by emitPopInst.
1124static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1125 MachineBasicBlock::iterator MI,
1126 unsigned NumAlignedDPRCS2Regs,
1127 const std::vector<CalleeSavedInfo> &CSI,
1128 const TargetRegisterInfo *TRI) {
1129 MachineFunction &MF = *MBB.getParent();
1130 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1131 DebugLoc DL = MI->getDebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001132 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001133
1134 // Find the frame index assigned to d8.
1135 int D8SpillFI = 0;
1136 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1137 if (CSI[i].getReg() == ARM::D8) {
1138 D8SpillFI = CSI[i].getFrameIdx();
1139 break;
1140 }
1141
1142 // Materialize the address of the d8 spill slot into the scratch register r4.
1143 // This can be fairly complicated if the stack frame is large, so just use
1144 // the normal frame index elimination mechanism to do it. This code runs as
1145 // the initial part of the epilog where the stack and base pointers haven't
1146 // been changed yet.
1147 bool isThumb = AFI->isThumbFunction();
1148 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1149
1150 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1151 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1152 .addFrameIndex(D8SpillFI).addImm(0)));
1153
1154 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1155 unsigned NextReg = ARM::D8;
1156
1157 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1158 if (NumAlignedDPRCS2Regs >= 6) {
1159 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001160 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001161 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1162 .addReg(ARM::R4, RegState::Define)
1163 .addReg(ARM::R4, RegState::Kill).addImm(16)
1164 .addReg(SupReg, RegState::ImplicitDefine));
1165 NextReg += 4;
1166 NumAlignedDPRCS2Regs -= 4;
1167 }
1168
1169 // We won't modify r4 beyond this point. It currently points to the next
1170 // register to be spilled.
1171 unsigned R4BaseReg = NextReg;
1172
1173 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1174 if (NumAlignedDPRCS2Regs >= 4) {
1175 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001176 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001177 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1178 .addReg(ARM::R4).addImm(16)
1179 .addReg(SupReg, RegState::ImplicitDefine));
1180 NextReg += 4;
1181 NumAlignedDPRCS2Regs -= 4;
1182 }
1183
1184 // 16-byte aligned vld1.64 with 2 d-regs.
1185 if (NumAlignedDPRCS2Regs >= 2) {
1186 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001187 &ARM::QPRRegClass);
Jim Grosbachc988e0c2012-03-05 19:33:30 +00001188 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1189 .addReg(ARM::R4).addImm(16));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001190 NextReg += 2;
1191 NumAlignedDPRCS2Regs -= 2;
1192 }
1193
1194 // Finally, use a vanilla vldr.64 for the remaining odd register.
1195 if (NumAlignedDPRCS2Regs)
1196 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1197 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1198
1199 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001200 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001201}
1202
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001203bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001204 MachineBasicBlock::iterator MI,
1205 const std::vector<CalleeSavedInfo> &CSI,
1206 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001207 if (CSI.empty())
1208 return false;
1209
1210 MachineFunction &MF = *MBB.getParent();
1211 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001212
1213 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001214 unsigned PushOneOpc = AFI->isThumbFunction() ?
1215 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001216 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001217 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1218 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001219 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001220 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001221 MachineInstr::FrameSetup);
1222 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001223 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1224
1225 // The code above does not insert spill code for the aligned DPRCS2 registers.
1226 // The stack realignment code will be inserted between the push instructions
1227 // and these spills.
1228 if (NumAlignedDPRCS2Regs)
1229 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001230
1231 return true;
1232}
1233
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001234bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001235 MachineBasicBlock::iterator MI,
1236 const std::vector<CalleeSavedInfo> &CSI,
1237 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001238 if (CSI.empty())
1239 return false;
1240
1241 MachineFunction &MF = *MBB.getParent();
1242 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001243 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001244 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1245
1246 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1247 // registers. Do that here instead.
1248 if (NumAlignedDPRCS2Regs)
1249 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001250
1251 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001252 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001253 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001254 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1255 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001256 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001257 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001258 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001259 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001260
1261 return true;
1262}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001263
1264// FIXME: Make generic?
1265static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1266 const ARMBaseInstrInfo &TII) {
1267 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001268 for (auto &MBB : MF) {
1269 for (auto &MI : MBB)
1270 FnSize += TII.GetInstSizeInBytes(&MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001271 }
1272 return FnSize;
1273}
1274
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001275/// estimateRSStackSizeLimit - Look at each instruction that references stack
1276/// frames and return the stack size limit beyond which some of these
1277/// instructions will require a scratch register during their expansion later.
1278// FIXME: Move to TII?
1279static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001280 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001281 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1282 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001283 for (auto &MBB : MF) {
1284 for (auto &MI : MBB) {
1285 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1286 if (!MI.getOperand(i).isFI())
1287 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001288
1289 // When using ADDri to get the address of a stack object, 255 is the
1290 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001291 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001292 Limit = std::min(Limit, (1U << 8) - 1);
1293 break;
1294 }
1295
1296 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001297 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001298 case ARMII::AddrMode3:
1299 case ARMII::AddrModeT2_i8:
1300 Limit = std::min(Limit, (1U << 8) - 1);
1301 break;
1302 case ARMII::AddrMode5:
1303 case ARMII::AddrModeT2_i8s4:
1304 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1305 break;
1306 case ARMII::AddrModeT2_i12:
1307 // i12 supports only positive offset so these will be converted to
1308 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1309 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1310 Limit = std::min(Limit, (1U << 8) - 1);
1311 break;
1312 case ARMII::AddrMode4:
1313 case ARMII::AddrMode6:
1314 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1315 // immediate offset for stack references.
1316 return 0;
1317 default:
1318 break;
1319 }
1320 break; // At most one FI per instruction
1321 }
1322 }
1323 }
1324
1325 return Limit;
1326}
1327
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001328// In functions that realign the stack, it can be an advantage to spill the
1329// callee-saved vector registers after realigning the stack. The vst1 and vld1
1330// instructions take alignment hints that can improve performance.
1331//
1332static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1333 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1334 if (!SpillAlignedNEONRegs)
1335 return;
1336
1337 // Naked functions don't spill callee-saved registers.
Bill Wendling698e84f2012-12-30 10:32:01 +00001338 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1339 Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001340 return;
1341
1342 // We are planning to use NEON instructions vst1 / vld1.
1343 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1344 return;
1345
1346 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopherd9134482014-08-04 21:25:23 +00001347 if (MF.getTarget()
1348 .getSubtargetImpl()
1349 ->getFrameLowering()
1350 ->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001351 return;
1352
1353 // Aligned spills require stack realignment.
Eric Christopherd9134482014-08-04 21:25:23 +00001354 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001355 MF.getSubtarget().getRegisterInfo());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001356 if (!RegInfo->canRealignStack(MF))
1357 return;
1358
1359 // We always spill contiguous d-registers starting from d8. Count how many
1360 // needs spilling. The register allocator will almost always use the
1361 // callee-saved registers in order, but it can happen that there are holes in
1362 // the range. Registers above the hole will be spilled to the standard DPRCS
1363 // area.
1364 MachineRegisterInfo &MRI = MF.getRegInfo();
1365 unsigned NumSpills = 0;
1366 for (; NumSpills < 8; ++NumSpills)
Jakob Stoklund Olesen07364422012-10-17 18:44:18 +00001367 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001368 break;
1369
1370 // Don't do this for just one d-register. It's not worth it.
1371 if (NumSpills < 2)
1372 return;
1373
1374 // Spill the first NumSpills D-registers after realigning the stack.
1375 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1376
1377 // A scratch register is required for the vst1 / vld1 instructions.
1378 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1379}
1380
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001381void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001382ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +00001383 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001384 // This tells PEI to spill the FP as if it is any other callee-save register
1385 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1386 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1387 // to combine multiple loads / stores.
1388 bool CanEliminateFrame = true;
1389 bool CS1Spilled = false;
1390 bool LRSpilled = false;
1391 unsigned NumGPRSpills = 0;
1392 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1393 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001394 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001395 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001396 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001397 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001398 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1399 MachineFrameInfo *MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001400 MachineRegisterInfo &MRI = MF.getRegInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001401 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1402
1403 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1404 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001405 // since it's not always possible to restore sp from fp in a single
1406 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001407 // FIXME: It will be better just to find spare register here.
1408 if (AFI->isThumb2Function() &&
1409 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001410 MRI.setPhysRegUsed(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001411
Evan Cheng572756a2011-01-16 05:14:33 +00001412 if (AFI->isThumb1OnlyFunction()) {
1413 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001414 if (AFI->getArgRegsSaveSize() > 0)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001415 MRI.setPhysRegUsed(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001416
Jim Grosbachdca85312011-06-13 21:18:25 +00001417 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1418 // for sure what the stack size will be, but for this, an estimate is good
1419 // enough. If there anything changes it, it'll be a spill, which implies
1420 // we've used all the registers and so R4 is already used, so not marking
Chad Rosieradd38c12011-10-20 00:07:12 +00001421 // it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001422 // FIXME: It will be better just to find spare register here.
Hal Finkel628ba122013-03-14 21:15:20 +00001423 unsigned StackSize = MFI->estimateStackSize(MF);
Chad Rosieradd38c12011-10-20 00:07:12 +00001424 if (MFI->hasVarSizedObjects() || StackSize > 508)
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001425 MRI.setPhysRegUsed(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001426 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001427
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001428 // See if we can spill vector registers to aligned stack.
1429 checkNumAlignedDPRCS2Regs(MF);
1430
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001431 // Spill the BasePtr if it's used.
1432 if (RegInfo->hasBasePointer(MF))
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001433 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001434
1435 // Don't spill FP if the frame can be eliminated. This is determined
1436 // by scanning the callee-save registers to see if any is used.
Craig Topper840beec2014-04-04 05:16:06 +00001437 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001438 for (unsigned i = 0; CSRegs[i]; ++i) {
1439 unsigned Reg = CSRegs[i];
1440 bool Spilled = false;
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001441 if (MRI.isPhysRegUsed(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001442 Spilled = true;
1443 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001444 }
1445
Craig Topperc7242e02012-04-20 07:30:17 +00001446 if (!ARM::GPRRegClass.contains(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001447 continue;
1448
1449 if (Spilled) {
1450 NumGPRSpills++;
1451
Tim Northover86f60b72014-05-30 13:23:06 +00001452 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001453 if (Reg == ARM::LR)
1454 LRSpilled = true;
1455 CS1Spilled = true;
1456 continue;
1457 }
1458
1459 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1460 switch (Reg) {
1461 case ARM::LR:
1462 LRSpilled = true;
1463 // Fallthrough
Tim Northoverd8407452013-10-01 14:33:28 +00001464 case ARM::R0: case ARM::R1:
1465 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001466 case ARM::R4: case ARM::R5:
1467 case ARM::R6: case ARM::R7:
1468 CS1Spilled = true;
1469 break;
1470 default:
1471 break;
1472 }
1473 } else {
Tim Northover86f60b72014-05-30 13:23:06 +00001474 if (!STI.isTargetDarwin()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001475 UnspilledCS1GPRs.push_back(Reg);
1476 continue;
1477 }
1478
1479 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001480 case ARM::R0: case ARM::R1:
1481 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001482 case ARM::R4: case ARM::R5:
1483 case ARM::R6: case ARM::R7:
1484 case ARM::LR:
1485 UnspilledCS1GPRs.push_back(Reg);
1486 break;
1487 default:
1488 UnspilledCS2GPRs.push_back(Reg);
1489 break;
1490 }
1491 }
1492 }
1493
1494 bool ForceLRSpill = false;
1495 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1496 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1497 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1498 // use of BL to implement far jump. If it turns out that it's not needed
1499 // then the branch fix up path will undo it.
1500 if (FnSize >= (1 << 11)) {
1501 CanEliminateFrame = false;
1502 ForceLRSpill = true;
1503 }
1504 }
1505
1506 // If any of the stack slot references may be out of range of an immediate
1507 // offset, make sure a register (or a spill slot) is available for the
1508 // register scavenger. Note that if we're indexing off the frame pointer, the
1509 // effective stack size is 4 bytes larger since the FP points to the stack
1510 // slot of the previous FP. Also, if we have variable sized objects in the
1511 // function, stack slot references will often be negative, and some of
1512 // our instructions are positive-offset only, so conservatively consider
1513 // that case to want a spill slot (or register) as well. Similarly, if
1514 // the function adjusts the stack pointer during execution and the
1515 // adjustments aren't already part of our stack size estimate, our offset
1516 // calculations may be off, so be conservative.
1517 // FIXME: We could add logic to be more precise about negative offsets
1518 // and which instructions will need a scratch register for them. Is it
1519 // worth the effort and added fragility?
1520 bool BigStack =
1521 (RS &&
Hal Finkel628ba122013-03-14 21:15:20 +00001522 (MFI->estimateStackSize(MF) +
1523 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001524 estimateRSStackSizeLimit(MF, this)))
1525 || MFI->hasVarSizedObjects()
1526 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1527
1528 bool ExtraCSSpill = false;
1529 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1530 AFI->setHasStackFrame(true);
1531
1532 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1533 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1534 if (!LRSpilled && CS1Spilled) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001535 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001536 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001537 SmallVectorImpl<unsigned>::iterator LRPos;
1538 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1539 (unsigned)ARM::LR);
1540 if (LRPos != UnspilledCS1GPRs.end())
1541 UnspilledCS1GPRs.erase(LRPos);
1542
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001543 ForceLRSpill = false;
1544 ExtraCSSpill = true;
1545 }
1546
1547 if (hasFP(MF)) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001548 MRI.setPhysRegUsed(FramePtr);
Joerg Sonnenberger818e7252014-05-06 20:43:01 +00001549 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1550 FramePtr);
1551 if (FPPos != UnspilledCS1GPRs.end())
1552 UnspilledCS1GPRs.erase(FPPos);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001553 NumGPRSpills++;
1554 }
1555
1556 // If stack and double are 8-byte aligned and we are spilling an odd number
1557 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1558 // the integer and double callee save areas.
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001559 unsigned TargetAlign = getStackAlignment();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001560 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1561 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1562 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1563 unsigned Reg = UnspilledCS1GPRs[i];
1564 // Don't spill high register if the function is thumb1
1565 if (!AFI->isThumb1OnlyFunction() ||
1566 isARMLowRegister(Reg) || Reg == ARM::LR) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001567 MRI.setPhysRegUsed(Reg);
1568 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001569 ExtraCSSpill = true;
1570 break;
1571 }
1572 }
1573 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1574 unsigned Reg = UnspilledCS2GPRs.front();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001575 MRI.setPhysRegUsed(Reg);
1576 if (!MRI.isReserved(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001577 ExtraCSSpill = true;
1578 }
1579 }
1580
1581 // Estimate if we might need to scavenge a register at some point in order
1582 // to materialize a stack offset. If so, either spill one additional
1583 // callee-saved register or reserve a special spill slot to facilitate
1584 // register scavenging. Thumb1 needs a spill slot for stack pointer
1585 // adjustments also, even when the frame itself is small.
1586 if (BigStack && !ExtraCSSpill) {
1587 // If any non-reserved CS register isn't spilled, just spill one or two
1588 // extra. That should take care of it!
1589 unsigned NumExtras = TargetAlign / 4;
1590 SmallVector<unsigned, 2> Extras;
1591 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1592 unsigned Reg = UnspilledCS1GPRs.back();
1593 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001594 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001595 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1596 Reg == ARM::LR)) {
1597 Extras.push_back(Reg);
1598 NumExtras--;
1599 }
1600 }
1601 // For non-Thumb1 functions, also check for hi-reg CS registers
1602 if (!AFI->isThumb1OnlyFunction()) {
1603 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1604 unsigned Reg = UnspilledCS2GPRs.back();
1605 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001606 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001607 Extras.push_back(Reg);
1608 NumExtras--;
1609 }
1610 }
1611 }
1612 if (Extras.size() && NumExtras == 0) {
1613 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001614 MRI.setPhysRegUsed(Extras[i]);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001615 }
1616 } else if (!AFI->isThumb1OnlyFunction()) {
1617 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1618 // closest to SP or frame pointer.
Craig Topperc7242e02012-04-20 07:30:17 +00001619 const TargetRegisterClass *RC = &ARM::GPRRegClass;
Hal Finkel9e331c22013-03-22 23:32:27 +00001620 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001621 RC->getAlignment(),
1622 false));
1623 }
1624 }
1625 }
1626
1627 if (ForceLRSpill) {
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001628 MRI.setPhysRegUsed(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001629 AFI->setLRIsSpilledForFarJump(true);
1630 }
1631}
Eli Bendersky8da87162013-02-21 20:05:00 +00001632
1633
1634void ARMFrameLowering::
1635eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1636 MachineBasicBlock::iterator I) const {
1637 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001638 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001639 if (!hasReservedCallFrame(MF)) {
1640 // If we have alloca, convert as follows:
1641 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1642 // ADJCALLSTACKUP -> add, sp, sp, amount
1643 MachineInstr *Old = I;
1644 DebugLoc dl = Old->getDebugLoc();
1645 unsigned Amount = Old->getOperand(0).getImm();
1646 if (Amount != 0) {
1647 // We need to keep the stack aligned properly. To do this, we round the
1648 // amount of space needed for the outgoing arguments up to the next
1649 // alignment boundary.
1650 unsigned Align = getStackAlignment();
1651 Amount = (Amount+Align-1)/Align*Align;
1652
1653 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1654 assert(!AFI->isThumb1OnlyFunction() &&
1655 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1656 bool isARM = !AFI->isThumbFunction();
1657
1658 // Replace the pseudo instruction with a new instruction...
1659 unsigned Opc = Old->getOpcode();
1660 int PIdx = Old->findFirstPredOperandIdx();
1661 ARMCC::CondCodes Pred = (PIdx == -1)
1662 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1663 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1664 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1665 unsigned PredReg = Old->getOperand(2).getReg();
1666 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1667 Pred, PredReg);
1668 } else {
1669 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1670 unsigned PredReg = Old->getOperand(3).getReg();
1671 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1672 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1673 Pred, PredReg);
1674 }
1675 }
1676 }
1677 MBB.erase(I);
1678}
1679
Oliver Stannardb14c6252014-04-02 16:10:33 +00001680/// Get the minimum constant for ARM that is greater than or equal to the
1681/// argument. In ARM, constants can have any value that can be produced by
1682/// rotating an 8-bit value to the right by an even number of bits within a
1683/// 32-bit word.
1684static uint32_t alignToARMConstant(uint32_t Value) {
1685 unsigned Shifted = 0;
1686
1687 if (Value == 0)
1688 return 0;
1689
1690 while (!(Value & 0xC0000000)) {
1691 Value = Value << 2;
1692 Shifted += 2;
1693 }
1694
1695 bool Carry = (Value & 0x00FFFFFF);
1696 Value = ((Value & 0xFF000000) >> 24) + Carry;
1697
1698 if (Value & 0x0000100)
1699 Value = Value & 0x000001FC;
1700
1701 if (Shifted > 24)
1702 Value = Value >> (Shifted - 24);
1703 else
1704 Value = Value << (24 - Shifted);
1705
1706 return Value;
1707}
1708
1709// The stack limit in the TCB is set to this many bytes above the actual
1710// stack limit.
1711static const uint64_t kSplitStackAvailable = 256;
1712
1713// Adjust the function prologue to enable split stacks. This currently only
1714// supports android and linux.
1715//
1716// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1717// must be well defined in order to allow for consistent implementations of the
1718// __morestack helper function. The ABI is also not a normal ABI in that it
1719// doesn't follow the normal calling conventions because this allows the
1720// prologue of each function to be optimized further.
1721//
1722// Currently, the ABI looks like (when calling __morestack)
1723//
1724// * r4 holds the minimum stack size requested for this function call
1725// * r5 holds the stack size of the arguments to the function
1726// * the beginning of the function is 3 instructions after the call to
1727// __morestack
1728//
1729// Implementations of __morestack should use r4 to allocate a new stack, r5 to
1730// place the arguments on to the new stack, and the 3-instruction knowledge to
1731// jump directly to the body of the function when working on the new stack.
1732//
1733// An old (and possibly no longer compatible) implementation of __morestack for
1734// ARM can be found at [1].
1735//
1736// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1737void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1738 unsigned Opcode;
1739 unsigned CFIIndex;
1740 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1741 bool Thumb = ST->isThumb();
1742
1743 // Sadly, this currently doesn't support varargs, platforms other than
1744 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1745 if (MF.getFunction()->isVarArg())
1746 report_fatal_error("Segmented stacks do not support vararg functions.");
1747 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00001748 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00001749
1750 MachineBasicBlock &prologueMBB = MF.front();
1751 MachineFrameInfo *MFI = MF.getFrameInfo();
1752 MachineModuleInfo &MMI = MF.getMMI();
1753 MCContext &Context = MMI.getContext();
1754 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1755 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001756 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00001757 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1758 DebugLoc DL;
1759
Tim Northoverf9e798b2014-05-22 13:03:43 +00001760 uint64_t StackSize = MFI->getStackSize();
1761
1762 // Do not generate a prologue for functions with a stack of size zero
1763 if (StackSize == 0)
1764 return;
1765
Oliver Stannardb14c6252014-04-02 16:10:33 +00001766 // Use R4 and R5 as scratch registers.
1767 // We save R4 and R5 before use and restore them before leaving the function.
1768 unsigned ScratchReg0 = ARM::R4;
1769 unsigned ScratchReg1 = ARM::R5;
1770 uint64_t AlignedStackSize;
1771
1772 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1773 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1774 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1775 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1776 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1777
1778 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1779 e = prologueMBB.livein_end();
1780 i != e; ++i) {
1781 AllocMBB->addLiveIn(*i);
1782 GetMBB->addLiveIn(*i);
1783 McrMBB->addLiveIn(*i);
1784 PrevStackMBB->addLiveIn(*i);
1785 PostStackMBB->addLiveIn(*i);
1786 }
1787
1788 MF.push_front(PostStackMBB);
1789 MF.push_front(AllocMBB);
1790 MF.push_front(GetMBB);
1791 MF.push_front(McrMBB);
1792 MF.push_front(PrevStackMBB);
1793
1794 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00001795 AlignedStackSize = alignToARMConstant(StackSize);
1796
1797 // When the frame size is less than 256 we just compare the stack
1798 // boundary directly to the value of the stack pointer, per gcc.
1799 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1800
1801 // We will use two of the callee save registers as scratch registers so we
1802 // need to save those registers onto the stack.
1803 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1804 // requested and arguments for __morestack().
1805 // SR0: Scratch Register #0
1806 // SR1: Scratch Register #1
1807 // push {SR0, SR1}
1808 if (Thumb) {
1809 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1810 .addReg(ScratchReg0).addReg(ScratchReg1);
1811 } else {
1812 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1813 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1814 .addReg(ScratchReg0).addReg(ScratchReg1);
1815 }
1816
1817 // Emit the relevant DWARF information about the change in stack pointer as
1818 // well as where to find both r4 and r5 (the callee-save registers)
1819 CFIIndex =
1820 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1821 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1822 .addCFIIndex(CFIIndex);
1823 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1824 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1825 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1826 .addCFIIndex(CFIIndex);
1827 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1828 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1829 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1830 .addCFIIndex(CFIIndex);
1831
1832 // mov SR1, sp
1833 if (Thumb) {
1834 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1835 .addReg(ARM::SP));
1836 } else if (CompareStackPointer) {
1837 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1838 .addReg(ARM::SP)).addReg(0);
1839 }
1840
1841 // sub SR1, sp, #StackSize
1842 if (!CompareStackPointer && Thumb) {
1843 AddDefaultPred(
1844 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1845 .addReg(ScratchReg1).addImm(AlignedStackSize));
1846 } else if (!CompareStackPointer) {
1847 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1848 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1849 }
1850
1851 if (Thumb && ST->isThumb1Only()) {
1852 unsigned PCLabelId = ARMFI->createPICLabelUId();
1853 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Oliver Stannard92e0fc02014-04-03 08:45:16 +00001854 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00001855 MachineConstantPool *MCP = MF.getConstantPool();
1856 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1857
1858 // ldr SR0, [pc, offset(STACK_LIMIT)]
1859 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1860 .addConstantPoolIndex(CPI));
1861
1862 // ldr SR0, [SR0]
1863 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1864 .addReg(ScratchReg0).addImm(0));
1865 } else {
1866 // Get TLS base address from the coprocessor
1867 // mrc p15, #0, SR0, c13, c0, #3
1868 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1869 .addImm(15)
1870 .addImm(0)
1871 .addImm(13)
1872 .addImm(0)
1873 .addImm(3));
1874
1875 // Use the last tls slot on android and a private field of the TCP on linux.
1876 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1877 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1878
1879 // Get the stack limit from the right offset
1880 // ldr SR0, [sr0, #4 * TlsOffset]
1881 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1882 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1883 }
1884
1885 // Compare stack limit with stack size requested.
1886 // cmp SR0, SR1
1887 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1888 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1889 .addReg(ScratchReg0)
1890 .addReg(ScratchReg1));
1891
1892 // This jump is taken if StackLimit < SP - stack required.
1893 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1894 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1895 .addImm(ARMCC::LO)
1896 .addReg(ARM::CPSR);
1897
1898
1899 // Calling __morestack(StackSize, Size of stack arguments).
1900 // __morestack knows that the stack size requested is in SR0(r4)
1901 // and amount size of stack arguments is in SR1(r5).
1902
1903 // Pass first argument for the __morestack by Scratch Register #0.
1904 // The amount size of stack required
1905 if (Thumb) {
1906 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1907 ScratchReg0)).addImm(AlignedStackSize));
1908 } else {
1909 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1910 .addImm(AlignedStackSize)).addReg(0);
1911 }
1912 // Pass second argument for the __morestack by Scratch Register #1.
1913 // The amount size of stack consumed to save function arguments.
1914 if (Thumb) {
1915 AddDefaultPred(
1916 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1917 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1918 } else {
1919 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1920 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1921 .addReg(0);
1922 }
1923
1924 // push {lr} - Save return address of this function.
1925 if (Thumb) {
1926 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1927 .addReg(ARM::LR);
1928 } else {
1929 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1930 .addReg(ARM::SP, RegState::Define)
1931 .addReg(ARM::SP))
1932 .addReg(ARM::LR);
1933 }
1934
1935 // Emit the DWARF info about the change in stack as well as where to find the
1936 // previous link register
1937 CFIIndex =
1938 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1939 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1940 .addCFIIndex(CFIIndex);
1941 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1942 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1943 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1944 .addCFIIndex(CFIIndex);
1945
1946 // Call __morestack().
1947 if (Thumb) {
1948 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1949 .addExternalSymbol("__morestack");
1950 } else {
1951 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1952 .addExternalSymbol("__morestack");
1953 }
1954
1955 // pop {lr} - Restore return address of this original function.
1956 if (Thumb) {
1957 if (ST->isThumb1Only()) {
1958 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1959 .addReg(ScratchReg0);
1960 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1961 .addReg(ScratchReg0));
1962 } else {
1963 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1964 .addReg(ARM::LR, RegState::Define)
1965 .addReg(ARM::SP, RegState::Define)
1966 .addReg(ARM::SP)
1967 .addImm(4));
1968 }
1969 } else {
1970 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1971 .addReg(ARM::SP, RegState::Define)
1972 .addReg(ARM::SP))
1973 .addReg(ARM::LR);
1974 }
1975
1976 // Restore SR0 and SR1 in case of __morestack() was called.
1977 // __morestack() will skip PostStackMBB block so we need to restore
1978 // scratch registers from here.
1979 // pop {SR0, SR1}
1980 if (Thumb) {
1981 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1982 .addReg(ScratchReg0)
1983 .addReg(ScratchReg1);
1984 } else {
1985 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1986 .addReg(ARM::SP, RegState::Define)
1987 .addReg(ARM::SP))
1988 .addReg(ScratchReg0)
1989 .addReg(ScratchReg1);
1990 }
1991
1992 // Update the CFA offset now that we've popped
1993 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1994 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1995 .addCFIIndex(CFIIndex);
1996
1997 // bx lr - Return from this function.
1998 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
1999 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2000
2001 // Restore SR0 and SR1 in case of __morestack() was not called.
2002 // pop {SR0, SR1}
2003 if (Thumb) {
2004 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2005 .addReg(ScratchReg0)
2006 .addReg(ScratchReg1);
2007 } else {
2008 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2009 .addReg(ARM::SP, RegState::Define)
2010 .addReg(ARM::SP))
2011 .addReg(ScratchReg0)
2012 .addReg(ScratchReg1);
2013 }
2014
2015 // Update the CFA offset now that we've popped
2016 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2017 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2018 .addCFIIndex(CFIIndex);
2019
2020 // Tell debuggers that r4 and r5 are now the same as they were in the
2021 // previous function, that they're the "Same Value".
2022 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2023 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2024 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2025 .addCFIIndex(CFIIndex);
2026 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2027 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2028 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2029 .addCFIIndex(CFIIndex);
2030
2031 // Organizing MBB lists
2032 PostStackMBB->addSuccessor(&prologueMBB);
2033
2034 AllocMBB->addSuccessor(PostStackMBB);
2035
2036 GetMBB->addSuccessor(PostStackMBB);
2037 GetMBB->addSuccessor(AllocMBB);
2038
2039 McrMBB->addSuccessor(GetMBB);
2040
2041 PrevStackMBB->addSuccessor(McrMBB);
2042
2043#ifdef XDEBUG
2044 MF.verify();
2045#endif
2046}