blob: f438469acb2b62180c71a02bedd0c8f2c45e7002 [file] [log] [blame]
Eugene Zelenko076468c2017-09-20 21:35:51 +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"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000019#include "ARMSubtarget.h"
Evan Chenga20cde32011-07-20 23:34:39 +000020#include "MCTargetDesc/ARMAddressingModes.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000021#include "MCTargetDesc/ARMBaseInfo.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000022#include "Utils/ARMBaseInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000023#include "llvm/ADT/BitVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/SmallVector.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000027#include "llvm/CodeGen/MachineBasicBlock.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000031#include "llvm/CodeGen/MachineInstr.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000033#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000034#include "llvm/CodeGen/MachineOperand.h"
Evan Chengeb56dca2010-11-22 18:12:04 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +000036#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000037#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetOpcodes.h"
39#include "llvm/CodeGen/TargetRegisterInfo.h"
40#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000041#include "llvm/IR/Attributes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/CallingConv.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000043#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Artyom Skrobovf6830f42014-02-14 17:19:07 +000045#include "llvm/MC/MCContext.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000046#include "llvm/MC/MCDwarf.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000047#include "llvm/MC/MCInstrDesc.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000048#include "llvm/MC/MCRegisterInfo.h"
49#include "llvm/Support/CodeGen.h"
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000050#include "llvm/Support/CommandLine.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000051#include "llvm/Support/Compiler.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000056#include "llvm/Target/TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include "llvm/Target/TargetOptions.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000058#include <algorithm>
59#include <cassert>
60#include <cstddef>
61#include <cstdint>
62#include <iterator>
63#include <utility>
64#include <vector>
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000065
Reid Klecknerbdfc05f2016-10-11 21:14:03 +000066#define DEBUG_TYPE "arm-frame-lowering"
67
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000068using namespace llvm;
69
Benjamin Kramer9fceb902012-02-24 22:09:25 +000070static cl::opt<bool>
Jakob Stoklund Olesen68a922c2012-01-06 22:19:37 +000071SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +000072 cl::desc("Align ARM NEON spills in prolog and epilog"));
73
74static MachineBasicBlock::iterator
75skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
76 unsigned NumAlignedDPRCS2Regs);
77
Eric Christopher45fb7b62014-06-26 19:29:59 +000078ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
79 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
80 STI(sti) {}
81
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000082bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
83 // iOS always has a FP for backtracking, force other targets to keep their FP
84 // when doing FastISel. The emitted code is currently superior, and in cases
85 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
86 return TargetFrameLowering::noFramePointerElim(MF) ||
87 MF.getSubtarget<ARMSubtarget>().useFastISel();
88}
89
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000090/// hasFP - Return true if the specified function should have a dedicated frame
91/// pointer register. This is true if the function has variable sized allocas
92/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000093bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +000094 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Oliver Stannard9aa6f012016-08-23 09:19:22 +000095 const MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000096
Oliver Stannard9aa6f012016-08-23 09:19:22 +000097 // ABI-required frame pointer.
98 if (MF.getTarget().Options.DisableFramePointerElim(MF))
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000099 return true;
100
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000101 // Frame pointer required for use within this function.
102 return (RegInfo->needsStackRealignment(MF) ||
Matthias Braun941a7052016-07-28 18:40:00 +0000103 MFI.hasVarSizedObjects() ||
104 MFI.isFrameAddressTaken());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000105}
106
Bob Wilson657f2272011-01-13 21:10:12 +0000107/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
108/// not required, we reserve argument space for call sites in the function
109/// immediately on entry to the current function. This eliminates the need for
110/// add/sub sp brackets around call sites. Returns true if the call frame is
111/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000112bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000113 const MachineFrameInfo &MFI = MF.getFrameInfo();
114 unsigned CFSize = MFI.getMaxCallFrameSize();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000115 // It's not always a good idea to include the call frame as part of the
116 // stack frame. ARM (especially Thumb) has small immediate offset to
117 // address the stack frame. So a large call frame can cause poor codegen
118 // and may even makes it impossible to scavenge a register.
119 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
120 return false;
121
Matthias Braun941a7052016-07-28 18:40:00 +0000122 return !MFI.hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000123}
124
Bob Wilson657f2272011-01-13 21:10:12 +0000125/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
126/// call frame pseudos can be simplified. Unlike most targets, having a FP
127/// is not sufficient here since we still may reference some objects via SP
128/// even when FP is available in Thumb2 mode.
129bool
130ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000131 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000132}
133
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000134static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000135 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000136 // Integer spill area is handled with "pop".
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000137 if (isPopOpcode(MI.getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000138 // The first two operands are predicates. The last two are
139 // imp-def and imp-use of SP. Check everything in between.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000140 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
141 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
Eric Christopherb006fc92010-11-18 19:40:05 +0000142 return false;
143 return true;
144 }
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000145 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
146 MI.getOpcode() == ARM::LDR_POST_REG ||
147 MI.getOpcode() == ARM::t2LDR_POST) &&
148 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
149 MI.getOperand(1).getReg() == ARM::SP)
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000150 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000151
152 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000153}
154
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000155static void emitRegPlusImmediate(
156 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
157 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
158 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
159 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000160 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000161 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000162 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000163 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000164 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000165 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000166}
167
Tim Northoverc9432eb2013-11-04 23:04:15 +0000168static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000169 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
Tim Northoverc9432eb2013-11-04 23:04:15 +0000170 const ARMBaseInstrInfo &TII, int NumBytes,
171 unsigned MIFlags = MachineInstr::NoFlags,
172 ARMCC::CondCodes Pred = ARMCC::AL,
173 unsigned PredReg = 0) {
174 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
175 MIFlags, Pred, PredReg);
176}
177
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000178static int sizeOfSPAdjustment(const MachineInstr &MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000179 int RegSize;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000180 switch (MI.getOpcode()) {
Tim Northover603d3162014-11-14 22:45:33 +0000181 case ARM::VSTMDDB_UPD:
182 RegSize = 8;
183 break;
184 case ARM::STMDB_UPD:
185 case ARM::t2STMDB_UPD:
186 RegSize = 4;
187 break;
188 case ARM::t2STR_PRE:
189 case ARM::STR_PRE_IMM:
190 return 4;
191 default:
192 llvm_unreachable("Unknown push or pop like instruction");
193 }
194
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000195 int count = 0;
196 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
197 // pred) so the list starts at 4.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000198 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000199 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000200 return count;
201}
202
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000203static bool WindowsRequiresStackProbe(const MachineFunction &MF,
204 size_t StackSizeInBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +0000205 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000206 const Function &F = MF.getFunction();
Matthias Braun941a7052016-07-28 18:40:00 +0000207 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
Matthias Braunf1caa282017-12-15 22:22:58 +0000208 if (F.hasFnAttribute("stack-probe-size"))
209 F.getFnAttribute("stack-probe-size")
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000210 .getValueAsString()
211 .getAsInteger(0, StackProbeSize);
Hans Wennborg89c35fc2018-02-23 13:46:25 +0000212 return (StackSizeInBytes >= StackProbeSize) &&
213 !F.hasFnAttribute("no-stack-arg-probe");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000214}
215
Tim Northover603d3162014-11-14 22:45:33 +0000216namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000217
Tim Northover603d3162014-11-14 22:45:33 +0000218struct StackAdjustingInsts {
219 struct InstInfo {
220 MachineBasicBlock::iterator I;
221 unsigned SPAdjust;
222 bool BeforeFPSet;
223 };
224
225 SmallVector<InstInfo, 4> Insts;
226
227 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
228 bool BeforeFPSet = false) {
229 InstInfo Info = {I, SPAdjust, BeforeFPSet};
230 Insts.push_back(Info);
231 }
232
233 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000234 auto Info =
235 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
Tim Northover603d3162014-11-14 22:45:33 +0000236 assert(Info != Insts.end() && "invalid sp adjusting instruction");
237 Info->SPAdjust += ExtraBytes;
238 }
239
Matthias Braunf23ef432016-11-30 23:48:42 +0000240 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
241 const ARMBaseInstrInfo &TII, bool HasFP) {
242 MachineFunction &MF = *MBB.getParent();
Tim Northover603d3162014-11-14 22:45:33 +0000243 unsigned CFAOffset = 0;
244 for (auto &Info : Insts) {
245 if (HasFP && !Info.BeforeFPSet)
246 return;
247
248 CFAOffset -= Info.SPAdjust;
Matthias Braunf23ef432016-11-30 23:48:42 +0000249 unsigned CFIIndex = MF.addFrameInst(
Tim Northover603d3162014-11-14 22:45:33 +0000250 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
251 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000252 TII.get(TargetOpcode::CFI_INSTRUCTION))
253 .addCFIIndex(CFIIndex)
254 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000255 }
256 }
257};
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000258
259} // end anonymous namespace
Tim Northover603d3162014-11-14 22:45:33 +0000260
Kristof Beyls933de7a2015-01-08 15:09:14 +0000261/// Emit an instruction sequence that will align the address in
262/// register Reg by zero-ing out the lower bits. For versions of the
263/// architecture that support Neon, this must be done in a single
264/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
265/// single instruction. That function only gets called when optimizing
266/// spilling of D registers on a core with the Neon instruction set
267/// present.
268static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
269 const TargetInstrInfo &TII,
270 MachineBasicBlock &MBB,
271 MachineBasicBlock::iterator MBBI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000272 const DebugLoc &DL, const unsigned Reg,
Kristof Beyls933de7a2015-01-08 15:09:14 +0000273 const unsigned Alignment,
274 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000275 const ARMSubtarget &AST =
276 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000277 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
278 const unsigned AlignMask = Alignment - 1;
279 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
280 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
281 if (!AFI->isThumbFunction()) {
282 // if the BFC instruction is available, use that to zero the lower
283 // bits:
284 // bfc Reg, #0, log2(Alignment)
285 // otherwise use BIC, if the mask to zero the required number of bits
286 // can be encoded in the bic immediate field
287 // bic Reg, Reg, Alignment-1
288 // otherwise, emit
289 // lsr Reg, Reg, log2(Alignment)
290 // lsl Reg, Reg, log2(Alignment)
291 if (CanUseBFC) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000292 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
293 .addReg(Reg, RegState::Kill)
294 .addImm(~AlignMask)
295 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000296 } else if (AlignMask <= 255) {
Diana Picus8a73f552017-01-13 10:18:01 +0000297 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
298 .addReg(Reg, RegState::Kill)
299 .addImm(AlignMask)
300 .add(predOps(ARMCC::AL))
301 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000302 } else {
303 assert(!MustBeSingleInstruction &&
304 "Shouldn't call emitAligningInstructions demanding a single "
305 "instruction to be emitted for large stack alignment for a target "
306 "without BFC.");
Diana Picus8a73f552017-01-13 10:18:01 +0000307 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
308 .addReg(Reg, RegState::Kill)
309 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
310 .add(predOps(ARMCC::AL))
311 .add(condCodeOp());
312 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
313 .addReg(Reg, RegState::Kill)
314 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
315 .add(predOps(ARMCC::AL))
316 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000317 }
318 } else {
319 // Since this is only reached for Thumb-2 targets, the BFC instruction
320 // should always be available.
321 assert(CanUseBFC);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000322 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
323 .addReg(Reg, RegState::Kill)
324 .addImm(~AlignMask)
325 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000326 }
327}
328
Matthias Braun8aaa3682017-04-19 21:11:44 +0000329/// We need the offset of the frame pointer relative to other MachineFrameInfo
330/// offsets which are encoded relative to SP at function begin.
331/// See also emitPrologue() for how the FP is set up.
332/// Unfortunately we cannot determine this value in determineCalleeSaves() yet
333/// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
334/// this to produce a conservative estimate that we check in an assert() later.
335static int getMaxFPOffset(const Function &F, const ARMFunctionInfo &AFI) {
336 // This is a conservative estimation: Assume the frame pointer being r7 and
337 // pc("r15") up to r8 getting spilled before (= 8 registers).
338 return -AFI.getArgRegsSaveSize() - (8 * 4);
339}
340
Quentin Colombet61b305e2015-05-05 17:38:16 +0000341void ARMFrameLowering::emitPrologue(MachineFunction &MF,
342 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000343 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000344 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000345 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000346 MachineModuleInfo &MMI = MF.getMMI();
347 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000348 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000349 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000350 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
351 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000352 assert(!AFI->isThumb1OnlyFunction() &&
353 "This emitPrologue does not support Thumb1!");
354 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000355 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover775aaeb2015-11-05 21:54:58 +0000356 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000357 unsigned NumBytes = MFI.getStackSize();
358 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000359
360 // Debug location must be unknown since the first debug location is used
361 // to determine the end of the prologue.
362 DebugLoc dl;
363
364 unsigned FramePtr = RegInfo->getFrameRegister(MF);
365
366 // Determine the sizes of each callee-save spill areas and record which frame
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000367 // belongs to which callee-save spill areas.
368 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
369 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000370 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000371
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000372 // All calls are tail calls in GHC calling conv, and functions have no
373 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000374 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000375 return;
376
Tim Northover603d3162014-11-14 22:45:33 +0000377 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000378 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000379
Oliver Stannardd55e1152014-03-05 15:25:27 +0000380 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000381 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000382 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000383 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000384 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000385 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000386
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000387 if (!AFI->hasStackFrame() &&
388 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000389 if (NumBytes - ArgRegsSaveSize != 0) {
390 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000391 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000392 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
393 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000394 }
Matthias Braunf23ef432016-11-30 23:48:42 +0000395 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000396 return;
397 }
398
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000399 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000400 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
401 unsigned Reg = CSI[i].getReg();
402 int FI = CSI[i].getFrameIdx();
403 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000404 case ARM::R8:
405 case ARM::R9:
406 case ARM::R10:
407 case ARM::R11:
408 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000409 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000410 GPRCS2Size += 4;
411 break;
412 }
Justin Bognerb03fd122016-08-17 05:10:15 +0000413 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +0000414 case ARM::R0:
415 case ARM::R1:
416 case ARM::R2:
417 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000418 case ARM::R4:
419 case ARM::R5:
420 case ARM::R6:
421 case ARM::R7:
422 case ARM::LR:
423 if (Reg == FramePtr)
424 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000425 GPRCS1Size += 4;
426 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000427 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000428 // This is a DPR. Exclude the aligned DPRCS2 spills.
429 if (Reg == ARM::D8)
430 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000431 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000432 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000433 }
434 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000435
Eric Christopherb006fc92010-11-18 19:40:05 +0000436 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000437 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
438 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000439 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000440 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
441 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000442
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000443 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000444 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
445 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
446 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
447 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
448 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000449 int FramePtrOffsetInPush = 0;
450 if (HasFP) {
Matthias Braun8aaa3682017-04-19 21:11:44 +0000451 int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
Matthias Braunf1caa282017-12-15 22:22:58 +0000452 assert(getMaxFPOffset(MF.getFunction(), *AFI) <= FPOffset &&
Matthias Braun8aaa3682017-04-19 21:11:44 +0000453 "Max FP estimation is wrong");
454 FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize;
Matthias Braun941a7052016-07-28 18:40:00 +0000455 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000456 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000457 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000458 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
459 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
460 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
461
Tim Northoverc9432eb2013-11-04 23:04:15 +0000462 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000463 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000464 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000465 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
466 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000467
Tim Northover228c9432014-11-05 00:27:13 +0000468 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
469 // .cfi_offset operations will reflect that.
470 if (DPRGapSize) {
471 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Duncan P. N. Exon Smithec083b52016-08-17 00:53:04 +0000472 if (LastPush != MBB.end() &&
473 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
Tim Northover603d3162014-11-14 22:45:33 +0000474 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
475 else {
Tim Northover228c9432014-11-05 00:27:13 +0000476 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
477 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000478 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
479 }
Tim Northover228c9432014-11-05 00:27:13 +0000480 }
481
Eric Christopherb006fc92010-11-18 19:40:05 +0000482 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000483 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000484 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000485 // instructions in the prologue.
Matthias Braun5d01e702017-11-28 01:17:52 +0000486 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000487 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000488 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000489 }
Evan Cheng70d29632011-02-25 00:24:46 +0000490 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000491
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000492 // Move past the aligned DPRCS2 area.
493 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
494 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
495 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
496 // leaves the stack pointer pointing to the DPRCS2 area.
497 //
498 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
Matthias Braun941a7052016-07-28 18:40:00 +0000499 NumBytes += MFI.getObjectOffset(D8SpillFI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000500 } else
501 NumBytes = DPRCSOffset;
502
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000503 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
504 uint32_t NumWords = NumBytes >> 2;
505
506 if (NumWords < 65536)
Diana Picus4f8c3e12017-01-13 09:37:56 +0000507 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
508 .addImm(NumWords)
509 .setMIFlags(MachineInstr::FrameSetup)
510 .add(predOps(ARMCC::AL));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000511 else
512 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000513 .addImm(NumWords)
514 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000515
516 switch (TM.getCodeModel()) {
517 case CodeModel::Small:
518 case CodeModel::Medium:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000519 case CodeModel::Kernel:
520 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000521 .add(predOps(ARMCC::AL))
522 .addExternalSymbol("__chkstk")
523 .addReg(ARM::R4, RegState::Implicit)
524 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000525 break;
526 case CodeModel::Large:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000527 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000528 .addExternalSymbol("__chkstk")
529 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000530
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000531 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000532 .add(predOps(ARMCC::AL))
533 .addReg(ARM::R12, RegState::Kill)
534 .addReg(ARM::R4, RegState::Implicit)
535 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000536 break;
537 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000538
Diana Picus8a73f552017-01-13 10:18:01 +0000539 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
540 .addReg(ARM::SP, RegState::Kill)
541 .addReg(ARM::R4, RegState::Kill)
542 .setMIFlags(MachineInstr::FrameSetup)
543 .add(predOps(ARMCC::AL))
544 .add(condCodeOp());
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000545 NumBytes = 0;
546 }
547
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000548 if (NumBytes) {
549 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000550 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000551 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000552 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
553 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000554 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
555 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000556 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
557 }
Tim Northover93bcc662013-11-08 17:18:07 +0000558
Evan Chengeb56dca2010-11-22 18:12:04 +0000559 if (HasFP && isARM)
560 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
561 // Note it's not safe to do this in Thumb2 mode because it would have
562 // taken two instructions:
563 // mov sp, r7
564 // sub sp, #24
565 // If an interrupt is taken between the two instructions, then sp is in
566 // an inconsistent state (pointing to the middle of callee-saved area).
567 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000568 AFI->setShouldRestoreSPFromFP(true);
569 }
570
Tim Northover603d3162014-11-14 22:45:33 +0000571 // Set FP to point to the stack slot that contains the previous FP.
572 // For iOS, FP is R7, which has now been stored in spill area 1.
573 // Otherwise, if this is not iOS, all the callee-saved registers go
574 // into spill area 1, including the FP in R11. In either case, it
575 // is in area one and the adjustment needs to take place just after
576 // that push.
577 if (HasFP) {
578 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000579 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
Tim Northover603d3162014-11-14 22:45:33 +0000580 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
581 dl, TII, FramePtr, ARM::SP,
582 PushSize + FramePtrOffsetInPush,
583 MachineInstr::FrameSetup);
584 if (FramePtrOffsetInPush + PushSize != 0) {
Matthias Braunf23ef432016-11-30 23:48:42 +0000585 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
Tim Northover603d3162014-11-14 22:45:33 +0000586 nullptr, MRI->getDwarfRegNum(FramePtr, true),
587 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
588 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000589 .addCFIIndex(CFIIndex)
590 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000591 } else {
592 unsigned CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +0000593 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
Tim Northover603d3162014-11-14 22:45:33 +0000594 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
595 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000596 .addCFIIndex(CFIIndex)
597 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000598 }
599 }
600
601 // Now that the prologue's actual instructions are finalised, we can insert
602 // the necessary DWARF cf instructions to describe the situation. Start by
603 // recording where each register ended up:
604 if (GPRCS1Size > 0) {
605 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
606 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000607 for (const auto &Entry : CSI) {
608 unsigned Reg = Entry.getReg();
609 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000610 switch (Reg) {
611 case ARM::R8:
612 case ARM::R9:
613 case ARM::R10:
614 case ARM::R11:
615 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000616 if (STI.splitFramePushPop(MF))
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000617 break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000618 LLVM_FALLTHROUGH;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000619 case ARM::R0:
620 case ARM::R1:
621 case ARM::R2:
622 case ARM::R3:
623 case ARM::R4:
624 case ARM::R5:
625 case ARM::R6:
626 case ARM::R7:
627 case ARM::LR:
Matthias Braunf23ef432016-11-30 23:48:42 +0000628 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Matthias Braun941a7052016-07-28 18:40:00 +0000629 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000630 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000631 .addCFIIndex(CFIIndex)
632 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000633 break;
634 }
635 }
636 }
637
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000638 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000639 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000640 for (const auto &Entry : CSI) {
641 unsigned Reg = Entry.getReg();
642 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000643 switch (Reg) {
644 case ARM::R8:
645 case ARM::R9:
646 case ARM::R10:
647 case ARM::R11:
648 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000649 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000650 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000651 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000652 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000653 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
654 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000655 .addCFIIndex(CFIIndex)
656 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000657 }
658 break;
659 }
660 }
661 }
662
663 if (DPRCSSize > 0) {
664 // Since vpush register list cannot have gaps, there may be multiple vpush
665 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000666 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000667 for (const auto &Entry : CSI) {
668 unsigned Reg = Entry.getReg();
669 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000670 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
671 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
672 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000673 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000674 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000675 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000676 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000677 .addCFIIndex(CFIIndex)
678 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000679 }
680 }
681 }
682
Tim Northover603d3162014-11-14 22:45:33 +0000683 // Now we can emit descriptions of where the canonical frame address was
684 // throughout the process. If we have a frame pointer, it takes over the job
685 // half-way through, so only the first few .cfi_def_cfa_offset instructions
686 // actually get emitted.
Matthias Braunf23ef432016-11-30 23:48:42 +0000687 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000688
Evan Chengeb56dca2010-11-22 18:12:04 +0000689 if (STI.isTargetELF() && hasFP(MF))
Matthias Braun941a7052016-07-28 18:40:00 +0000690 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
691 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000692
693 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
694 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000695 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000696 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
697
698 // If we need dynamic stack realignment, do it here. Be paranoid and make
699 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000700 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000701 // realigned.
702 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +0000703 unsigned MaxAlign = MFI.getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000704 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000705 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000706 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
707 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000708 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000709 // We cannot use sp as source/dest register here, thus we're using r4 to
710 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000711 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000712 // -- use emitAligningInstructions to produce best sequence to zero
713 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000714 // mov sp, r4
715 // FIXME: It will be better just to find spare register here.
Diana Picus4f8c3e12017-01-13 09:37:56 +0000716 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
717 .addReg(ARM::SP, RegState::Kill)
718 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000719 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
720 false);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000721 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
722 .addReg(ARM::R4, RegState::Kill)
723 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000724 }
725
726 AFI->setShouldRestoreSPFromFP(true);
727 }
728
729 // If we need a base pointer, set it up here. It's whatever the value
730 // of the stack pointer is at this point. Any variable size objects
731 // will be allocated after this, so we can still use the base pointer
732 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000733 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000734 if (RegInfo->hasBasePointer(MF)) {
735 if (isARM)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000736 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
737 .addReg(ARM::SP)
738 .add(predOps(ARMCC::AL))
739 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000740 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000741 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
742 .addReg(ARM::SP)
743 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000744 }
745
746 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000747 // the sp from fp. We can assume there's an FP here since hasFP already
748 // checks for hasVarSizedObjects.
Matthias Braun941a7052016-07-28 18:40:00 +0000749 if (MFI.hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000750 AFI->setShouldRestoreSPFromFP(true);
751}
752
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000753void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000754 MachineBasicBlock &MBB) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000755 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000756 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000757 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000758 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000759 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000760 assert(!AFI->isThumb1OnlyFunction() &&
761 "This emitEpilogue does not support Thumb1!");
762 bool isARM = !AFI->isThumbFunction();
763
Tim Northover8cda34f2015-03-11 18:54:22 +0000764 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000765 int NumBytes = (int)MFI.getStackSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000766 unsigned FramePtr = RegInfo->getFrameRegister(MF);
767
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000768 // All calls are tail calls in GHC calling conv, and functions have no
769 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000770 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000771 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000772
773 // First put ourselves on the first (from top) terminator instructions.
774 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
775 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000776
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000777 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000778 if (NumBytes - ArgRegsSaveSize != 0)
779 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000780 } else {
781 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000782 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000783 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000784 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000785 --MBBI;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000786 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
787 if (!isCSRestore(*MBBI, TII, CSRegs))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000788 ++MBBI;
789 }
790
791 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000792 NumBytes -= (ArgRegsSaveSize +
793 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000794 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000795 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000796 AFI->getDPRCalleeSavedAreaSize());
797
798 // Reset SP based on frame pointer only if the stack frame extends beyond
799 // frame pointer stack slot or target is ELF and the function has FP.
800 if (AFI->shouldRestoreSPFromFP()) {
801 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
802 if (NumBytes) {
803 if (isARM)
804 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
805 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000806 else {
807 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000808 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000809 // mov sp, r7
810 // sub sp, #24
811 // This is bad, if an interrupt is taken after the mov, sp is in an
812 // inconsistent state.
813 // Use the first callee-saved register as a scratch register.
Matthias Braun941a7052016-07-28 18:40:00 +0000814 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000815 "No scratch register to restore SP from FP!");
816 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000817 ARMCC::AL, 0, TII);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000818 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
819 .addReg(ARM::R4)
820 .add(predOps(ARMCC::AL));
Evan Chengeb56dca2010-11-22 18:12:04 +0000821 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000822 } else {
823 // Thumb2 or ARM.
824 if (isARM)
825 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000826 .addReg(FramePtr)
827 .add(predOps(ARMCC::AL))
828 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000829 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000830 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
831 .addReg(FramePtr)
832 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000833 }
Tim Northoverdee86042013-12-02 14:46:26 +0000834 } else if (NumBytes &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000835 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
836 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000837
Eric Christopherb006fc92010-11-18 19:40:05 +0000838 // Increment past our save areas.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000839 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
Evan Cheng70d29632011-02-25 00:24:46 +0000840 MBBI++;
841 // Since vpop register list cannot have gaps, there may be multiple vpop
842 // instructions in the epilogue.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000843 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
Evan Cheng70d29632011-02-25 00:24:46 +0000844 MBBI++;
845 }
Tim Northover228c9432014-11-05 00:27:13 +0000846 if (AFI->getDPRCalleeSavedGapSize()) {
847 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
848 "unexpected DPR alignment gap");
849 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
850 }
851
Eric Christopherb006fc92010-11-18 19:40:05 +0000852 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
853 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000854 }
855
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000856 if (ArgRegsSaveSize)
857 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000858}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000859
Bob Wilson657f2272011-01-13 21:10:12 +0000860/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
861/// debug info. It's the same as what we use for resolving the code-gen
862/// references for now. FIXME: This can go wrong when references are
863/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000864int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000865ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000866 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000867 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
868}
869
870int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000871ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000872 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000873 int SPAdj) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000874 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000875 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000876 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000877 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000878 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +0000879 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
Matthias Braun941a7052016-07-28 18:40:00 +0000880 bool isFixed = MFI.isFixedObjectIndex(FI);
Anton Korobeynikov46877782010-11-20 15:59:32 +0000881
882 FrameReg = ARM::SP;
883 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000884
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000885 // SP can move around if there are allocas. We may also lose track of SP
886 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000887 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000888
Anton Korobeynikov46877782010-11-20 15:59:32 +0000889 // When dynamically realigning the stack, use the frame pointer for
890 // parameters, and the stack/base pointer for locals.
891 if (RegInfo->needsStackRealignment(MF)) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000892 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000893 if (isFixed) {
894 FrameReg = RegInfo->getFrameRegister(MF);
895 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000896 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000897 assert(RegInfo->hasBasePointer(MF) &&
898 "VLAs and dynamic stack alignment, but missing base pointer!");
899 FrameReg = RegInfo->getBaseRegister();
900 }
901 return Offset;
902 }
903
904 // If there is a frame pointer, use it when we can.
905 if (hasFP(MF) && AFI->hasStackFrame()) {
906 // Use frame pointer to reference fixed objects. Use it for locals if
907 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000908 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000909 FrameReg = RegInfo->getFrameRegister(MF);
910 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000911 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000912 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000913 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000914 // Try to use the frame pointer if we can, else use the base pointer
915 // since it's available. This is handy for the emergency spill slot, in
916 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000917 if (FPOffset >= -255 && FPOffset < 0) {
918 FrameReg = RegInfo->getFrameRegister(MF);
919 return FPOffset;
920 }
Evan Chengc0d20042011-04-22 01:42:52 +0000921 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000922 } else if (AFI->isThumb2Function()) {
Andrew Trickf7ecc162011-08-25 17:40:54 +0000923 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000924 // ldr <rd>, [sp, #<imm8>]
925 // if at all possible to save space.
926 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
927 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000928 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000929 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Anton Korobeynikov46877782010-11-20 15:59:32 +0000930 if (FPOffset >= -255 && FPOffset < 0) {
931 FrameReg = RegInfo->getFrameRegister(MF);
932 return FPOffset;
933 }
934 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
935 // Otherwise, use SP or FP, whichever is closer to the stack slot.
936 FrameReg = RegInfo->getFrameRegister(MF);
937 return FPOffset;
938 }
939 }
940 // Use the base pointer if we have one.
941 if (RegInfo->hasBasePointer(MF))
942 FrameReg = RegInfo->getBaseRegister();
943 return Offset;
944}
945
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000946void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000947 MachineBasicBlock::iterator MI,
948 const std::vector<CalleeSavedInfo> &CSI,
949 unsigned StmOpc, unsigned StrOpc,
950 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000951 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000952 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000953 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000954 MachineFunction &MF = *MBB.getParent();
Tim Northover775aaeb2015-11-05 21:54:58 +0000955 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000956 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000957
958 DebugLoc DL;
959
Eugene Zelenko076468c2017-09-20 21:35:51 +0000960 using RegAndKill = std::pair<unsigned, bool>;
961
Tim Northover46a6f0f2016-11-14 20:28:24 +0000962 SmallVector<RegAndKill, 4> Regs;
Tim Northover775aaeb2015-11-05 21:54:58 +0000963 unsigned i = CSI.size();
Evan Cheng775ead32010-12-07 23:08:38 +0000964 while (i != 0) {
965 unsigned LastReg = 0;
966 for (; i != 0; --i) {
967 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000968 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000969
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000970 // D-registers in the aligned area DPRCS2 are NOT spilled here.
971 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
972 continue;
973
Matthias Braun0dba4e32017-05-31 01:21:30 +0000974 const MachineRegisterInfo &MRI = MF.getRegInfo();
975 bool isLiveIn = MRI.isLiveIn(Reg);
976 if (!isLiveIn && !MRI.isReserved(Reg))
Evan Cheng775ead32010-12-07 23:08:38 +0000977 MBB.addLiveIn(Reg);
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000978 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000979 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000980 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000981 if (NoGap && LastReg && LastReg != Reg-1)
982 break;
Evan Cheng775ead32010-12-07 23:08:38 +0000983 LastReg = Reg;
Matthias Braun707e02c2016-04-13 21:43:25 +0000984 // Do not set a kill flag on values that are also marked as live-in. This
985 // happens with the @llvm-returnaddress intrinsic and with arguments
986 // passed in callee saved registers.
987 // Omitting the kill flags is conservatively correct even if the live-in
988 // is not used after all.
989 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000990 }
991
Jim Grosbach5fccad82010-12-09 18:31:13 +0000992 if (Regs.empty())
993 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +0000994
Tim Northover3d38c382016-11-14 20:31:53 +0000995 std::sort(Regs.begin(), Regs.end(), [&](const RegAndKill &LHS,
996 const RegAndKill &RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +0000997 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
998 });
999
Jim Grosbach5fccad82010-12-09 18:31:13 +00001000 if (Regs.size() > 1 || StrOpc== 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001001 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1002 .addReg(ARM::SP)
1003 .setMIFlags(MIFlags)
1004 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001005 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1006 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +00001007 } else if (Regs.size() == 1) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001008 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1009 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1010 .addReg(ARM::SP)
1011 .setMIFlags(MIFlags)
1012 .addImm(-4)
1013 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001014 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001015 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001016
1017 // Put any subsequent vpush instructions before this one: they will refer to
1018 // higher register numbers so need to be pushed first in order to preserve
1019 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +00001020 if (MI != MBB.begin())
1021 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001022 }
Evan Cheng775ead32010-12-07 23:08:38 +00001023}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001024
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001025void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001026 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001027 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001028 unsigned LdmOpc, unsigned LdrOpc,
1029 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001030 bool(*Func)(unsigned, bool),
1031 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +00001032 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001033 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +00001034 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Evan Cheng775ead32010-12-07 23:08:38 +00001035 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +00001036 DebugLoc DL;
1037 bool isTailCall = false;
1038 bool isInterrupt = false;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001039 bool isTrap = false;
Quentin Colombet71a71482015-07-20 21:42:14 +00001040 if (MBB.end() != MI) {
1041 DL = MI->getDebugLoc();
1042 unsigned RetOpcode = MI->getOpcode();
1043 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1044 isInterrupt =
1045 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001046 isTrap =
1047 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1048 RetOpcode == ARM::tTRAP;
Quentin Colombet71a71482015-07-20 21:42:14 +00001049 }
Evan Cheng775ead32010-12-07 23:08:38 +00001050
1051 SmallVector<unsigned, 4> Regs;
1052 unsigned i = CSI.size();
1053 while (i != 0) {
1054 unsigned LastReg = 0;
1055 bool DeleteRet = false;
1056 for (; i != 0; --i) {
Matthias Braun51687912017-09-28 23:12:06 +00001057 CalleeSavedInfo &Info = CSI[i-1];
1058 unsigned Reg = Info.getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001059 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001060
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001061 // The aligned reloads from area DPRCS2 are not inserted here.
1062 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1063 continue;
1064
Tim Northoverd8407452013-10-01 14:33:28 +00001065 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001066 !isTrap && STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001067 if (MBB.succ_empty()) {
1068 Reg = ARM::PC;
1069 DeleteRet = true;
1070 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Matthias Braun51687912017-09-28 23:12:06 +00001071 // We 'restore' LR into PC so it is not live out of the return block:
1072 // Clear Restored bit.
1073 Info.setRestored(false);
Quentin Colombet71a71482015-07-20 21:42:14 +00001074 } else
1075 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001076 // Fold the return instruction into the LDM.
Evan Cheng775ead32010-12-07 23:08:38 +00001077 }
1078
Evan Cheng9d54ae62010-12-08 06:29:02 +00001079 // If NoGap is true, pop consecutive registers and then leave the rest
1080 // for other instructions. e.g.
1081 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1082 if (NoGap && LastReg && LastReg != Reg-1)
1083 break;
1084
Evan Cheng775ead32010-12-07 23:08:38 +00001085 LastReg = Reg;
1086 Regs.push_back(Reg);
1087 }
1088
Jim Grosbach5fccad82010-12-09 18:31:13 +00001089 if (Regs.empty())
1090 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001091
1092 std::sort(Regs.begin(), Regs.end(), [&](unsigned LHS, unsigned RHS) {
1093 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1094 });
1095
Jim Grosbach5fccad82010-12-09 18:31:13 +00001096 if (Regs.size() > 1 || LdrOpc == 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001097 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1098 .addReg(ARM::SP)
1099 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001100 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1101 MIB.addReg(Regs[i], getDefRegState(true));
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001102 if (DeleteRet) {
1103 if (MI != MBB.end()) {
1104 MIB.copyImplicitOps(*MI);
1105 MI->eraseFromParent();
1106 }
Andrew Trick6446bf72011-08-25 17:50:53 +00001107 }
Evan Cheng775ead32010-12-07 23:08:38 +00001108 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001109 } else if (Regs.size() == 1) {
1110 // If we adjusted the reg to PC from LR above, switch it back here. We
1111 // only do that for LDM.
1112 if (Regs[0] == ARM::PC)
1113 Regs[0] = ARM::LR;
1114 MachineInstrBuilder MIB =
1115 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1116 .addReg(ARM::SP, RegState::Define)
1117 .addReg(ARM::SP);
1118 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1119 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001120 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001121 MIB.addReg(0);
1122 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1123 } else
1124 MIB.addImm(4);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001125 MIB.add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001126 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001127 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001128
1129 // Put any subsequent vpop instructions after this one: they will refer to
1130 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001131 if (MI != MBB.end())
1132 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001133 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001134}
1135
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001136/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001137/// starting from d8. Also insert stack realignment code and leave the stack
1138/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001139static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1140 MachineBasicBlock::iterator MI,
1141 unsigned NumAlignedDPRCS2Regs,
1142 const std::vector<CalleeSavedInfo> &CSI,
1143 const TargetRegisterInfo *TRI) {
1144 MachineFunction &MF = *MBB.getParent();
1145 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001146 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001147 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Matthias Braun941a7052016-07-28 18:40:00 +00001148 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001149
1150 // Mark the D-register spill slots as properly aligned. Since MFI computes
1151 // stack slot layout backwards, this can actually mean that the d-reg stack
1152 // slot offsets can be wrong. The offset for d8 will always be correct.
1153 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1154 unsigned DNum = CSI[i].getReg() - ARM::D8;
Tim Northovere0ccdc62015-10-28 22:46:43 +00001155 if (DNum > NumAlignedDPRCS2Regs - 1)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001156 continue;
1157 int FI = CSI[i].getFrameIdx();
1158 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1159 // registers will be 8-byte aligned.
1160 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1161
1162 // The stack slot for D8 needs to be maximally aligned because this is
1163 // actually the point where we align the stack pointer. MachineFrameInfo
1164 // computes all offsets relative to the incoming stack pointer which is a
1165 // bit weird when realigning the stack. Any extra padding for this
1166 // over-alignment is not realized because the code inserted below adjusts
1167 // the stack pointer by numregs * 8 before aligning the stack pointer.
1168 if (DNum == 0)
1169 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1170 }
1171
1172 // Move the stack pointer to the d8 spill slot, and align it at the same
1173 // time. Leave the stack slot address in the scratch register r4.
1174 //
1175 // sub r4, sp, #numregs * 8
1176 // bic r4, r4, #align - 1
1177 // mov sp, r4
1178 //
1179 bool isThumb = AFI->isThumbFunction();
1180 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1181 AFI->setShouldRestoreSPFromFP(true);
1182
1183 // sub r4, sp, #numregs * 8
1184 // The immediate is <= 64, so it doesn't need any special encoding.
1185 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
Diana Picus8a73f552017-01-13 10:18:01 +00001186 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1187 .addReg(ARM::SP)
1188 .addImm(8 * NumAlignedDPRCS2Regs)
1189 .add(predOps(ARMCC::AL))
1190 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001191
Matthias Braun941a7052016-07-28 18:40:00 +00001192 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001193 // We must set parameter MustBeSingleInstruction to true, since
1194 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1195 // stack alignment. Luckily, this can always be done since all ARM
1196 // architecture versions that support Neon also support the BFC
1197 // instruction.
1198 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001199
1200 // mov sp, r4
1201 // The stack pointer must be adjusted before spilling anything, otherwise
1202 // the stack slots could be clobbered by an interrupt handler.
1203 // Leave r4 live, it is used below.
1204 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1205 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001206 .addReg(ARM::R4)
1207 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001208 if (!isThumb)
Diana Picus8a73f552017-01-13 10:18:01 +00001209 MIB.add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001210
1211 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1212 // r4 holds the stack slot address.
1213 unsigned NextReg = ARM::D8;
1214
1215 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1216 // The writeback is only needed when emitting two vst1.64 instructions.
1217 if (NumAlignedDPRCS2Regs >= 6) {
1218 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001219 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001220 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001221 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1222 .addReg(ARM::R4, RegState::Kill)
1223 .addImm(16)
1224 .addReg(NextReg)
1225 .addReg(SupReg, RegState::ImplicitKill)
1226 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001227 NextReg += 4;
1228 NumAlignedDPRCS2Regs -= 4;
1229 }
1230
1231 // We won't modify r4 beyond this point. It currently points to the next
1232 // register to be spilled.
1233 unsigned R4BaseReg = NextReg;
1234
1235 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1236 if (NumAlignedDPRCS2Regs >= 4) {
1237 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001238 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001239 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001240 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1241 .addReg(ARM::R4)
1242 .addImm(16)
1243 .addReg(NextReg)
1244 .addReg(SupReg, RegState::ImplicitKill)
1245 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001246 NextReg += 4;
1247 NumAlignedDPRCS2Regs -= 4;
1248 }
1249
1250 // 16-byte aligned vst1.64 with 2 d-regs.
1251 if (NumAlignedDPRCS2Regs >= 2) {
1252 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001253 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001254 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001255 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1256 .addReg(ARM::R4)
1257 .addImm(16)
1258 .addReg(SupReg)
1259 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001260 NextReg += 2;
1261 NumAlignedDPRCS2Regs -= 2;
1262 }
1263
1264 // Finally, use a vanilla vstr.64 for the odd last register.
1265 if (NumAlignedDPRCS2Regs) {
1266 MBB.addLiveIn(NextReg);
1267 // vstr.64 uses addrmode5 which has an offset scale of 4.
Diana Picus4f8c3e12017-01-13 09:37:56 +00001268 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1269 .addReg(NextReg)
1270 .addReg(ARM::R4)
1271 .addImm((NextReg - R4BaseReg) * 2)
1272 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001273 }
1274
1275 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001276 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001277}
1278
1279/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1280/// iterator to the following instruction.
1281static MachineBasicBlock::iterator
1282skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1283 unsigned NumAlignedDPRCS2Regs) {
1284 // sub r4, sp, #numregs * 8
1285 // bic r4, r4, #align - 1
1286 // mov sp, r4
1287 ++MI; ++MI; ++MI;
1288 assert(MI->mayStore() && "Expecting spill instruction");
1289
1290 // These switches all fall through.
1291 switch(NumAlignedDPRCS2Regs) {
1292 case 7:
1293 ++MI;
1294 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001295 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001296 default:
1297 ++MI;
1298 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001299 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001300 case 1:
1301 case 2:
1302 case 4:
1303 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1304 ++MI;
1305 }
1306 return MI;
1307}
1308
1309/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1310/// starting from d8. These instructions are assumed to execute while the
1311/// stack is still aligned, unlike the code inserted by emitPopInst.
1312static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1313 MachineBasicBlock::iterator MI,
1314 unsigned NumAlignedDPRCS2Regs,
1315 const std::vector<CalleeSavedInfo> &CSI,
1316 const TargetRegisterInfo *TRI) {
1317 MachineFunction &MF = *MBB.getParent();
1318 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001319 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001320 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001321
1322 // Find the frame index assigned to d8.
1323 int D8SpillFI = 0;
1324 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1325 if (CSI[i].getReg() == ARM::D8) {
1326 D8SpillFI = CSI[i].getFrameIdx();
1327 break;
1328 }
1329
1330 // Materialize the address of the d8 spill slot into the scratch register r4.
1331 // This can be fairly complicated if the stack frame is large, so just use
1332 // the normal frame index elimination mechanism to do it. This code runs as
1333 // the initial part of the epilog where the stack and base pointers haven't
1334 // been changed yet.
1335 bool isThumb = AFI->isThumbFunction();
1336 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1337
1338 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
Diana Picus8a73f552017-01-13 10:18:01 +00001339 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1340 .addFrameIndex(D8SpillFI)
1341 .addImm(0)
1342 .add(predOps(ARMCC::AL))
1343 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001344
1345 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1346 unsigned NextReg = ARM::D8;
1347
1348 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1349 if (NumAlignedDPRCS2Regs >= 6) {
1350 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001351 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001352 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1353 .addReg(ARM::R4, RegState::Define)
1354 .addReg(ARM::R4, RegState::Kill)
1355 .addImm(16)
1356 .addReg(SupReg, RegState::ImplicitDefine)
1357 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001358 NextReg += 4;
1359 NumAlignedDPRCS2Regs -= 4;
1360 }
1361
1362 // We won't modify r4 beyond this point. It currently points to the next
1363 // register to be spilled.
1364 unsigned R4BaseReg = NextReg;
1365
1366 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1367 if (NumAlignedDPRCS2Regs >= 4) {
1368 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001369 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001370 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1371 .addReg(ARM::R4)
1372 .addImm(16)
1373 .addReg(SupReg, RegState::ImplicitDefine)
1374 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001375 NextReg += 4;
1376 NumAlignedDPRCS2Regs -= 4;
1377 }
1378
1379 // 16-byte aligned vld1.64 with 2 d-regs.
1380 if (NumAlignedDPRCS2Regs >= 2) {
1381 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001382 &ARM::QPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001383 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1384 .addReg(ARM::R4)
1385 .addImm(16)
1386 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001387 NextReg += 2;
1388 NumAlignedDPRCS2Regs -= 2;
1389 }
1390
1391 // Finally, use a vanilla vldr.64 for the remaining odd register.
1392 if (NumAlignedDPRCS2Regs)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001393 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1394 .addReg(ARM::R4)
1395 .addImm(2 * (NextReg - R4BaseReg))
1396 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001397
1398 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001399 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001400}
1401
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001402bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001403 MachineBasicBlock::iterator MI,
1404 const std::vector<CalleeSavedInfo> &CSI,
1405 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001406 if (CSI.empty())
1407 return false;
1408
1409 MachineFunction &MF = *MBB.getParent();
1410 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001411
1412 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001413 unsigned PushOneOpc = AFI->isThumbFunction() ?
1414 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001415 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001416 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1417 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001418 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001419 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001420 MachineInstr::FrameSetup);
1421 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001422 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1423
1424 // The code above does not insert spill code for the aligned DPRCS2 registers.
1425 // The stack realignment code will be inserted between the push instructions
1426 // and these spills.
1427 if (NumAlignedDPRCS2Regs)
1428 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001429
1430 return true;
1431}
1432
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001433bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001434 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001435 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001436 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001437 if (CSI.empty())
1438 return false;
1439
1440 MachineFunction &MF = *MBB.getParent();
1441 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001442 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001443 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1444
1445 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1446 // registers. Do that here instead.
1447 if (NumAlignedDPRCS2Regs)
1448 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001449
1450 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001451 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001452 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001453 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1454 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001455 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001456 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001457 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001458 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001459
1460 return true;
1461}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001462
1463// FIXME: Make generic?
1464static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1465 const ARMBaseInstrInfo &TII) {
1466 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001467 for (auto &MBB : MF) {
1468 for (auto &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001469 FnSize += TII.getInstSizeInBytes(MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001470 }
1471 return FnSize;
1472}
1473
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001474/// estimateRSStackSizeLimit - Look at each instruction that references stack
1475/// frames and return the stack size limit beyond which some of these
1476/// instructions will require a scratch register during their expansion later.
1477// FIXME: Move to TII?
1478static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001479 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001480 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1481 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001482 for (auto &MBB : MF) {
1483 for (auto &MI : MBB) {
1484 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1485 if (!MI.getOperand(i).isFI())
1486 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001487
1488 // When using ADDri to get the address of a stack object, 255 is the
1489 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001490 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001491 Limit = std::min(Limit, (1U << 8) - 1);
1492 break;
1493 }
1494
1495 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001496 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001497 case ARMII::AddrMode3:
1498 case ARMII::AddrModeT2_i8:
1499 Limit = std::min(Limit, (1U << 8) - 1);
1500 break;
1501 case ARMII::AddrMode5:
1502 case ARMII::AddrModeT2_i8s4:
1503 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1504 break;
1505 case ARMII::AddrModeT2_i12:
1506 // i12 supports only positive offset so these will be converted to
1507 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1508 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1509 Limit = std::min(Limit, (1U << 8) - 1);
1510 break;
1511 case ARMII::AddrMode4:
1512 case ARMII::AddrMode6:
1513 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1514 // immediate offset for stack references.
1515 return 0;
1516 default:
1517 break;
1518 }
1519 break; // At most one FI per instruction
1520 }
1521 }
1522 }
1523
1524 return Limit;
1525}
1526
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001527// In functions that realign the stack, it can be an advantage to spill the
1528// callee-saved vector registers after realigning the stack. The vst1 and vld1
1529// instructions take alignment hints that can improve performance.
Matthias Braun02564862015-07-14 17:17:13 +00001530static void
1531checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001532 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1533 if (!SpillAlignedNEONRegs)
1534 return;
1535
1536 // Naked functions don't spill callee-saved registers.
Matthias Braunf1caa282017-12-15 22:22:58 +00001537 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001538 return;
1539
1540 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001541 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001542 return;
1543
1544 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001545 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001546 return;
1547
1548 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001549 if (!static_cast<const ARMBaseRegisterInfo *>(
1550 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001551 return;
1552
1553 // We always spill contiguous d-registers starting from d8. Count how many
1554 // needs spilling. The register allocator will almost always use the
1555 // callee-saved registers in order, but it can happen that there are holes in
1556 // the range. Registers above the hole will be spilled to the standard DPRCS
1557 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001558 unsigned NumSpills = 0;
1559 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001560 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001561 break;
1562
1563 // Don't do this for just one d-register. It's not worth it.
1564 if (NumSpills < 2)
1565 return;
1566
1567 // Spill the first NumSpills D-registers after realigning the stack.
1568 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1569
1570 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001571 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001572}
1573
Matthias Braun02564862015-07-14 17:17:13 +00001574void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1575 BitVector &SavedRegs,
1576 RegScavenger *RS) const {
1577 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001578 // This tells PEI to spill the FP as if it is any other callee-save register
1579 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1580 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1581 // to combine multiple loads / stores.
1582 bool CanEliminateFrame = true;
1583 bool CS1Spilled = false;
1584 bool LRSpilled = false;
1585 unsigned NumGPRSpills = 0;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001586 unsigned NumFPRSpills = 0;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001587 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1588 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001589 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001590 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001591 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001592 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001593 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001594 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001595 MachineRegisterInfo &MRI = MF.getRegInfo();
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001596 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1597 (void)TRI; // Silence unused warning in non-assert builds.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001598 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1599
1600 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1601 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001602 // since it's not always possible to restore sp from fp in a single
1603 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001604 // FIXME: It will be better just to find spare register here.
1605 if (AFI->isThumb2Function() &&
Matthias Braun941a7052016-07-28 18:40:00 +00001606 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001607 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001608
Evan Cheng572756a2011-01-16 05:14:33 +00001609 if (AFI->isThumb1OnlyFunction()) {
1610 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001611 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001612 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001613
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001614 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
1615 // requires stack alignment. We don't know for sure what the stack size
1616 // will be, but for this, an estimate is good enough. If there anything
1617 // changes it, it'll be a spill, which implies we've used all the registers
1618 // and so R4 is already used, so not marking it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001619 // FIXME: It will be better just to find spare register here.
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001620 if (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF) ||
1621 MFI.estimateStackSize(MF) > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001622 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001623 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001624
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001625 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001626 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001627
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001628 // Spill the BasePtr if it's used.
1629 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001630 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001631
1632 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001633 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001634 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001635 for (unsigned i = 0; CSRegs[i]; ++i) {
1636 unsigned Reg = CSRegs[i];
1637 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001638 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001639 Spilled = true;
1640 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001641 }
1642
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001643 if (!ARM::GPRRegClass.contains(Reg)) {
1644 if (Spilled) {
1645 if (ARM::SPRRegClass.contains(Reg))
1646 NumFPRSpills++;
1647 else if (ARM::DPRRegClass.contains(Reg))
1648 NumFPRSpills += 2;
1649 else if (ARM::QPRRegClass.contains(Reg))
1650 NumFPRSpills += 4;
1651 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001652 continue;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001653 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001654
1655 if (Spilled) {
1656 NumGPRSpills++;
1657
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001658 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001659 if (Reg == ARM::LR)
1660 LRSpilled = true;
1661 CS1Spilled = true;
1662 continue;
1663 }
1664
1665 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1666 switch (Reg) {
1667 case ARM::LR:
1668 LRSpilled = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00001669 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +00001670 case ARM::R0: case ARM::R1:
1671 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001672 case ARM::R4: case ARM::R5:
1673 case ARM::R6: case ARM::R7:
1674 CS1Spilled = true;
1675 break;
1676 default:
1677 break;
1678 }
1679 } else {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001680 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001681 UnspilledCS1GPRs.push_back(Reg);
1682 continue;
1683 }
1684
1685 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001686 case ARM::R0: case ARM::R1:
1687 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001688 case ARM::R4: case ARM::R5:
1689 case ARM::R6: case ARM::R7:
1690 case ARM::LR:
1691 UnspilledCS1GPRs.push_back(Reg);
1692 break;
1693 default:
1694 UnspilledCS2GPRs.push_back(Reg);
1695 break;
1696 }
1697 }
1698 }
1699
1700 bool ForceLRSpill = false;
1701 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1702 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1703 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1704 // use of BL to implement far jump. If it turns out that it's not needed
1705 // then the branch fix up path will undo it.
1706 if (FnSize >= (1 << 11)) {
1707 CanEliminateFrame = false;
1708 ForceLRSpill = true;
1709 }
1710 }
1711
1712 // If any of the stack slot references may be out of range of an immediate
1713 // offset, make sure a register (or a spill slot) is available for the
1714 // register scavenger. Note that if we're indexing off the frame pointer, the
1715 // effective stack size is 4 bytes larger since the FP points to the stack
1716 // slot of the previous FP. Also, if we have variable sized objects in the
1717 // function, stack slot references will often be negative, and some of
1718 // our instructions are positive-offset only, so conservatively consider
1719 // that case to want a spill slot (or register) as well. Similarly, if
1720 // the function adjusts the stack pointer during execution and the
1721 // adjustments aren't already part of our stack size estimate, our offset
1722 // calculations may be off, so be conservative.
1723 // FIXME: We could add logic to be more precise about negative offsets
1724 // and which instructions will need a scratch register for them. Is it
1725 // worth the effort and added fragility?
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001726 unsigned EstimatedStackSize =
Matthias Braun941a7052016-07-28 18:40:00 +00001727 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001728
1729 // Determine biggest (positive) SP offset in MachineFrameInfo.
1730 int MaxFixedOffset = 0;
1731 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1732 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1733 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1734 }
1735
Matthias Braun44047422017-04-05 16:58:41 +00001736 bool HasFP = hasFP(MF);
1737 if (HasFP) {
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001738 if (AFI->hasStackFrame())
1739 EstimatedStackSize += 4;
1740 } else {
1741 // If FP is not used, SP will be used to access arguments, so count the
1742 // size of arguments into the estimation.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001743 EstimatedStackSize += MaxFixedOffset;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001744 }
1745 EstimatedStackSize += 16; // For possible paddings.
1746
Matthias Braun8aaa3682017-04-19 21:11:44 +00001747 unsigned EstimatedRSStackSizeLimit = estimateRSStackSizeLimit(MF, this);
Matthias Braunf1caa282017-12-15 22:22:58 +00001748 int MaxFPOffset = getMaxFPOffset(MF.getFunction(), *AFI);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001749 bool BigFrameOffsets = EstimatedStackSize >= EstimatedRSStackSizeLimit ||
1750 MFI.hasVarSizedObjects() ||
1751 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF)) ||
1752 // For large argument stacks fp relative addressed may overflow.
1753 (HasFP && (MaxFixedOffset - MaxFPOffset) >= (int)EstimatedRSStackSizeLimit);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001754 if (BigFrameOffsets ||
1755 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001756 AFI->setHasStackFrame(true);
1757
Matthias Braun44047422017-04-05 16:58:41 +00001758 if (HasFP) {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001759 SavedRegs.set(FramePtr);
1760 // If the frame pointer is required by the ABI, also spill LR so that we
1761 // emit a complete frame record.
1762 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1763 SavedRegs.set(ARM::LR);
1764 LRSpilled = true;
1765 NumGPRSpills++;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001766 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001767 if (LRPos != UnspilledCS1GPRs.end())
1768 UnspilledCS1GPRs.erase(LRPos);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001769 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001770 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001771 if (FPPos != UnspilledCS1GPRs.end())
1772 UnspilledCS1GPRs.erase(FPPos);
1773 NumGPRSpills++;
1774 if (FramePtr == ARM::R7)
1775 CS1Spilled = true;
1776 }
1777
Matthias Braunc618a462017-07-28 01:36:32 +00001778 // This is true when we inserted a spill for an unused register that can now
1779 // be used for register scavenging.
1780 bool ExtraCSSpill = false;
1781
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001782 if (AFI->isThumb1OnlyFunction()) {
1783 // For Thumb1-only targets, we need some low registers when we save and
1784 // restore the high registers (which aren't allocatable, but could be
1785 // used by inline assembly) because the push/pop instructions can not
1786 // access high registers. If necessary, we might need to push more low
1787 // registers to ensure that there is at least one free that can be used
1788 // for the saving & restoring, and preferably we should ensure that as
1789 // many as are needed are available so that fewer push/pop instructions
1790 // are required.
1791
1792 // Low registers which are not currently pushed, but could be (r4-r7).
1793 SmallVector<unsigned, 4> AvailableRegs;
1794
1795 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1796 // free.
1797 int EntryRegDeficit = 0;
1798 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1799 if (!MF.getRegInfo().isLiveIn(Reg)) {
1800 --EntryRegDeficit;
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001801 DEBUG(dbgs() << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001802 << " is unused argument register, EntryRegDeficit = "
1803 << EntryRegDeficit << "\n");
1804 }
1805 }
1806
1807 // Unused return registers can be clobbered in the epilogue for free.
1808 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
1809 DEBUG(dbgs() << AFI->getReturnRegsCount()
1810 << " return regs used, ExitRegDeficit = " << ExitRegDeficit
1811 << "\n");
1812
1813 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
1814 DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
1815
1816 // r4-r6 can be used in the prologue if they are pushed by the first push
1817 // instruction.
1818 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1819 if (SavedRegs.test(Reg)) {
1820 --RegDeficit;
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001821 DEBUG(dbgs() << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001822 << " is saved low register, RegDeficit = " << RegDeficit
1823 << "\n");
1824 } else {
1825 AvailableRegs.push_back(Reg);
1826 DEBUG(dbgs()
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001827 << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001828 << " is non-saved low register, adding to AvailableRegs\n");
1829 }
1830 }
1831
1832 // r7 can be used if it is not being used as the frame pointer.
Matthias Braun44047422017-04-05 16:58:41 +00001833 if (!HasFP) {
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001834 if (SavedRegs.test(ARM::R7)) {
1835 --RegDeficit;
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001836 DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001837 << RegDeficit << "\n");
1838 } else {
1839 AvailableRegs.push_back(ARM::R7);
1840 DEBUG(dbgs()
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001841 << "%r7 is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001842 }
1843 }
1844
1845 // Each of r8-r11 needs to be copied to a low register, then pushed.
1846 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1847 if (SavedRegs.test(Reg)) {
1848 ++RegDeficit;
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001849 DEBUG(dbgs() << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001850 << " is saved high register, RegDeficit = " << RegDeficit
1851 << "\n");
1852 }
1853 }
1854
1855 // LR can only be used by PUSH, not POP, and can't be used at all if the
1856 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1857 // are more limited at function entry than exit.
1858 if ((EntryRegDeficit > ExitRegDeficit) &&
1859 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1860 MF.getFrameInfo().isReturnAddressTaken())) {
1861 if (SavedRegs.test(ARM::LR)) {
1862 --RegDeficit;
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001863 DEBUG(dbgs() << "%lr is saved register, RegDeficit = " << RegDeficit
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001864 << "\n");
1865 } else {
1866 AvailableRegs.push_back(ARM::LR);
Francis Visoiu Mistrih9d7bb0c2017-11-28 17:15:09 +00001867 DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001868 }
1869 }
1870
1871 // If there are more high registers that need pushing than low registers
1872 // available, push some more low registers so that we can use fewer push
1873 // instructions. This might not reduce RegDeficit all the way to zero,
1874 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1875 // need saving.
1876 DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
1877 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1878 unsigned Reg = AvailableRegs.pop_back_val();
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001879 DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001880 << " to make up reg deficit\n");
1881 SavedRegs.set(Reg);
1882 NumGPRSpills++;
1883 CS1Spilled = true;
Matthias Braunc618a462017-07-28 01:36:32 +00001884 assert(!MRI.isReserved(Reg) && "Should not be reserved");
1885 if (!MRI.isPhysRegUsed(Reg))
1886 ExtraCSSpill = true;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001887 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001888 if (Reg == ARM::LR)
1889 LRSpilled = true;
1890 }
1891 DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit << "\n");
1892 }
1893
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001894 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1895 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1896 if (!LRSpilled && CS1Spilled) {
Matthias Braun02564862015-07-14 17:17:13 +00001897 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001898 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001899 SmallVectorImpl<unsigned>::iterator LRPos;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001900 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
Tim Northoverd8407452013-10-01 14:33:28 +00001901 if (LRPos != UnspilledCS1GPRs.end())
1902 UnspilledCS1GPRs.erase(LRPos);
1903
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001904 ForceLRSpill = false;
Matthias Braunc618a462017-07-28 01:36:32 +00001905 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR))
1906 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001907 }
1908
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001909 // If stack and double are 8-byte aligned and we are spilling an odd number
1910 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1911 // the integer and double callee save areas.
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001912 DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001913 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001914 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001915 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1916 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1917 unsigned Reg = UnspilledCS1GPRs[i];
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001918 // Don't spill high register if the function is thumb. In the case of
1919 // Windows on ARM, accept R11 (frame pointer)
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001920 if (!AFI->isThumbFunction() ||
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001921 (STI.isTargetWindows() && Reg == ARM::R11) ||
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001922 isARMLowRegister(Reg) || Reg == ARM::LR) {
Matthias Braun02564862015-07-14 17:17:13 +00001923 SavedRegs.set(Reg);
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001924 DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001925 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00001926 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001927 ExtraCSSpill = true;
1928 break;
1929 }
1930 }
1931 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1932 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00001933 SavedRegs.set(Reg);
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001934 DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001935 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00001936 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001937 ExtraCSSpill = true;
1938 }
1939 }
1940
1941 // Estimate if we might need to scavenge a register at some point in order
1942 // to materialize a stack offset. If so, either spill one additional
1943 // callee-saved register or reserve a special spill slot to facilitate
1944 // register scavenging. Thumb1 needs a spill slot for stack pointer
1945 // adjustments also, even when the frame itself is small.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001946 if (BigFrameOffsets && !ExtraCSSpill) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001947 // If any non-reserved CS register isn't spilled, just spill one or two
1948 // extra. That should take care of it!
1949 unsigned NumExtras = TargetAlign / 4;
1950 SmallVector<unsigned, 2> Extras;
1951 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1952 unsigned Reg = UnspilledCS1GPRs.back();
1953 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001954 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001955 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1956 Reg == ARM::LR)) {
1957 Extras.push_back(Reg);
1958 NumExtras--;
1959 }
1960 }
1961 // For non-Thumb1 functions, also check for hi-reg CS registers
1962 if (!AFI->isThumb1OnlyFunction()) {
1963 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1964 unsigned Reg = UnspilledCS2GPRs.back();
1965 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001966 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001967 Extras.push_back(Reg);
1968 NumExtras--;
1969 }
1970 }
1971 }
Matthias Braunc618a462017-07-28 01:36:32 +00001972 if (NumExtras == 0) {
1973 for (unsigned Reg : Extras) {
1974 SavedRegs.set(Reg);
1975 if (!MRI.isPhysRegUsed(Reg))
1976 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001977 }
Matthias Braunc618a462017-07-28 01:36:32 +00001978 }
1979 if (!ExtraCSSpill && !AFI->isThumb1OnlyFunction()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001980 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1981 // closest to SP or frame pointer.
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001982 assert(RS && "Register scavenging not provided");
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00001983 const TargetRegisterClass &RC = ARM::GPRRegClass;
1984 unsigned Size = TRI->getSpillSize(RC);
1985 unsigned Align = TRI->getSpillAlignment(RC);
1986 RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001987 }
1988 }
1989 }
1990
1991 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00001992 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001993 AFI->setLRIsSpilledForFarJump(true);
1994 }
1995}
Eli Bendersky8da87162013-02-21 20:05:00 +00001996
Hans Wennborge1a2e902016-03-31 18:33:38 +00001997MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
1998 MachineFunction &MF, MachineBasicBlock &MBB,
1999 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00002000 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002001 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00002002 if (!hasReservedCallFrame(MF)) {
2003 // If we have alloca, convert as follows:
2004 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
2005 // ADJCALLSTACKUP -> add, sp, sp, amount
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002006 MachineInstr &Old = *I;
2007 DebugLoc dl = Old.getDebugLoc();
Serge Pavlov5943a962017-04-19 03:12:05 +00002008 unsigned Amount = TII.getFrameSize(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002009 if (Amount != 0) {
2010 // We need to keep the stack aligned properly. To do this, we round the
2011 // amount of space needed for the outgoing arguments up to the next
2012 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00002013 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00002014
2015 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2016 assert(!AFI->isThumb1OnlyFunction() &&
2017 "This eliminateCallFramePseudoInstr does not support Thumb1!");
2018 bool isARM = !AFI->isThumbFunction();
2019
2020 // Replace the pseudo instruction with a new instruction...
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002021 unsigned Opc = Old.getOpcode();
2022 int PIdx = Old.findFirstPredOperandIdx();
2023 ARMCC::CondCodes Pred =
2024 (PIdx == -1) ? ARMCC::AL
2025 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
Serge Pavlov5943a962017-04-19 03:12:05 +00002026 unsigned PredReg = TII.getFramePred(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002027 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
Eli Bendersky8da87162013-02-21 20:05:00 +00002028 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2029 Pred, PredReg);
2030 } else {
Eli Bendersky8da87162013-02-21 20:05:00 +00002031 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2032 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2033 Pred, PredReg);
2034 }
2035 }
2036 }
Hans Wennborge1a2e902016-03-31 18:33:38 +00002037 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00002038}
2039
Oliver Stannardb14c6252014-04-02 16:10:33 +00002040/// Get the minimum constant for ARM that is greater than or equal to the
2041/// argument. In ARM, constants can have any value that can be produced by
2042/// rotating an 8-bit value to the right by an even number of bits within a
2043/// 32-bit word.
2044static uint32_t alignToARMConstant(uint32_t Value) {
2045 unsigned Shifted = 0;
2046
2047 if (Value == 0)
2048 return 0;
2049
2050 while (!(Value & 0xC0000000)) {
2051 Value = Value << 2;
2052 Shifted += 2;
2053 }
2054
2055 bool Carry = (Value & 0x00FFFFFF);
2056 Value = ((Value & 0xFF000000) >> 24) + Carry;
2057
2058 if (Value & 0x0000100)
2059 Value = Value & 0x000001FC;
2060
2061 if (Shifted > 24)
2062 Value = Value >> (Shifted - 24);
2063 else
2064 Value = Value << (24 - Shifted);
2065
2066 return Value;
2067}
2068
2069// The stack limit in the TCB is set to this many bytes above the actual
2070// stack limit.
2071static const uint64_t kSplitStackAvailable = 256;
2072
2073// Adjust the function prologue to enable split stacks. This currently only
2074// supports android and linux.
2075//
2076// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2077// must be well defined in order to allow for consistent implementations of the
2078// __morestack helper function. The ABI is also not a normal ABI in that it
2079// doesn't follow the normal calling conventions because this allows the
2080// prologue of each function to be optimized further.
2081//
2082// Currently, the ABI looks like (when calling __morestack)
2083//
2084// * r4 holds the minimum stack size requested for this function call
2085// * r5 holds the stack size of the arguments to the function
2086// * the beginning of the function is 3 instructions after the call to
2087// __morestack
2088//
2089// Implementations of __morestack should use r4 to allocate a new stack, r5 to
2090// place the arguments on to the new stack, and the 3-instruction knowledge to
2091// jump directly to the body of the function when working on the new stack.
2092//
2093// An old (and possibly no longer compatible) implementation of __morestack for
2094// ARM can be found at [1].
2095//
2096// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00002097void ARMFrameLowering::adjustForSegmentedStacks(
2098 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00002099 unsigned Opcode;
2100 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00002101 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002102 bool Thumb = ST->isThumb();
2103
2104 // Sadly, this currently doesn't support varargs, platforms other than
2105 // android/linux. Note that thumb1/thumb2 are support for android/linux.
Matthias Braunf1caa282017-12-15 22:22:58 +00002106 if (MF.getFunction().isVarArg())
Oliver Stannardb14c6252014-04-02 16:10:33 +00002107 report_fatal_error("Segmented stacks do not support vararg functions.");
2108 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00002109 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00002110
Matthias Braun941a7052016-07-28 18:40:00 +00002111 MachineFrameInfo &MFI = MF.getFrameInfo();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002112 MachineModuleInfo &MMI = MF.getMMI();
2113 MCContext &Context = MMI.getContext();
2114 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2115 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002116 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002117 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2118 DebugLoc DL;
2119
Matthias Braun941a7052016-07-28 18:40:00 +00002120 uint64_t StackSize = MFI.getStackSize();
Tim Northoverf9e798b2014-05-22 13:03:43 +00002121
2122 // Do not generate a prologue for functions with a stack of size zero
2123 if (StackSize == 0)
2124 return;
2125
Oliver Stannardb14c6252014-04-02 16:10:33 +00002126 // Use R4 and R5 as scratch registers.
2127 // We save R4 and R5 before use and restore them before leaving the function.
2128 unsigned ScratchReg0 = ARM::R4;
2129 unsigned ScratchReg1 = ARM::R5;
2130 uint64_t AlignedStackSize;
2131
2132 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2133 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2134 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2135 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2136 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2137
Quentin Colombet71a71482015-07-20 21:42:14 +00002138 // Grab everything that reaches PrologueMBB to update there liveness as well.
2139 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2140 SmallVector<MachineBasicBlock *, 2> WalkList;
2141 WalkList.push_back(&PrologueMBB);
2142
2143 do {
2144 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2145 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2146 if (BeforePrologueRegion.insert(PredBB).second)
2147 WalkList.push_back(PredBB);
2148 }
2149 } while (!WalkList.empty());
2150
2151 // The order in that list is important.
2152 // The blocks will all be inserted before PrologueMBB using that order.
2153 // Therefore the block that should appear first in the CFG should appear
2154 // first in the list.
2155 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2156 PostStackMBB};
Quentin Colombet71a71482015-07-20 21:42:14 +00002157
Craig Topper80720812015-12-01 06:13:01 +00002158 for (MachineBasicBlock *B : AddedBlocks)
2159 BeforePrologueRegion.insert(B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002160
Matthias Braund9da1622015-09-09 18:08:03 +00002161 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00002162 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00002163 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002164 }
2165
Quentin Colombet71a71482015-07-20 21:42:14 +00002166 // Remove the newly added blocks from the list, since we know
2167 // we do not have to do the following updates for them.
Craig Topper80720812015-12-01 06:13:01 +00002168 for (MachineBasicBlock *B : AddedBlocks) {
2169 BeforePrologueRegion.erase(B);
2170 MF.insert(PrologueMBB.getIterator(), B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002171 }
2172
2173 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2174 // Make sure the LiveIns are still sorted and unique.
2175 MBB->sortUniqueLiveIns();
2176 // Replace the edges to PrologueMBB by edges to the sequences
2177 // we are about to add.
2178 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2179 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00002180
2181 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00002182 AlignedStackSize = alignToARMConstant(StackSize);
2183
2184 // When the frame size is less than 256 we just compare the stack
2185 // boundary directly to the value of the stack pointer, per gcc.
2186 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2187
2188 // We will use two of the callee save registers as scratch registers so we
2189 // need to save those registers onto the stack.
2190 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2191 // requested and arguments for __morestack().
2192 // SR0: Scratch Register #0
2193 // SR1: Scratch Register #1
2194 // push {SR0, SR1}
2195 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002196 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2197 .add(predOps(ARMCC::AL))
2198 .addReg(ScratchReg0)
2199 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002200 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002201 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2202 .addReg(ARM::SP, RegState::Define)
2203 .addReg(ARM::SP)
2204 .add(predOps(ARMCC::AL))
2205 .addReg(ScratchReg0)
2206 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002207 }
2208
2209 // Emit the relevant DWARF information about the change in stack pointer as
2210 // well as where to find both r4 and r5 (the callee-save registers)
2211 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002212 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002213 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2214 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002215 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002216 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2217 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2218 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002219 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002220 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2221 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2222 .addCFIIndex(CFIIndex);
2223
2224 // mov SR1, sp
2225 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002226 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2227 .addReg(ARM::SP)
2228 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002229 } else if (CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002230 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2231 .addReg(ARM::SP)
2232 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002233 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002234 }
2235
2236 // sub SR1, sp, #StackSize
2237 if (!CompareStackPointer && Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002238 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2239 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002240 .addReg(ScratchReg1)
2241 .addImm(AlignedStackSize)
2242 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002243 } else if (!CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002244 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2245 .addReg(ARM::SP)
2246 .addImm(AlignedStackSize)
2247 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002248 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002249 }
2250
2251 if (Thumb && ST->isThumb1Only()) {
2252 unsigned PCLabelId = ARMFI->createPICLabelUId();
2253 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Matthias Braunf1caa282017-12-15 22:22:58 +00002254 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002255 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00002256 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002257
2258 // ldr SR0, [pc, offset(STACK_LIMIT)]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002259 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2260 .addConstantPoolIndex(CPI)
2261 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002262
2263 // ldr SR0, [SR0]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002264 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2265 .addReg(ScratchReg0)
2266 .addImm(0)
2267 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002268 } else {
2269 // Get TLS base address from the coprocessor
2270 // mrc p15, #0, SR0, c13, c0, #3
Diana Picus4f8c3e12017-01-13 09:37:56 +00002271 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2272 .addImm(15)
2273 .addImm(0)
2274 .addImm(13)
2275 .addImm(0)
2276 .addImm(3)
2277 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002278
2279 // Use the last tls slot on android and a private field of the TCP on linux.
2280 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2281 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2282
2283 // Get the stack limit from the right offset
2284 // ldr SR0, [sr0, #4 * TlsOffset]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002285 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2286 .addReg(ScratchReg0)
2287 .addImm(4 * TlsOffset)
2288 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002289 }
2290
2291 // Compare stack limit with stack size requested.
2292 // cmp SR0, SR1
2293 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
Diana Picus4f8c3e12017-01-13 09:37:56 +00002294 BuildMI(GetMBB, DL, TII.get(Opcode))
2295 .addReg(ScratchReg0)
2296 .addReg(ScratchReg1)
2297 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002298
2299 // This jump is taken if StackLimit < SP - stack required.
2300 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2301 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2302 .addImm(ARMCC::LO)
2303 .addReg(ARM::CPSR);
2304
2305
2306 // Calling __morestack(StackSize, Size of stack arguments).
2307 // __morestack knows that the stack size requested is in SR0(r4)
2308 // and amount size of stack arguments is in SR1(r5).
2309
2310 // Pass first argument for the __morestack by Scratch Register #0.
2311 // The amount size of stack required
2312 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002313 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2314 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002315 .addImm(AlignedStackSize)
2316 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002317 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002318 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2319 .addImm(AlignedStackSize)
2320 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002321 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002322 }
2323 // Pass second argument for the __morestack by Scratch Register #1.
2324 // The amount size of stack consumed to save function arguments.
2325 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002326 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2327 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002328 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2329 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002330 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002331 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2332 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2333 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002334 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002335 }
2336
2337 // push {lr} - Save return address of this function.
2338 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002339 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2340 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002341 .addReg(ARM::LR);
2342 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002343 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2344 .addReg(ARM::SP, RegState::Define)
2345 .addReg(ARM::SP)
2346 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002347 .addReg(ARM::LR);
2348 }
2349
2350 // Emit the DWARF info about the change in stack as well as where to find the
2351 // previous link register
2352 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002353 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002354 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2355 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002356 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002357 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2358 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2359 .addCFIIndex(CFIIndex);
2360
2361 // Call __morestack().
2362 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002363 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2364 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002365 .addExternalSymbol("__morestack");
2366 } else {
2367 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2368 .addExternalSymbol("__morestack");
2369 }
2370
2371 // pop {lr} - Restore return address of this original function.
2372 if (Thumb) {
2373 if (ST->isThumb1Only()) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002374 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2375 .add(predOps(ARMCC::AL))
2376 .addReg(ScratchReg0);
2377 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2378 .addReg(ScratchReg0)
2379 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002380 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002381 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2382 .addReg(ARM::LR, RegState::Define)
2383 .addReg(ARM::SP, RegState::Define)
2384 .addReg(ARM::SP)
2385 .addImm(4)
2386 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002387 }
2388 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002389 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2390 .addReg(ARM::SP, RegState::Define)
2391 .addReg(ARM::SP)
2392 .add(predOps(ARMCC::AL))
2393 .addReg(ARM::LR);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002394 }
2395
2396 // Restore SR0 and SR1 in case of __morestack() was called.
2397 // __morestack() will skip PostStackMBB block so we need to restore
2398 // scratch registers from here.
2399 // pop {SR0, SR1}
2400 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002401 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2402 .add(predOps(ARMCC::AL))
2403 .addReg(ScratchReg0)
2404 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002405 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002406 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2407 .addReg(ARM::SP, RegState::Define)
2408 .addReg(ARM::SP)
2409 .add(predOps(ARMCC::AL))
2410 .addReg(ScratchReg0)
2411 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002412 }
2413
2414 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002415 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002416 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2417 .addCFIIndex(CFIIndex);
2418
Joerg Sonnenberger0f76a352017-08-28 20:20:47 +00002419 // Return from this function.
2420 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002421
2422 // Restore SR0 and SR1 in case of __morestack() was not called.
2423 // pop {SR0, SR1}
2424 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002425 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2426 .add(predOps(ARMCC::AL))
2427 .addReg(ScratchReg0)
2428 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002429 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002430 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2431 .addReg(ARM::SP, RegState::Define)
2432 .addReg(ARM::SP)
2433 .add(predOps(ARMCC::AL))
2434 .addReg(ScratchReg0)
2435 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002436 }
2437
2438 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002439 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002440 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2441 .addCFIIndex(CFIIndex);
2442
2443 // Tell debuggers that r4 and r5 are now the same as they were in the
2444 // previous function, that they're the "Same Value".
Matthias Braunf23ef432016-11-30 23:48:42 +00002445 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002446 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2447 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2448 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002449 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002450 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2451 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2452 .addCFIIndex(CFIIndex);
2453
2454 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002455 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002456
2457 AllocMBB->addSuccessor(PostStackMBB);
2458
2459 GetMBB->addSuccessor(PostStackMBB);
2460 GetMBB->addSuccessor(AllocMBB);
2461
2462 McrMBB->addSuccessor(GetMBB);
2463
2464 PrevStackMBB->addSuccessor(McrMBB);
2465
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002466#ifdef EXPENSIVE_CHECKS
Oliver Stannardb14c6252014-04-02 16:10:33 +00002467 MF.verify();
2468#endif
2469}