blob: 2417166ca962149fc429675f4934228763cac98f [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
Tim Northovere25e4582018-04-07 10:57:03 +000090/// Returns true if the target can safely skip saving callee-saved registers
91/// for noreturn nounwind functions.
92bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
93 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
94 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
95 !MF.getFunction().hasFnAttribute(Attribute::UWTable));
96
97 // Frame pointer and link register are not treated as normal CSR, thus we
98 // can always skip CSR saves for nonreturning functions.
99 return true;
100}
101
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000102/// hasFP - Return true if the specified function should have a dedicated frame
103/// pointer register. This is true if the function has variable sized allocas
104/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000105bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000106 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000107 const MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000108
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000109 // ABI-required frame pointer.
110 if (MF.getTarget().Options.DisableFramePointerElim(MF))
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000111 return true;
112
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000113 // Frame pointer required for use within this function.
114 return (RegInfo->needsStackRealignment(MF) ||
Matthias Braun941a7052016-07-28 18:40:00 +0000115 MFI.hasVarSizedObjects() ||
116 MFI.isFrameAddressTaken());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000117}
118
Bob Wilson657f2272011-01-13 21:10:12 +0000119/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
120/// not required, we reserve argument space for call sites in the function
121/// immediately on entry to the current function. This eliminates the need for
122/// add/sub sp brackets around call sites. Returns true if the call frame is
123/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000124bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000125 const MachineFrameInfo &MFI = MF.getFrameInfo();
126 unsigned CFSize = MFI.getMaxCallFrameSize();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000127 // It's not always a good idea to include the call frame as part of the
128 // stack frame. ARM (especially Thumb) has small immediate offset to
129 // address the stack frame. So a large call frame can cause poor codegen
130 // and may even makes it impossible to scavenge a register.
131 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
132 return false;
133
Matthias Braun941a7052016-07-28 18:40:00 +0000134 return !MFI.hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000135}
136
Bob Wilson657f2272011-01-13 21:10:12 +0000137/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
138/// call frame pseudos can be simplified. Unlike most targets, having a FP
139/// is not sufficient here since we still may reference some objects via SP
140/// even when FP is available in Thumb2 mode.
141bool
142ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000143 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000144}
145
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000146static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000147 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000148 // Integer spill area is handled with "pop".
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000149 if (isPopOpcode(MI.getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000150 // The first two operands are predicates. The last two are
151 // imp-def and imp-use of SP. Check everything in between.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000152 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
153 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
Eric Christopherb006fc92010-11-18 19:40:05 +0000154 return false;
155 return true;
156 }
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000157 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
158 MI.getOpcode() == ARM::LDR_POST_REG ||
159 MI.getOpcode() == ARM::t2LDR_POST) &&
160 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
161 MI.getOperand(1).getReg() == ARM::SP)
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000162 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000163
164 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000165}
166
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000167static void emitRegPlusImmediate(
168 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
169 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
170 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
171 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000172 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000173 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000174 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000175 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000176 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000177 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000178}
179
Tim Northoverc9432eb2013-11-04 23:04:15 +0000180static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000181 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
Tim Northoverc9432eb2013-11-04 23:04:15 +0000182 const ARMBaseInstrInfo &TII, int NumBytes,
183 unsigned MIFlags = MachineInstr::NoFlags,
184 ARMCC::CondCodes Pred = ARMCC::AL,
185 unsigned PredReg = 0) {
186 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
187 MIFlags, Pred, PredReg);
188}
189
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000190static int sizeOfSPAdjustment(const MachineInstr &MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000191 int RegSize;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000192 switch (MI.getOpcode()) {
Tim Northover603d3162014-11-14 22:45:33 +0000193 case ARM::VSTMDDB_UPD:
194 RegSize = 8;
195 break;
196 case ARM::STMDB_UPD:
197 case ARM::t2STMDB_UPD:
198 RegSize = 4;
199 break;
200 case ARM::t2STR_PRE:
201 case ARM::STR_PRE_IMM:
202 return 4;
203 default:
204 llvm_unreachable("Unknown push or pop like instruction");
205 }
206
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000207 int count = 0;
208 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
209 // pred) so the list starts at 4.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000210 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000211 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000212 return count;
213}
214
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000215static bool WindowsRequiresStackProbe(const MachineFunction &MF,
216 size_t StackSizeInBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +0000217 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000218 const Function &F = MF.getFunction();
Matthias Braun941a7052016-07-28 18:40:00 +0000219 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
Matthias Braunf1caa282017-12-15 22:22:58 +0000220 if (F.hasFnAttribute("stack-probe-size"))
221 F.getFnAttribute("stack-probe-size")
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000222 .getValueAsString()
223 .getAsInteger(0, StackProbeSize);
Hans Wennborg89c35fc2018-02-23 13:46:25 +0000224 return (StackSizeInBytes >= StackProbeSize) &&
225 !F.hasFnAttribute("no-stack-arg-probe");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000226}
227
Tim Northover603d3162014-11-14 22:45:33 +0000228namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000229
Tim Northover603d3162014-11-14 22:45:33 +0000230struct StackAdjustingInsts {
231 struct InstInfo {
232 MachineBasicBlock::iterator I;
233 unsigned SPAdjust;
234 bool BeforeFPSet;
235 };
236
237 SmallVector<InstInfo, 4> Insts;
238
239 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
240 bool BeforeFPSet = false) {
241 InstInfo Info = {I, SPAdjust, BeforeFPSet};
242 Insts.push_back(Info);
243 }
244
245 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000246 auto Info =
247 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
Tim Northover603d3162014-11-14 22:45:33 +0000248 assert(Info != Insts.end() && "invalid sp adjusting instruction");
249 Info->SPAdjust += ExtraBytes;
250 }
251
Matthias Braunf23ef432016-11-30 23:48:42 +0000252 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
253 const ARMBaseInstrInfo &TII, bool HasFP) {
254 MachineFunction &MF = *MBB.getParent();
Tim Northover603d3162014-11-14 22:45:33 +0000255 unsigned CFAOffset = 0;
256 for (auto &Info : Insts) {
257 if (HasFP && !Info.BeforeFPSet)
258 return;
259
260 CFAOffset -= Info.SPAdjust;
Matthias Braunf23ef432016-11-30 23:48:42 +0000261 unsigned CFIIndex = MF.addFrameInst(
Tim Northover603d3162014-11-14 22:45:33 +0000262 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
263 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000264 TII.get(TargetOpcode::CFI_INSTRUCTION))
265 .addCFIIndex(CFIIndex)
266 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000267 }
268 }
269};
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000270
271} // end anonymous namespace
Tim Northover603d3162014-11-14 22:45:33 +0000272
Kristof Beyls933de7a2015-01-08 15:09:14 +0000273/// Emit an instruction sequence that will align the address in
274/// register Reg by zero-ing out the lower bits. For versions of the
275/// architecture that support Neon, this must be done in a single
276/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
277/// single instruction. That function only gets called when optimizing
278/// spilling of D registers on a core with the Neon instruction set
279/// present.
280static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
281 const TargetInstrInfo &TII,
282 MachineBasicBlock &MBB,
283 MachineBasicBlock::iterator MBBI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000284 const DebugLoc &DL, const unsigned Reg,
Kristof Beyls933de7a2015-01-08 15:09:14 +0000285 const unsigned Alignment,
286 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000287 const ARMSubtarget &AST =
288 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000289 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
290 const unsigned AlignMask = Alignment - 1;
291 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
292 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
293 if (!AFI->isThumbFunction()) {
294 // if the BFC instruction is available, use that to zero the lower
295 // bits:
296 // bfc Reg, #0, log2(Alignment)
297 // otherwise use BIC, if the mask to zero the required number of bits
298 // can be encoded in the bic immediate field
299 // bic Reg, Reg, Alignment-1
300 // otherwise, emit
301 // lsr Reg, Reg, log2(Alignment)
302 // lsl Reg, Reg, log2(Alignment)
303 if (CanUseBFC) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000304 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
305 .addReg(Reg, RegState::Kill)
306 .addImm(~AlignMask)
307 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000308 } else if (AlignMask <= 255) {
Diana Picus8a73f552017-01-13 10:18:01 +0000309 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
310 .addReg(Reg, RegState::Kill)
311 .addImm(AlignMask)
312 .add(predOps(ARMCC::AL))
313 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000314 } else {
315 assert(!MustBeSingleInstruction &&
316 "Shouldn't call emitAligningInstructions demanding a single "
317 "instruction to be emitted for large stack alignment for a target "
318 "without BFC.");
Diana Picus8a73f552017-01-13 10:18:01 +0000319 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
320 .addReg(Reg, RegState::Kill)
321 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
322 .add(predOps(ARMCC::AL))
323 .add(condCodeOp());
324 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
325 .addReg(Reg, RegState::Kill)
326 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
327 .add(predOps(ARMCC::AL))
328 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000329 }
330 } else {
331 // Since this is only reached for Thumb-2 targets, the BFC instruction
332 // should always be available.
333 assert(CanUseBFC);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000334 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
335 .addReg(Reg, RegState::Kill)
336 .addImm(~AlignMask)
337 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000338 }
339}
340
Matthias Braun8aaa3682017-04-19 21:11:44 +0000341/// We need the offset of the frame pointer relative to other MachineFrameInfo
342/// offsets which are encoded relative to SP at function begin.
343/// See also emitPrologue() for how the FP is set up.
344/// Unfortunately we cannot determine this value in determineCalleeSaves() yet
345/// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
346/// this to produce a conservative estimate that we check in an assert() later.
347static int getMaxFPOffset(const Function &F, const ARMFunctionInfo &AFI) {
348 // This is a conservative estimation: Assume the frame pointer being r7 and
349 // pc("r15") up to r8 getting spilled before (= 8 registers).
350 return -AFI.getArgRegsSaveSize() - (8 * 4);
351}
352
Quentin Colombet61b305e2015-05-05 17:38:16 +0000353void ARMFrameLowering::emitPrologue(MachineFunction &MF,
354 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000355 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000356 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000357 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000358 MachineModuleInfo &MMI = MF.getMMI();
359 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000360 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000361 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000362 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
363 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000364 assert(!AFI->isThumb1OnlyFunction() &&
365 "This emitPrologue does not support Thumb1!");
366 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000367 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover775aaeb2015-11-05 21:54:58 +0000368 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000369 unsigned NumBytes = MFI.getStackSize();
370 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000371
372 // Debug location must be unknown since the first debug location is used
373 // to determine the end of the prologue.
374 DebugLoc dl;
Fangrui Songf78650a2018-07-30 19:41:25 +0000375
Tim Northover775aaeb2015-11-05 21:54:58 +0000376 unsigned FramePtr = RegInfo->getFrameRegister(MF);
377
378 // Determine the sizes of each callee-save spill areas and record which frame
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000379 // belongs to which callee-save spill areas.
380 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
381 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000382 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000383
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000384 // All calls are tail calls in GHC calling conv, and functions have no
385 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000386 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000387 return;
388
Tim Northover603d3162014-11-14 22:45:33 +0000389 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000390 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000391
Oliver Stannardd55e1152014-03-05 15:25:27 +0000392 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000393 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000394 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000395 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000396 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000397 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000398
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000399 if (!AFI->hasStackFrame() &&
400 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000401 if (NumBytes - ArgRegsSaveSize != 0) {
402 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000403 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000404 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
405 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000406 }
Matthias Braunf23ef432016-11-30 23:48:42 +0000407 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000408 return;
409 }
410
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000411 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000412 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
413 unsigned Reg = CSI[i].getReg();
414 int FI = CSI[i].getFrameIdx();
415 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000416 case ARM::R8:
417 case ARM::R9:
418 case ARM::R10:
419 case ARM::R11:
420 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000421 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000422 GPRCS2Size += 4;
423 break;
424 }
Justin Bognerb03fd122016-08-17 05:10:15 +0000425 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +0000426 case ARM::R0:
427 case ARM::R1:
428 case ARM::R2:
429 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000430 case ARM::R4:
431 case ARM::R5:
432 case ARM::R6:
433 case ARM::R7:
434 case ARM::LR:
435 if (Reg == FramePtr)
436 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000437 GPRCS1Size += 4;
438 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000439 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000440 // This is a DPR. Exclude the aligned DPRCS2 spills.
441 if (Reg == ARM::D8)
442 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000443 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000444 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000445 }
446 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000447
Eric Christopherb006fc92010-11-18 19:40:05 +0000448 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000449 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
450 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000451 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000452 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
453 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000454
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000455 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000456 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
457 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
458 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
459 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
460 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000461 int FramePtrOffsetInPush = 0;
462 if (HasFP) {
Matthias Braun8aaa3682017-04-19 21:11:44 +0000463 int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
Matthias Braunf1caa282017-12-15 22:22:58 +0000464 assert(getMaxFPOffset(MF.getFunction(), *AFI) <= FPOffset &&
Matthias Braun8aaa3682017-04-19 21:11:44 +0000465 "Max FP estimation is wrong");
466 FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize;
Matthias Braun941a7052016-07-28 18:40:00 +0000467 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000468 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000469 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000470 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
471 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
472 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
473
Tim Northoverc9432eb2013-11-04 23:04:15 +0000474 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000475 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000476 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000477 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
478 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000479
Tim Northover228c9432014-11-05 00:27:13 +0000480 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
481 // .cfi_offset operations will reflect that.
482 if (DPRGapSize) {
483 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Duncan P. N. Exon Smithec083b52016-08-17 00:53:04 +0000484 if (LastPush != MBB.end() &&
485 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
Tim Northover603d3162014-11-14 22:45:33 +0000486 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
487 else {
Tim Northover228c9432014-11-05 00:27:13 +0000488 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
489 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000490 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
491 }
Tim Northover228c9432014-11-05 00:27:13 +0000492 }
493
Eric Christopherb006fc92010-11-18 19:40:05 +0000494 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000495 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000496 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000497 // instructions in the prologue.
Matthias Braun5d01e702017-11-28 01:17:52 +0000498 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000499 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000500 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000501 }
Evan Cheng70d29632011-02-25 00:24:46 +0000502 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000503
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000504 // Move past the aligned DPRCS2 area.
505 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
506 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
507 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
508 // leaves the stack pointer pointing to the DPRCS2 area.
509 //
510 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
Matthias Braun941a7052016-07-28 18:40:00 +0000511 NumBytes += MFI.getObjectOffset(D8SpillFI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000512 } else
513 NumBytes = DPRCSOffset;
514
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000515 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
516 uint32_t NumWords = NumBytes >> 2;
517
518 if (NumWords < 65536)
Diana Picus4f8c3e12017-01-13 09:37:56 +0000519 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
520 .addImm(NumWords)
521 .setMIFlags(MachineInstr::FrameSetup)
522 .add(predOps(ARMCC::AL));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000523 else
524 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000525 .addImm(NumWords)
526 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000527
528 switch (TM.getCodeModel()) {
David Green9dd1d452018-08-22 11:31:39 +0000529 case CodeModel::Tiny:
530 llvm_unreachable("Tiny code model not available on ARM.");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000531 case CodeModel::Small:
532 case CodeModel::Medium:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000533 case CodeModel::Kernel:
534 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000535 .add(predOps(ARMCC::AL))
536 .addExternalSymbol("__chkstk")
537 .addReg(ARM::R4, RegState::Implicit)
538 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000539 break;
540 case CodeModel::Large:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000541 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000542 .addExternalSymbol("__chkstk")
543 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000544
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000545 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000546 .add(predOps(ARMCC::AL))
547 .addReg(ARM::R12, RegState::Kill)
548 .addReg(ARM::R4, RegState::Implicit)
549 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000550 break;
551 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000552
Diana Picus8a73f552017-01-13 10:18:01 +0000553 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
554 .addReg(ARM::SP, RegState::Kill)
555 .addReg(ARM::R4, RegState::Kill)
556 .setMIFlags(MachineInstr::FrameSetup)
557 .add(predOps(ARMCC::AL))
558 .add(condCodeOp());
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000559 NumBytes = 0;
560 }
561
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000562 if (NumBytes) {
563 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000564 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000565 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000566 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
567 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000568 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
569 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000570 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
571 }
Tim Northover93bcc662013-11-08 17:18:07 +0000572
Evan Chengeb56dca2010-11-22 18:12:04 +0000573 if (HasFP && isARM)
574 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
575 // Note it's not safe to do this in Thumb2 mode because it would have
576 // taken two instructions:
577 // mov sp, r7
578 // sub sp, #24
579 // If an interrupt is taken between the two instructions, then sp is in
580 // an inconsistent state (pointing to the middle of callee-saved area).
581 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000582 AFI->setShouldRestoreSPFromFP(true);
583 }
584
Tim Northover603d3162014-11-14 22:45:33 +0000585 // Set FP to point to the stack slot that contains the previous FP.
586 // For iOS, FP is R7, which has now been stored in spill area 1.
587 // Otherwise, if this is not iOS, all the callee-saved registers go
588 // into spill area 1, including the FP in R11. In either case, it
589 // is in area one and the adjustment needs to take place just after
590 // that push.
591 if (HasFP) {
592 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000593 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
Tim Northover603d3162014-11-14 22:45:33 +0000594 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
595 dl, TII, FramePtr, ARM::SP,
596 PushSize + FramePtrOffsetInPush,
597 MachineInstr::FrameSetup);
598 if (FramePtrOffsetInPush + PushSize != 0) {
Matthias Braunf23ef432016-11-30 23:48:42 +0000599 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
Tim Northover603d3162014-11-14 22:45:33 +0000600 nullptr, MRI->getDwarfRegNum(FramePtr, true),
601 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
602 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000603 .addCFIIndex(CFIIndex)
604 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000605 } else {
606 unsigned CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +0000607 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
Tim Northover603d3162014-11-14 22:45:33 +0000608 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
609 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000610 .addCFIIndex(CFIIndex)
611 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000612 }
613 }
614
615 // Now that the prologue's actual instructions are finalised, we can insert
616 // the necessary DWARF cf instructions to describe the situation. Start by
617 // recording where each register ended up:
618 if (GPRCS1Size > 0) {
619 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
620 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000621 for (const auto &Entry : CSI) {
622 unsigned Reg = Entry.getReg();
623 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000624 switch (Reg) {
625 case ARM::R8:
626 case ARM::R9:
627 case ARM::R10:
628 case ARM::R11:
629 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000630 if (STI.splitFramePushPop(MF))
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000631 break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000632 LLVM_FALLTHROUGH;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000633 case ARM::R0:
634 case ARM::R1:
635 case ARM::R2:
636 case ARM::R3:
637 case ARM::R4:
638 case ARM::R5:
639 case ARM::R6:
640 case ARM::R7:
641 case ARM::LR:
Matthias Braunf23ef432016-11-30 23:48:42 +0000642 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Matthias Braun941a7052016-07-28 18:40:00 +0000643 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000644 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000645 .addCFIIndex(CFIIndex)
646 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000647 break;
648 }
649 }
650 }
651
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000652 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000653 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000654 for (const auto &Entry : CSI) {
655 unsigned Reg = Entry.getReg();
656 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000657 switch (Reg) {
658 case ARM::R8:
659 case ARM::R9:
660 case ARM::R10:
661 case ARM::R11:
662 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000663 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000664 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000665 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000666 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000667 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
668 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000669 .addCFIIndex(CFIIndex)
670 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000671 }
672 break;
673 }
674 }
675 }
676
677 if (DPRCSSize > 0) {
678 // Since vpush register list cannot have gaps, there may be multiple vpush
679 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000680 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000681 for (const auto &Entry : CSI) {
682 unsigned Reg = Entry.getReg();
683 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000684 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
685 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
686 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000687 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000688 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000689 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000690 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000691 .addCFIIndex(CFIIndex)
692 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000693 }
694 }
695 }
696
Tim Northover603d3162014-11-14 22:45:33 +0000697 // Now we can emit descriptions of where the canonical frame address was
698 // throughout the process. If we have a frame pointer, it takes over the job
699 // half-way through, so only the first few .cfi_def_cfa_offset instructions
700 // actually get emitted.
Matthias Braunf23ef432016-11-30 23:48:42 +0000701 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000702
Evan Chengeb56dca2010-11-22 18:12:04 +0000703 if (STI.isTargetELF() && hasFP(MF))
Matthias Braun941a7052016-07-28 18:40:00 +0000704 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
705 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000706
707 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
708 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000709 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000710 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
711
712 // If we need dynamic stack realignment, do it here. Be paranoid and make
713 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000714 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000715 // realigned.
716 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +0000717 unsigned MaxAlign = MFI.getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000718 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000719 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000720 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
721 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000722 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000723 // We cannot use sp as source/dest register here, thus we're using r4 to
724 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000725 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000726 // -- use emitAligningInstructions to produce best sequence to zero
727 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000728 // mov sp, r4
729 // FIXME: It will be better just to find spare register here.
Diana Picus4f8c3e12017-01-13 09:37:56 +0000730 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
731 .addReg(ARM::SP, RegState::Kill)
732 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000733 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
734 false);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000735 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
736 .addReg(ARM::R4, RegState::Kill)
737 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000738 }
739
740 AFI->setShouldRestoreSPFromFP(true);
741 }
742
743 // If we need a base pointer, set it up here. It's whatever the value
744 // of the stack pointer is at this point. Any variable size objects
745 // will be allocated after this, so we can still use the base pointer
746 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000747 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000748 if (RegInfo->hasBasePointer(MF)) {
749 if (isARM)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000750 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
751 .addReg(ARM::SP)
752 .add(predOps(ARMCC::AL))
753 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000754 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000755 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
756 .addReg(ARM::SP)
757 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000758 }
759
760 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000761 // the sp from fp. We can assume there's an FP here since hasFP already
762 // checks for hasVarSizedObjects.
Matthias Braun941a7052016-07-28 18:40:00 +0000763 if (MFI.hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000764 AFI->setShouldRestoreSPFromFP(true);
765}
766
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000767void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000768 MachineBasicBlock &MBB) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000769 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000770 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000771 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000772 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000773 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000774 assert(!AFI->isThumb1OnlyFunction() &&
775 "This emitEpilogue does not support Thumb1!");
776 bool isARM = !AFI->isThumbFunction();
777
Tim Northover8cda34f2015-03-11 18:54:22 +0000778 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000779 int NumBytes = (int)MFI.getStackSize();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000780 unsigned FramePtr = RegInfo->getFrameRegister(MF);
781
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000782 // All calls are tail calls in GHC calling conv, and functions have no
783 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000784 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000785 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000786
787 // First put ourselves on the first (from top) terminator instructions.
788 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
789 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000790
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000791 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000792 if (NumBytes - ArgRegsSaveSize != 0)
793 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000794 } else {
795 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000796 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000797 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000798 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000799 --MBBI;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000800 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
801 if (!isCSRestore(*MBBI, TII, CSRegs))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000802 ++MBBI;
803 }
804
805 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000806 NumBytes -= (ArgRegsSaveSize +
807 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000808 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000809 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000810 AFI->getDPRCalleeSavedAreaSize());
811
812 // Reset SP based on frame pointer only if the stack frame extends beyond
813 // frame pointer stack slot or target is ELF and the function has FP.
814 if (AFI->shouldRestoreSPFromFP()) {
815 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
816 if (NumBytes) {
817 if (isARM)
818 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
819 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000820 else {
821 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000822 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000823 // mov sp, r7
824 // sub sp, #24
825 // This is bad, if an interrupt is taken after the mov, sp is in an
826 // inconsistent state.
827 // Use the first callee-saved register as a scratch register.
Matthias Braun941a7052016-07-28 18:40:00 +0000828 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000829 "No scratch register to restore SP from FP!");
830 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000831 ARMCC::AL, 0, TII);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000832 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
833 .addReg(ARM::R4)
834 .add(predOps(ARMCC::AL));
Evan Chengeb56dca2010-11-22 18:12:04 +0000835 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000836 } else {
837 // Thumb2 or ARM.
838 if (isARM)
839 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000840 .addReg(FramePtr)
841 .add(predOps(ARMCC::AL))
842 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000843 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000844 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
845 .addReg(FramePtr)
846 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000847 }
Tim Northoverdee86042013-12-02 14:46:26 +0000848 } else if (NumBytes &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000849 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
850 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000851
Eric Christopherb006fc92010-11-18 19:40:05 +0000852 // Increment past our save areas.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000853 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
Evan Cheng70d29632011-02-25 00:24:46 +0000854 MBBI++;
855 // Since vpop register list cannot have gaps, there may be multiple vpop
856 // instructions in the epilogue.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000857 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
Evan Cheng70d29632011-02-25 00:24:46 +0000858 MBBI++;
859 }
Tim Northover228c9432014-11-05 00:27:13 +0000860 if (AFI->getDPRCalleeSavedGapSize()) {
861 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
862 "unexpected DPR alignment gap");
863 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
864 }
865
Eric Christopherb006fc92010-11-18 19:40:05 +0000866 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
867 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000868 }
869
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000870 if (ArgRegsSaveSize)
871 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000872}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000873
Bob Wilson657f2272011-01-13 21:10:12 +0000874/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
875/// debug info. It's the same as what we use for resolving the code-gen
876/// references for now. FIXME: This can go wrong when references are
877/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000878int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000879ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000880 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000881 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
882}
883
884int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000885ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000886 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000887 int SPAdj) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000888 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000889 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000890 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000891 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000892 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +0000893 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
Matthias Braun941a7052016-07-28 18:40:00 +0000894 bool isFixed = MFI.isFixedObjectIndex(FI);
Anton Korobeynikov46877782010-11-20 15:59:32 +0000895
896 FrameReg = ARM::SP;
897 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000898
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000899 // SP can move around if there are allocas. We may also lose track of SP
900 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000901 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000902
Anton Korobeynikov46877782010-11-20 15:59:32 +0000903 // When dynamically realigning the stack, use the frame pointer for
904 // parameters, and the stack/base pointer for locals.
905 if (RegInfo->needsStackRealignment(MF)) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000906 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000907 if (isFixed) {
908 FrameReg = RegInfo->getFrameRegister(MF);
909 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000910 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000911 assert(RegInfo->hasBasePointer(MF) &&
912 "VLAs and dynamic stack alignment, but missing base pointer!");
913 FrameReg = RegInfo->getBaseRegister();
Tim Northover4bf394b2018-12-07 13:43:55 +0000914 Offset -= SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000915 }
916 return Offset;
917 }
918
919 // If there is a frame pointer, use it when we can.
920 if (hasFP(MF) && AFI->hasStackFrame()) {
921 // Use frame pointer to reference fixed objects. Use it for locals if
922 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000923 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000924 FrameReg = RegInfo->getFrameRegister(MF);
925 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000926 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000927 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000928 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000929 // Try to use the frame pointer if we can, else use the base pointer
930 // since it's available. This is handy for the emergency spill slot, in
931 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000932 if (FPOffset >= -255 && FPOffset < 0) {
933 FrameReg = RegInfo->getFrameRegister(MF);
934 return FPOffset;
935 }
Evan Chengc0d20042011-04-22 01:42:52 +0000936 }
Momchil Velikov505614b2018-03-02 15:47:14 +0000937 } else if (AFI->isThumbFunction()) {
938 // Prefer SP to base pointer, if the offset is suitably aligned and in
939 // range as the effective range of the immediate offset is bigger when
940 // basing off SP.
Andrew Trickf7ecc162011-08-25 17:40:54 +0000941 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000942 // ldr <rd>, [sp, #<imm8>]
Evan Chengc0d20042011-04-22 01:42:52 +0000943 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
944 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000945 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000946 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Momchil Velikov505614b2018-03-02 15:47:14 +0000947 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000948 FrameReg = RegInfo->getFrameRegister(MF);
949 return FPOffset;
950 }
951 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
952 // Otherwise, use SP or FP, whichever is closer to the stack slot.
953 FrameReg = RegInfo->getFrameRegister(MF);
954 return FPOffset;
955 }
956 }
957 // Use the base pointer if we have one.
958 if (RegInfo->hasBasePointer(MF))
959 FrameReg = RegInfo->getBaseRegister();
960 return Offset;
961}
962
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000963void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000964 MachineBasicBlock::iterator MI,
965 const std::vector<CalleeSavedInfo> &CSI,
966 unsigned StmOpc, unsigned StrOpc,
967 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000968 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000969 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000970 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000971 MachineFunction &MF = *MBB.getParent();
Tim Northover775aaeb2015-11-05 21:54:58 +0000972 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000973 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000974
975 DebugLoc DL;
976
Eugene Zelenko076468c2017-09-20 21:35:51 +0000977 using RegAndKill = std::pair<unsigned, bool>;
978
Tim Northover46a6f0f2016-11-14 20:28:24 +0000979 SmallVector<RegAndKill, 4> Regs;
Tim Northover775aaeb2015-11-05 21:54:58 +0000980 unsigned i = CSI.size();
Evan Cheng775ead32010-12-07 23:08:38 +0000981 while (i != 0) {
982 unsigned LastReg = 0;
983 for (; i != 0; --i) {
984 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000985 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000986
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000987 // D-registers in the aligned area DPRCS2 are NOT spilled here.
988 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
989 continue;
990
Matthias Braun0dba4e32017-05-31 01:21:30 +0000991 const MachineRegisterInfo &MRI = MF.getRegInfo();
992 bool isLiveIn = MRI.isLiveIn(Reg);
993 if (!isLiveIn && !MRI.isReserved(Reg))
Evan Cheng775ead32010-12-07 23:08:38 +0000994 MBB.addLiveIn(Reg);
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000995 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +0000996 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +0000997 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +0000998 if (NoGap && LastReg && LastReg != Reg-1)
999 break;
Evan Cheng775ead32010-12-07 23:08:38 +00001000 LastReg = Reg;
Matthias Braun707e02c2016-04-13 21:43:25 +00001001 // Do not set a kill flag on values that are also marked as live-in. This
1002 // happens with the @llvm-returnaddress intrinsic and with arguments
1003 // passed in callee saved registers.
1004 // Omitting the kill flags is conservatively correct even if the live-in
1005 // is not used after all.
1006 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001007 }
1008
Jim Grosbach5fccad82010-12-09 18:31:13 +00001009 if (Regs.empty())
1010 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001011
Fangrui Song0cac7262018-09-27 02:13:45 +00001012 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +00001013 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1014 });
1015
Jim Grosbach5fccad82010-12-09 18:31:13 +00001016 if (Regs.size() > 1 || StrOpc== 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001017 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1018 .addReg(ARM::SP)
1019 .setMIFlags(MIFlags)
1020 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001021 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1022 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +00001023 } else if (Regs.size() == 1) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001024 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1025 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1026 .addReg(ARM::SP)
1027 .setMIFlags(MIFlags)
1028 .addImm(-4)
1029 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001030 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001031 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001032
1033 // Put any subsequent vpush instructions before this one: they will refer to
1034 // higher register numbers so need to be pushed first in order to preserve
1035 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +00001036 if (MI != MBB.begin())
1037 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001038 }
Evan Cheng775ead32010-12-07 23:08:38 +00001039}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001040
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001041void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001042 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001043 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001044 unsigned LdmOpc, unsigned LdrOpc,
1045 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001046 bool(*Func)(unsigned, bool),
1047 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +00001048 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001049 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +00001050 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Evan Cheng775ead32010-12-07 23:08:38 +00001051 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +00001052 DebugLoc DL;
1053 bool isTailCall = false;
1054 bool isInterrupt = false;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001055 bool isTrap = false;
Quentin Colombet71a71482015-07-20 21:42:14 +00001056 if (MBB.end() != MI) {
1057 DL = MI->getDebugLoc();
1058 unsigned RetOpcode = MI->getOpcode();
1059 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1060 isInterrupt =
1061 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001062 isTrap =
1063 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1064 RetOpcode == ARM::tTRAP;
Quentin Colombet71a71482015-07-20 21:42:14 +00001065 }
Evan Cheng775ead32010-12-07 23:08:38 +00001066
1067 SmallVector<unsigned, 4> Regs;
1068 unsigned i = CSI.size();
1069 while (i != 0) {
1070 unsigned LastReg = 0;
1071 bool DeleteRet = false;
1072 for (; i != 0; --i) {
Matthias Braun51687912017-09-28 23:12:06 +00001073 CalleeSavedInfo &Info = CSI[i-1];
1074 unsigned Reg = Info.getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001075 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001076
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001077 // The aligned reloads from area DPRCS2 are not inserted here.
1078 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1079 continue;
1080
Tim Northoverd8407452013-10-01 14:33:28 +00001081 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001082 !isTrap && STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001083 if (MBB.succ_empty()) {
1084 Reg = ARM::PC;
Thomas Preud'hommec699eaa2018-03-05 11:49:00 +00001085 // Fold the return instruction into the LDM.
Quentin Colombet71a71482015-07-20 21:42:14 +00001086 DeleteRet = true;
1087 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Matthias Braun51687912017-09-28 23:12:06 +00001088 // We 'restore' LR into PC so it is not live out of the return block:
1089 // Clear Restored bit.
1090 Info.setRestored(false);
Quentin Colombet71a71482015-07-20 21:42:14 +00001091 } else
1092 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001093 }
1094
Evan Cheng9d54ae62010-12-08 06:29:02 +00001095 // If NoGap is true, pop consecutive registers and then leave the rest
1096 // for other instructions. e.g.
1097 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1098 if (NoGap && LastReg && LastReg != Reg-1)
1099 break;
1100
Evan Cheng775ead32010-12-07 23:08:38 +00001101 LastReg = Reg;
1102 Regs.push_back(Reg);
1103 }
1104
Jim Grosbach5fccad82010-12-09 18:31:13 +00001105 if (Regs.empty())
1106 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001107
Fangrui Song0cac7262018-09-27 02:13:45 +00001108 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +00001109 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1110 });
1111
Jim Grosbach5fccad82010-12-09 18:31:13 +00001112 if (Regs.size() > 1 || LdrOpc == 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001113 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1114 .addReg(ARM::SP)
1115 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001116 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1117 MIB.addReg(Regs[i], getDefRegState(true));
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001118 if (DeleteRet) {
1119 if (MI != MBB.end()) {
1120 MIB.copyImplicitOps(*MI);
1121 MI->eraseFromParent();
1122 }
Andrew Trick6446bf72011-08-25 17:50:53 +00001123 }
Evan Cheng775ead32010-12-07 23:08:38 +00001124 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001125 } else if (Regs.size() == 1) {
1126 // If we adjusted the reg to PC from LR above, switch it back here. We
1127 // only do that for LDM.
1128 if (Regs[0] == ARM::PC)
1129 Regs[0] = ARM::LR;
1130 MachineInstrBuilder MIB =
1131 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1132 .addReg(ARM::SP, RegState::Define)
1133 .addReg(ARM::SP);
1134 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1135 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001136 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001137 MIB.addReg(0);
1138 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1139 } else
1140 MIB.addImm(4);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001141 MIB.add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001142 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001143 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001144
1145 // Put any subsequent vpop instructions after this one: they will refer to
1146 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001147 if (MI != MBB.end())
1148 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001149 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001150}
1151
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001152/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001153/// starting from d8. Also insert stack realignment code and leave the stack
1154/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001155static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1156 MachineBasicBlock::iterator MI,
1157 unsigned NumAlignedDPRCS2Regs,
1158 const std::vector<CalleeSavedInfo> &CSI,
1159 const TargetRegisterInfo *TRI) {
1160 MachineFunction &MF = *MBB.getParent();
1161 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001162 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001163 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Matthias Braun941a7052016-07-28 18:40:00 +00001164 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001165
1166 // Mark the D-register spill slots as properly aligned. Since MFI computes
1167 // stack slot layout backwards, this can actually mean that the d-reg stack
1168 // slot offsets can be wrong. The offset for d8 will always be correct.
1169 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1170 unsigned DNum = CSI[i].getReg() - ARM::D8;
Tim Northovere0ccdc62015-10-28 22:46:43 +00001171 if (DNum > NumAlignedDPRCS2Regs - 1)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001172 continue;
1173 int FI = CSI[i].getFrameIdx();
1174 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1175 // registers will be 8-byte aligned.
1176 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1177
1178 // The stack slot for D8 needs to be maximally aligned because this is
1179 // actually the point where we align the stack pointer. MachineFrameInfo
1180 // computes all offsets relative to the incoming stack pointer which is a
1181 // bit weird when realigning the stack. Any extra padding for this
1182 // over-alignment is not realized because the code inserted below adjusts
1183 // the stack pointer by numregs * 8 before aligning the stack pointer.
1184 if (DNum == 0)
1185 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1186 }
1187
1188 // Move the stack pointer to the d8 spill slot, and align it at the same
1189 // time. Leave the stack slot address in the scratch register r4.
1190 //
1191 // sub r4, sp, #numregs * 8
1192 // bic r4, r4, #align - 1
1193 // mov sp, r4
1194 //
1195 bool isThumb = AFI->isThumbFunction();
1196 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1197 AFI->setShouldRestoreSPFromFP(true);
1198
1199 // sub r4, sp, #numregs * 8
1200 // The immediate is <= 64, so it doesn't need any special encoding.
1201 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
Diana Picus8a73f552017-01-13 10:18:01 +00001202 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1203 .addReg(ARM::SP)
1204 .addImm(8 * NumAlignedDPRCS2Regs)
1205 .add(predOps(ARMCC::AL))
1206 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001207
Matthias Braun941a7052016-07-28 18:40:00 +00001208 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001209 // We must set parameter MustBeSingleInstruction to true, since
1210 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1211 // stack alignment. Luckily, this can always be done since all ARM
1212 // architecture versions that support Neon also support the BFC
1213 // instruction.
1214 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001215
1216 // mov sp, r4
1217 // The stack pointer must be adjusted before spilling anything, otherwise
1218 // the stack slots could be clobbered by an interrupt handler.
1219 // Leave r4 live, it is used below.
1220 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1221 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001222 .addReg(ARM::R4)
1223 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001224 if (!isThumb)
Diana Picus8a73f552017-01-13 10:18:01 +00001225 MIB.add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001226
1227 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1228 // r4 holds the stack slot address.
1229 unsigned NextReg = ARM::D8;
1230
1231 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1232 // The writeback is only needed when emitting two vst1.64 instructions.
1233 if (NumAlignedDPRCS2Regs >= 6) {
1234 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001235 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001236 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001237 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1238 .addReg(ARM::R4, RegState::Kill)
1239 .addImm(16)
1240 .addReg(NextReg)
1241 .addReg(SupReg, RegState::ImplicitKill)
1242 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001243 NextReg += 4;
1244 NumAlignedDPRCS2Regs -= 4;
1245 }
1246
1247 // We won't modify r4 beyond this point. It currently points to the next
1248 // register to be spilled.
1249 unsigned R4BaseReg = NextReg;
1250
1251 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1252 if (NumAlignedDPRCS2Regs >= 4) {
1253 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001254 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001255 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001256 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1257 .addReg(ARM::R4)
1258 .addImm(16)
1259 .addReg(NextReg)
1260 .addReg(SupReg, RegState::ImplicitKill)
1261 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001262 NextReg += 4;
1263 NumAlignedDPRCS2Regs -= 4;
1264 }
1265
1266 // 16-byte aligned vst1.64 with 2 d-regs.
1267 if (NumAlignedDPRCS2Regs >= 2) {
1268 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001269 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001270 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001271 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1272 .addReg(ARM::R4)
1273 .addImm(16)
1274 .addReg(SupReg)
1275 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001276 NextReg += 2;
1277 NumAlignedDPRCS2Regs -= 2;
1278 }
1279
1280 // Finally, use a vanilla vstr.64 for the odd last register.
1281 if (NumAlignedDPRCS2Regs) {
1282 MBB.addLiveIn(NextReg);
1283 // vstr.64 uses addrmode5 which has an offset scale of 4.
Diana Picus4f8c3e12017-01-13 09:37:56 +00001284 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1285 .addReg(NextReg)
1286 .addReg(ARM::R4)
1287 .addImm((NextReg - R4BaseReg) * 2)
1288 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001289 }
1290
1291 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001292 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001293}
1294
1295/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1296/// iterator to the following instruction.
1297static MachineBasicBlock::iterator
1298skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1299 unsigned NumAlignedDPRCS2Regs) {
1300 // sub r4, sp, #numregs * 8
1301 // bic r4, r4, #align - 1
1302 // mov sp, r4
1303 ++MI; ++MI; ++MI;
1304 assert(MI->mayStore() && "Expecting spill instruction");
1305
1306 // These switches all fall through.
1307 switch(NumAlignedDPRCS2Regs) {
1308 case 7:
1309 ++MI;
1310 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001311 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001312 default:
1313 ++MI;
1314 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001315 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001316 case 1:
1317 case 2:
1318 case 4:
1319 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1320 ++MI;
1321 }
1322 return MI;
1323}
1324
1325/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1326/// starting from d8. These instructions are assumed to execute while the
1327/// stack is still aligned, unlike the code inserted by emitPopInst.
1328static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1329 MachineBasicBlock::iterator MI,
1330 unsigned NumAlignedDPRCS2Regs,
1331 const std::vector<CalleeSavedInfo> &CSI,
1332 const TargetRegisterInfo *TRI) {
1333 MachineFunction &MF = *MBB.getParent();
1334 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001335 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001336 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001337
1338 // Find the frame index assigned to d8.
1339 int D8SpillFI = 0;
1340 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1341 if (CSI[i].getReg() == ARM::D8) {
1342 D8SpillFI = CSI[i].getFrameIdx();
1343 break;
1344 }
1345
1346 // Materialize the address of the d8 spill slot into the scratch register r4.
1347 // This can be fairly complicated if the stack frame is large, so just use
1348 // the normal frame index elimination mechanism to do it. This code runs as
1349 // the initial part of the epilog where the stack and base pointers haven't
1350 // been changed yet.
1351 bool isThumb = AFI->isThumbFunction();
1352 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1353
1354 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
Diana Picus8a73f552017-01-13 10:18:01 +00001355 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1356 .addFrameIndex(D8SpillFI)
1357 .addImm(0)
1358 .add(predOps(ARMCC::AL))
1359 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001360
1361 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1362 unsigned NextReg = ARM::D8;
1363
1364 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1365 if (NumAlignedDPRCS2Regs >= 6) {
1366 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001367 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001368 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1369 .addReg(ARM::R4, RegState::Define)
1370 .addReg(ARM::R4, RegState::Kill)
1371 .addImm(16)
1372 .addReg(SupReg, RegState::ImplicitDefine)
1373 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001374 NextReg += 4;
1375 NumAlignedDPRCS2Regs -= 4;
1376 }
1377
1378 // We won't modify r4 beyond this point. It currently points to the next
1379 // register to be spilled.
1380 unsigned R4BaseReg = NextReg;
1381
1382 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1383 if (NumAlignedDPRCS2Regs >= 4) {
1384 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001385 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001386 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1387 .addReg(ARM::R4)
1388 .addImm(16)
1389 .addReg(SupReg, RegState::ImplicitDefine)
1390 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001391 NextReg += 4;
1392 NumAlignedDPRCS2Regs -= 4;
1393 }
1394
1395 // 16-byte aligned vld1.64 with 2 d-regs.
1396 if (NumAlignedDPRCS2Regs >= 2) {
1397 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001398 &ARM::QPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001399 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1400 .addReg(ARM::R4)
1401 .addImm(16)
1402 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001403 NextReg += 2;
1404 NumAlignedDPRCS2Regs -= 2;
1405 }
1406
1407 // Finally, use a vanilla vldr.64 for the remaining odd register.
1408 if (NumAlignedDPRCS2Regs)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001409 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1410 .addReg(ARM::R4)
1411 .addImm(2 * (NextReg - R4BaseReg))
1412 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001413
1414 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001415 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001416}
1417
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001418bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001419 MachineBasicBlock::iterator MI,
1420 const std::vector<CalleeSavedInfo> &CSI,
1421 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001422 if (CSI.empty())
1423 return false;
1424
1425 MachineFunction &MF = *MBB.getParent();
1426 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001427
1428 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001429 unsigned PushOneOpc = AFI->isThumbFunction() ?
1430 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001431 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001432 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1433 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001434 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001435 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001436 MachineInstr::FrameSetup);
1437 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001438 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1439
1440 // The code above does not insert spill code for the aligned DPRCS2 registers.
1441 // The stack realignment code will be inserted between the push instructions
1442 // and these spills.
1443 if (NumAlignedDPRCS2Regs)
1444 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001445
1446 return true;
1447}
1448
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001449bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001450 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001451 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001452 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001453 if (CSI.empty())
1454 return false;
1455
1456 MachineFunction &MF = *MBB.getParent();
1457 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001458 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001459 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1460
1461 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1462 // registers. Do that here instead.
1463 if (NumAlignedDPRCS2Regs)
1464 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001465
1466 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001467 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001468 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001469 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1470 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001471 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001472 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001473 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001474 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001475
1476 return true;
1477}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001478
1479// FIXME: Make generic?
1480static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1481 const ARMBaseInstrInfo &TII) {
1482 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001483 for (auto &MBB : MF) {
1484 for (auto &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001485 FnSize += TII.getInstSizeInBytes(MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001486 }
1487 return FnSize;
1488}
1489
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001490/// estimateRSStackSizeLimit - Look at each instruction that references stack
1491/// frames and return the stack size limit beyond which some of these
1492/// instructions will require a scratch register during their expansion later.
1493// FIXME: Move to TII?
1494static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001495 const TargetFrameLowering *TFI) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001496 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1497 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001498 for (auto &MBB : MF) {
1499 for (auto &MI : MBB) {
1500 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1501 if (!MI.getOperand(i).isFI())
1502 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001503
1504 // When using ADDri to get the address of a stack object, 255 is the
1505 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001506 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001507 Limit = std::min(Limit, (1U << 8) - 1);
1508 break;
1509 }
1510
1511 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001512 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001513 case ARMII::AddrMode3:
1514 case ARMII::AddrModeT2_i8:
1515 Limit = std::min(Limit, (1U << 8) - 1);
1516 break;
1517 case ARMII::AddrMode5:
1518 case ARMII::AddrModeT2_i8s4:
Tim Northoverbb7d7b32018-09-07 09:21:25 +00001519 case ARMII::AddrModeT2_ldrex:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001520 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1521 break;
1522 case ARMII::AddrModeT2_i12:
1523 // i12 supports only positive offset so these will be converted to
1524 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1525 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1526 Limit = std::min(Limit, (1U << 8) - 1);
1527 break;
1528 case ARMII::AddrMode4:
1529 case ARMII::AddrMode6:
1530 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1531 // immediate offset for stack references.
1532 return 0;
1533 default:
1534 break;
1535 }
1536 break; // At most one FI per instruction
1537 }
1538 }
1539 }
1540
1541 return Limit;
1542}
1543
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001544// In functions that realign the stack, it can be an advantage to spill the
1545// callee-saved vector registers after realigning the stack. The vst1 and vld1
1546// instructions take alignment hints that can improve performance.
Matthias Braun02564862015-07-14 17:17:13 +00001547static void
1548checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001549 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1550 if (!SpillAlignedNEONRegs)
1551 return;
1552
1553 // Naked functions don't spill callee-saved registers.
Matthias Braunf1caa282017-12-15 22:22:58 +00001554 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001555 return;
1556
1557 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001558 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001559 return;
1560
1561 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001562 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001563 return;
1564
1565 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001566 if (!static_cast<const ARMBaseRegisterInfo *>(
1567 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001568 return;
1569
1570 // We always spill contiguous d-registers starting from d8. Count how many
1571 // needs spilling. The register allocator will almost always use the
1572 // callee-saved registers in order, but it can happen that there are holes in
1573 // the range. Registers above the hole will be spilled to the standard DPRCS
1574 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001575 unsigned NumSpills = 0;
1576 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001577 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001578 break;
1579
1580 // Don't do this for just one d-register. It's not worth it.
1581 if (NumSpills < 2)
1582 return;
1583
1584 // Spill the first NumSpills D-registers after realigning the stack.
1585 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1586
1587 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001588 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001589}
1590
Matthias Braun02564862015-07-14 17:17:13 +00001591void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1592 BitVector &SavedRegs,
1593 RegScavenger *RS) const {
1594 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001595 // This tells PEI to spill the FP as if it is any other callee-save register
1596 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1597 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1598 // to combine multiple loads / stores.
1599 bool CanEliminateFrame = true;
1600 bool CS1Spilled = false;
1601 bool LRSpilled = false;
1602 unsigned NumGPRSpills = 0;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001603 unsigned NumFPRSpills = 0;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001604 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1605 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001606 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001607 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001608 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001609 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001610 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001611 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001612 MachineRegisterInfo &MRI = MF.getRegInfo();
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001613 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1614 (void)TRI; // Silence unused warning in non-assert builds.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001615 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1616
1617 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1618 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001619 // since it's not always possible to restore sp from fp in a single
1620 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001621 // FIXME: It will be better just to find spare register here.
1622 if (AFI->isThumb2Function() &&
Matthias Braun941a7052016-07-28 18:40:00 +00001623 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001624 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001625
Martin Storsjoace7ae92018-05-14 21:32:52 +00001626 // If a stack probe will be emitted, spill R4 and LR, since they are
1627 // clobbered by the stack probe call.
1628 // This estimate should be a safe, conservative estimate. The actual
1629 // stack probe is enabled based on the size of the local objects;
1630 // this estimate also includes the varargs store size.
1631 if (STI.isTargetWindows() &&
1632 WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
1633 SavedRegs.set(ARM::R4);
1634 SavedRegs.set(ARM::LR);
1635 }
1636
Evan Cheng572756a2011-01-16 05:14:33 +00001637 if (AFI->isThumb1OnlyFunction()) {
1638 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001639 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001640 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001641
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001642 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
1643 // requires stack alignment. We don't know for sure what the stack size
1644 // will be, but for this, an estimate is good enough. If there anything
1645 // changes it, it'll be a spill, which implies we've used all the registers
1646 // and so R4 is already used, so not marking it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001647 // FIXME: It will be better just to find spare register here.
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001648 if (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF) ||
1649 MFI.estimateStackSize(MF) > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001650 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001651 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001652
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001653 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001654 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001655
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001656 // Spill the BasePtr if it's used.
1657 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001658 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001659
1660 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001661 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001662 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001663 for (unsigned i = 0; CSRegs[i]; ++i) {
1664 unsigned Reg = CSRegs[i];
1665 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001666 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001667 Spilled = true;
1668 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001669 }
1670
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001671 if (!ARM::GPRRegClass.contains(Reg)) {
1672 if (Spilled) {
1673 if (ARM::SPRRegClass.contains(Reg))
1674 NumFPRSpills++;
1675 else if (ARM::DPRRegClass.contains(Reg))
1676 NumFPRSpills += 2;
1677 else if (ARM::QPRRegClass.contains(Reg))
1678 NumFPRSpills += 4;
1679 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001680 continue;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001681 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001682
1683 if (Spilled) {
1684 NumGPRSpills++;
1685
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001686 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001687 if (Reg == ARM::LR)
1688 LRSpilled = true;
1689 CS1Spilled = true;
1690 continue;
1691 }
1692
1693 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1694 switch (Reg) {
1695 case ARM::LR:
1696 LRSpilled = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00001697 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +00001698 case ARM::R0: case ARM::R1:
1699 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001700 case ARM::R4: case ARM::R5:
1701 case ARM::R6: case ARM::R7:
1702 CS1Spilled = true;
1703 break;
1704 default:
1705 break;
1706 }
1707 } else {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001708 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001709 UnspilledCS1GPRs.push_back(Reg);
1710 continue;
1711 }
1712
1713 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001714 case ARM::R0: case ARM::R1:
1715 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001716 case ARM::R4: case ARM::R5:
1717 case ARM::R6: case ARM::R7:
1718 case ARM::LR:
1719 UnspilledCS1GPRs.push_back(Reg);
1720 break;
1721 default:
1722 UnspilledCS2GPRs.push_back(Reg);
1723 break;
1724 }
1725 }
1726 }
1727
1728 bool ForceLRSpill = false;
1729 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1730 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1731 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1732 // use of BL to implement far jump. If it turns out that it's not needed
1733 // then the branch fix up path will undo it.
1734 if (FnSize >= (1 << 11)) {
1735 CanEliminateFrame = false;
1736 ForceLRSpill = true;
1737 }
1738 }
1739
1740 // If any of the stack slot references may be out of range of an immediate
1741 // offset, make sure a register (or a spill slot) is available for the
1742 // register scavenger. Note that if we're indexing off the frame pointer, the
1743 // effective stack size is 4 bytes larger since the FP points to the stack
1744 // slot of the previous FP. Also, if we have variable sized objects in the
1745 // function, stack slot references will often be negative, and some of
1746 // our instructions are positive-offset only, so conservatively consider
1747 // that case to want a spill slot (or register) as well. Similarly, if
1748 // the function adjusts the stack pointer during execution and the
1749 // adjustments aren't already part of our stack size estimate, our offset
1750 // calculations may be off, so be conservative.
1751 // FIXME: We could add logic to be more precise about negative offsets
1752 // and which instructions will need a scratch register for them. Is it
1753 // worth the effort and added fragility?
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001754 unsigned EstimatedStackSize =
Matthias Braun941a7052016-07-28 18:40:00 +00001755 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001756
1757 // Determine biggest (positive) SP offset in MachineFrameInfo.
1758 int MaxFixedOffset = 0;
1759 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1760 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1761 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1762 }
1763
Matthias Braun44047422017-04-05 16:58:41 +00001764 bool HasFP = hasFP(MF);
1765 if (HasFP) {
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001766 if (AFI->hasStackFrame())
1767 EstimatedStackSize += 4;
1768 } else {
1769 // If FP is not used, SP will be used to access arguments, so count the
1770 // size of arguments into the estimation.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001771 EstimatedStackSize += MaxFixedOffset;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001772 }
1773 EstimatedStackSize += 16; // For possible paddings.
1774
Matthias Braun8aaa3682017-04-19 21:11:44 +00001775 unsigned EstimatedRSStackSizeLimit = estimateRSStackSizeLimit(MF, this);
Matthias Braunf1caa282017-12-15 22:22:58 +00001776 int MaxFPOffset = getMaxFPOffset(MF.getFunction(), *AFI);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001777 bool BigFrameOffsets = EstimatedStackSize >= EstimatedRSStackSizeLimit ||
1778 MFI.hasVarSizedObjects() ||
1779 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF)) ||
1780 // For large argument stacks fp relative addressed may overflow.
1781 (HasFP && (MaxFixedOffset - MaxFPOffset) >= (int)EstimatedRSStackSizeLimit);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001782 if (BigFrameOffsets ||
1783 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001784 AFI->setHasStackFrame(true);
1785
Matthias Braun44047422017-04-05 16:58:41 +00001786 if (HasFP) {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001787 SavedRegs.set(FramePtr);
1788 // If the frame pointer is required by the ABI, also spill LR so that we
1789 // emit a complete frame record.
1790 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1791 SavedRegs.set(ARM::LR);
1792 LRSpilled = true;
1793 NumGPRSpills++;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001794 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001795 if (LRPos != UnspilledCS1GPRs.end())
1796 UnspilledCS1GPRs.erase(LRPos);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001797 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001798 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001799 if (FPPos != UnspilledCS1GPRs.end())
1800 UnspilledCS1GPRs.erase(FPPos);
1801 NumGPRSpills++;
1802 if (FramePtr == ARM::R7)
1803 CS1Spilled = true;
1804 }
1805
Matthias Braunc618a462017-07-28 01:36:32 +00001806 // This is true when we inserted a spill for an unused register that can now
1807 // be used for register scavenging.
1808 bool ExtraCSSpill = false;
1809
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001810 if (AFI->isThumb1OnlyFunction()) {
1811 // For Thumb1-only targets, we need some low registers when we save and
1812 // restore the high registers (which aren't allocatable, but could be
1813 // used by inline assembly) because the push/pop instructions can not
1814 // access high registers. If necessary, we might need to push more low
1815 // registers to ensure that there is at least one free that can be used
1816 // for the saving & restoring, and preferably we should ensure that as
1817 // many as are needed are available so that fewer push/pop instructions
1818 // are required.
1819
1820 // Low registers which are not currently pushed, but could be (r4-r7).
1821 SmallVector<unsigned, 4> AvailableRegs;
1822
1823 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1824 // free.
1825 int EntryRegDeficit = 0;
1826 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1827 if (!MF.getRegInfo().isLiveIn(Reg)) {
1828 --EntryRegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001829 LLVM_DEBUG(dbgs()
1830 << printReg(Reg, TRI)
1831 << " is unused argument register, EntryRegDeficit = "
1832 << EntryRegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001833 }
1834 }
1835
1836 // Unused return registers can be clobbered in the epilogue for free.
1837 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001838 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
1839 << " return regs used, ExitRegDeficit = "
1840 << ExitRegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001841
1842 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001843 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001844
1845 // r4-r6 can be used in the prologue if they are pushed by the first push
1846 // instruction.
1847 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1848 if (SavedRegs.test(Reg)) {
1849 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001850 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1851 << " is saved low register, RegDeficit = "
1852 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001853 } else {
1854 AvailableRegs.push_back(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001855 LLVM_DEBUG(
1856 dbgs()
1857 << printReg(Reg, TRI)
1858 << " is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001859 }
1860 }
1861
1862 // r7 can be used if it is not being used as the frame pointer.
Matthias Braun44047422017-04-05 16:58:41 +00001863 if (!HasFP) {
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001864 if (SavedRegs.test(ARM::R7)) {
1865 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001866 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
1867 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001868 } else {
1869 AvailableRegs.push_back(ARM::R7);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001870 LLVM_DEBUG(
1871 dbgs()
1872 << "%r7 is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001873 }
1874 }
1875
1876 // Each of r8-r11 needs to be copied to a low register, then pushed.
1877 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1878 if (SavedRegs.test(Reg)) {
1879 ++RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001880 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1881 << " is saved high register, RegDeficit = "
1882 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001883 }
1884 }
1885
1886 // LR can only be used by PUSH, not POP, and can't be used at all if the
1887 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1888 // are more limited at function entry than exit.
1889 if ((EntryRegDeficit > ExitRegDeficit) &&
1890 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1891 MF.getFrameInfo().isReturnAddressTaken())) {
1892 if (SavedRegs.test(ARM::LR)) {
1893 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001894 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
1895 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001896 } else {
1897 AvailableRegs.push_back(ARM::LR);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001898 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001899 }
1900 }
1901
1902 // If there are more high registers that need pushing than low registers
1903 // available, push some more low registers so that we can use fewer push
1904 // instructions. This might not reduce RegDeficit all the way to zero,
1905 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1906 // need saving.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001907 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001908 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1909 unsigned Reg = AvailableRegs.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001910 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
1911 << " to make up reg deficit\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001912 SavedRegs.set(Reg);
1913 NumGPRSpills++;
1914 CS1Spilled = true;
Matthias Braunc618a462017-07-28 01:36:32 +00001915 assert(!MRI.isReserved(Reg) && "Should not be reserved");
1916 if (!MRI.isPhysRegUsed(Reg))
1917 ExtraCSSpill = true;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001918 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001919 if (Reg == ARM::LR)
1920 LRSpilled = true;
1921 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001922 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
1923 << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001924 }
1925
Eli Friedman5b45a392018-08-08 20:03:10 +00001926 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
1927 // restore LR in that case.
1928 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
1929
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001930 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1931 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
Eli Friedman5b45a392018-08-08 20:03:10 +00001932 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
Matthias Braun02564862015-07-14 17:17:13 +00001933 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001934 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00001935 SmallVectorImpl<unsigned>::iterator LRPos;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001936 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
Tim Northoverd8407452013-10-01 14:33:28 +00001937 if (LRPos != UnspilledCS1GPRs.end())
1938 UnspilledCS1GPRs.erase(LRPos);
1939
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001940 ForceLRSpill = false;
Matthias Braunc618a462017-07-28 01:36:32 +00001941 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR))
1942 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001943 }
1944
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001945 // If stack and double are 8-byte aligned and we are spilling an odd number
1946 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1947 // the integer and double callee save areas.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001948 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001949 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00001950 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001951 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1952 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1953 unsigned Reg = UnspilledCS1GPRs[i];
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001954 // Don't spill high register if the function is thumb. In the case of
1955 // Windows on ARM, accept R11 (frame pointer)
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00001956 if (!AFI->isThumbFunction() ||
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00001957 (STI.isTargetWindows() && Reg == ARM::R11) ||
Eli Friedman5b45a392018-08-08 20:03:10 +00001958 isARMLowRegister(Reg) ||
1959 (Reg == ARM::LR && !ExpensiveLRRestore)) {
Matthias Braun02564862015-07-14 17:17:13 +00001960 SavedRegs.set(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001961 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
1962 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00001963 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001964 ExtraCSSpill = true;
1965 break;
1966 }
1967 }
1968 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1969 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00001970 SavedRegs.set(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001971 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
1972 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00001973 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001974 ExtraCSSpill = true;
1975 }
1976 }
1977
1978 // Estimate if we might need to scavenge a register at some point in order
1979 // to materialize a stack offset. If so, either spill one additional
1980 // callee-saved register or reserve a special spill slot to facilitate
1981 // register scavenging. Thumb1 needs a spill slot for stack pointer
1982 // adjustments also, even when the frame itself is small.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001983 if (BigFrameOffsets && !ExtraCSSpill) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001984 // If any non-reserved CS register isn't spilled, just spill one or two
1985 // extra. That should take care of it!
1986 unsigned NumExtras = TargetAlign / 4;
1987 SmallVector<unsigned, 2> Extras;
1988 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1989 unsigned Reg = UnspilledCS1GPRs.back();
1990 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001991 if (!MRI.isReserved(Reg) &&
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001992 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1993 Reg == ARM::LR)) {
1994 Extras.push_back(Reg);
1995 NumExtras--;
1996 }
1997 }
1998 // For non-Thumb1 functions, also check for hi-reg CS registers
1999 if (!AFI->isThumb1OnlyFunction()) {
2000 while (NumExtras && !UnspilledCS2GPRs.empty()) {
2001 unsigned Reg = UnspilledCS2GPRs.back();
2002 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00002003 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002004 Extras.push_back(Reg);
2005 NumExtras--;
2006 }
2007 }
2008 }
Matthias Braunc618a462017-07-28 01:36:32 +00002009 if (NumExtras == 0) {
2010 for (unsigned Reg : Extras) {
2011 SavedRegs.set(Reg);
2012 if (!MRI.isPhysRegUsed(Reg))
2013 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002014 }
Matthias Braunc618a462017-07-28 01:36:32 +00002015 }
2016 if (!ExtraCSSpill && !AFI->isThumb1OnlyFunction()) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002017 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
2018 // closest to SP or frame pointer.
Weiming Zhao5b5501e2016-05-08 05:11:54 +00002019 assert(RS && "Register scavenging not provided");
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00002020 const TargetRegisterClass &RC = ARM::GPRRegClass;
2021 unsigned Size = TRI->getSpillSize(RC);
2022 unsigned Align = TRI->getSpillAlignment(RC);
2023 RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002024 }
2025 }
2026 }
2027
2028 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00002029 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002030 AFI->setLRIsSpilledForFarJump(true);
2031 }
2032}
Eli Bendersky8da87162013-02-21 20:05:00 +00002033
Hans Wennborge1a2e902016-03-31 18:33:38 +00002034MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
2035 MachineFunction &MF, MachineBasicBlock &MBB,
2036 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00002037 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002038 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00002039 if (!hasReservedCallFrame(MF)) {
2040 // If we have alloca, convert as follows:
2041 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
2042 // ADJCALLSTACKUP -> add, sp, sp, amount
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002043 MachineInstr &Old = *I;
2044 DebugLoc dl = Old.getDebugLoc();
Serge Pavlov5943a962017-04-19 03:12:05 +00002045 unsigned Amount = TII.getFrameSize(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002046 if (Amount != 0) {
2047 // We need to keep the stack aligned properly. To do this, we round the
2048 // amount of space needed for the outgoing arguments up to the next
2049 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00002050 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00002051
2052 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2053 assert(!AFI->isThumb1OnlyFunction() &&
2054 "This eliminateCallFramePseudoInstr does not support Thumb1!");
2055 bool isARM = !AFI->isThumbFunction();
2056
2057 // Replace the pseudo instruction with a new instruction...
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002058 unsigned Opc = Old.getOpcode();
2059 int PIdx = Old.findFirstPredOperandIdx();
2060 ARMCC::CondCodes Pred =
2061 (PIdx == -1) ? ARMCC::AL
2062 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
Serge Pavlov5943a962017-04-19 03:12:05 +00002063 unsigned PredReg = TII.getFramePred(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002064 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
Eli Bendersky8da87162013-02-21 20:05:00 +00002065 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2066 Pred, PredReg);
2067 } else {
Eli Bendersky8da87162013-02-21 20:05:00 +00002068 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2069 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2070 Pred, PredReg);
2071 }
2072 }
2073 }
Hans Wennborge1a2e902016-03-31 18:33:38 +00002074 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00002075}
2076
Oliver Stannardb14c6252014-04-02 16:10:33 +00002077/// Get the minimum constant for ARM that is greater than or equal to the
2078/// argument. In ARM, constants can have any value that can be produced by
2079/// rotating an 8-bit value to the right by an even number of bits within a
2080/// 32-bit word.
2081static uint32_t alignToARMConstant(uint32_t Value) {
2082 unsigned Shifted = 0;
2083
2084 if (Value == 0)
2085 return 0;
2086
2087 while (!(Value & 0xC0000000)) {
2088 Value = Value << 2;
2089 Shifted += 2;
2090 }
2091
2092 bool Carry = (Value & 0x00FFFFFF);
2093 Value = ((Value & 0xFF000000) >> 24) + Carry;
2094
2095 if (Value & 0x0000100)
2096 Value = Value & 0x000001FC;
2097
2098 if (Shifted > 24)
2099 Value = Value >> (Shifted - 24);
2100 else
2101 Value = Value << (24 - Shifted);
2102
2103 return Value;
2104}
2105
2106// The stack limit in the TCB is set to this many bytes above the actual
2107// stack limit.
2108static const uint64_t kSplitStackAvailable = 256;
2109
2110// Adjust the function prologue to enable split stacks. This currently only
2111// supports android and linux.
2112//
2113// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2114// must be well defined in order to allow for consistent implementations of the
2115// __morestack helper function. The ABI is also not a normal ABI in that it
2116// doesn't follow the normal calling conventions because this allows the
2117// prologue of each function to be optimized further.
2118//
2119// Currently, the ABI looks like (when calling __morestack)
2120//
2121// * r4 holds the minimum stack size requested for this function call
2122// * r5 holds the stack size of the arguments to the function
2123// * the beginning of the function is 3 instructions after the call to
2124// __morestack
2125//
2126// Implementations of __morestack should use r4 to allocate a new stack, r5 to
2127// place the arguments on to the new stack, and the 3-instruction knowledge to
2128// jump directly to the body of the function when working on the new stack.
2129//
2130// An old (and possibly no longer compatible) implementation of __morestack for
2131// ARM can be found at [1].
2132//
2133// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00002134void ARMFrameLowering::adjustForSegmentedStacks(
2135 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00002136 unsigned Opcode;
2137 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00002138 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002139 bool Thumb = ST->isThumb();
2140
2141 // Sadly, this currently doesn't support varargs, platforms other than
2142 // android/linux. Note that thumb1/thumb2 are support for android/linux.
Matthias Braunf1caa282017-12-15 22:22:58 +00002143 if (MF.getFunction().isVarArg())
Oliver Stannardb14c6252014-04-02 16:10:33 +00002144 report_fatal_error("Segmented stacks do not support vararg functions.");
2145 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00002146 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00002147
Matthias Braun941a7052016-07-28 18:40:00 +00002148 MachineFrameInfo &MFI = MF.getFrameInfo();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002149 MachineModuleInfo &MMI = MF.getMMI();
2150 MCContext &Context = MMI.getContext();
2151 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2152 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002153 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002154 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2155 DebugLoc DL;
2156
Matthias Braun941a7052016-07-28 18:40:00 +00002157 uint64_t StackSize = MFI.getStackSize();
Tim Northoverf9e798b2014-05-22 13:03:43 +00002158
Than McIntosh31909932018-06-26 14:11:30 +00002159 // Do not generate a prologue for leaf functions with a stack of size zero.
2160 // For non-leaf functions we have to allow for the possibility that the
Sterling Augustine9cc1ffa2018-11-26 23:26:31 +00002161 // callis to a non-split function, as in PR37807. This function could also
2162 // take the address of a non-split function. When the linker tries to adjust
2163 // its non-existent prologue, it would fail with an error. Mark the object
2164 // file so that such failures are not errors. See this Go language bug-report
2165 // https://go-review.googlesource.com/c/go/+/148819/
2166 if (StackSize == 0 && !MFI.hasTailCall()) {
2167 MF.getMMI().setHasNosplitStack(true);
Tim Northoverf9e798b2014-05-22 13:03:43 +00002168 return;
Sterling Augustine9cc1ffa2018-11-26 23:26:31 +00002169 }
Tim Northoverf9e798b2014-05-22 13:03:43 +00002170
Oliver Stannardb14c6252014-04-02 16:10:33 +00002171 // Use R4 and R5 as scratch registers.
2172 // We save R4 and R5 before use and restore them before leaving the function.
2173 unsigned ScratchReg0 = ARM::R4;
2174 unsigned ScratchReg1 = ARM::R5;
2175 uint64_t AlignedStackSize;
2176
2177 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2178 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2179 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2180 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2181 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2182
Quentin Colombet71a71482015-07-20 21:42:14 +00002183 // Grab everything that reaches PrologueMBB to update there liveness as well.
2184 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2185 SmallVector<MachineBasicBlock *, 2> WalkList;
2186 WalkList.push_back(&PrologueMBB);
2187
2188 do {
2189 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2190 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2191 if (BeforePrologueRegion.insert(PredBB).second)
2192 WalkList.push_back(PredBB);
2193 }
2194 } while (!WalkList.empty());
2195
2196 // The order in that list is important.
2197 // The blocks will all be inserted before PrologueMBB using that order.
2198 // Therefore the block that should appear first in the CFG should appear
2199 // first in the list.
2200 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2201 PostStackMBB};
Quentin Colombet71a71482015-07-20 21:42:14 +00002202
Craig Topper80720812015-12-01 06:13:01 +00002203 for (MachineBasicBlock *B : AddedBlocks)
2204 BeforePrologueRegion.insert(B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002205
Matthias Braund9da1622015-09-09 18:08:03 +00002206 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00002207 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00002208 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002209 }
2210
Quentin Colombet71a71482015-07-20 21:42:14 +00002211 // Remove the newly added blocks from the list, since we know
2212 // we do not have to do the following updates for them.
Craig Topper80720812015-12-01 06:13:01 +00002213 for (MachineBasicBlock *B : AddedBlocks) {
2214 BeforePrologueRegion.erase(B);
2215 MF.insert(PrologueMBB.getIterator(), B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002216 }
2217
2218 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2219 // Make sure the LiveIns are still sorted and unique.
2220 MBB->sortUniqueLiveIns();
2221 // Replace the edges to PrologueMBB by edges to the sequences
2222 // we are about to add.
2223 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2224 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00002225
2226 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00002227 AlignedStackSize = alignToARMConstant(StackSize);
2228
2229 // When the frame size is less than 256 we just compare the stack
2230 // boundary directly to the value of the stack pointer, per gcc.
2231 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2232
2233 // We will use two of the callee save registers as scratch registers so we
2234 // need to save those registers onto the stack.
2235 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2236 // requested and arguments for __morestack().
2237 // SR0: Scratch Register #0
2238 // SR1: Scratch Register #1
2239 // push {SR0, SR1}
2240 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002241 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2242 .add(predOps(ARMCC::AL))
2243 .addReg(ScratchReg0)
2244 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002245 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002246 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2247 .addReg(ARM::SP, RegState::Define)
2248 .addReg(ARM::SP)
2249 .add(predOps(ARMCC::AL))
2250 .addReg(ScratchReg0)
2251 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002252 }
2253
2254 // Emit the relevant DWARF information about the change in stack pointer as
2255 // well as where to find both r4 and r5 (the callee-save registers)
2256 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002257 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002258 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2259 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002260 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002261 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2262 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2263 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002264 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002265 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2266 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2267 .addCFIIndex(CFIIndex);
2268
2269 // mov SR1, sp
2270 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002271 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2272 .addReg(ARM::SP)
2273 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002274 } else if (CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002275 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2276 .addReg(ARM::SP)
2277 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002278 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002279 }
2280
2281 // sub SR1, sp, #StackSize
2282 if (!CompareStackPointer && Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002283 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2284 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002285 .addReg(ScratchReg1)
2286 .addImm(AlignedStackSize)
2287 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002288 } else if (!CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002289 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2290 .addReg(ARM::SP)
2291 .addImm(AlignedStackSize)
2292 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002293 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002294 }
2295
2296 if (Thumb && ST->isThumb1Only()) {
2297 unsigned PCLabelId = ARMFI->createPICLabelUId();
2298 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Matthias Braunf1caa282017-12-15 22:22:58 +00002299 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002300 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00002301 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002302
2303 // ldr SR0, [pc, offset(STACK_LIMIT)]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002304 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2305 .addConstantPoolIndex(CPI)
2306 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002307
2308 // ldr SR0, [SR0]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002309 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2310 .addReg(ScratchReg0)
2311 .addImm(0)
2312 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002313 } else {
2314 // Get TLS base address from the coprocessor
2315 // mrc p15, #0, SR0, c13, c0, #3
Diana Picus4f8c3e12017-01-13 09:37:56 +00002316 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2317 .addImm(15)
2318 .addImm(0)
2319 .addImm(13)
2320 .addImm(0)
2321 .addImm(3)
2322 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002323
2324 // Use the last tls slot on android and a private field of the TCP on linux.
2325 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2326 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2327
2328 // Get the stack limit from the right offset
2329 // ldr SR0, [sr0, #4 * TlsOffset]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002330 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2331 .addReg(ScratchReg0)
2332 .addImm(4 * TlsOffset)
2333 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002334 }
2335
2336 // Compare stack limit with stack size requested.
2337 // cmp SR0, SR1
2338 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
Diana Picus4f8c3e12017-01-13 09:37:56 +00002339 BuildMI(GetMBB, DL, TII.get(Opcode))
2340 .addReg(ScratchReg0)
2341 .addReg(ScratchReg1)
2342 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002343
2344 // This jump is taken if StackLimit < SP - stack required.
2345 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2346 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2347 .addImm(ARMCC::LO)
2348 .addReg(ARM::CPSR);
2349
2350
2351 // Calling __morestack(StackSize, Size of stack arguments).
2352 // __morestack knows that the stack size requested is in SR0(r4)
2353 // and amount size of stack arguments is in SR1(r5).
2354
2355 // Pass first argument for the __morestack by Scratch Register #0.
2356 // The amount size of stack required
2357 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002358 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2359 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002360 .addImm(AlignedStackSize)
2361 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002362 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002363 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2364 .addImm(AlignedStackSize)
2365 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002366 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002367 }
2368 // Pass second argument for the __morestack by Scratch Register #1.
2369 // The amount size of stack consumed to save function arguments.
2370 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002371 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2372 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002373 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2374 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002375 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002376 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2377 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2378 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002379 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002380 }
2381
2382 // push {lr} - Save return address of this function.
2383 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002384 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2385 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002386 .addReg(ARM::LR);
2387 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002388 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2389 .addReg(ARM::SP, RegState::Define)
2390 .addReg(ARM::SP)
2391 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002392 .addReg(ARM::LR);
2393 }
2394
2395 // Emit the DWARF info about the change in stack as well as where to find the
2396 // previous link register
2397 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002398 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002399 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2400 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002401 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002402 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2403 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2404 .addCFIIndex(CFIIndex);
2405
2406 // Call __morestack().
2407 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002408 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2409 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002410 .addExternalSymbol("__morestack");
2411 } else {
2412 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2413 .addExternalSymbol("__morestack");
2414 }
2415
2416 // pop {lr} - Restore return address of this original function.
2417 if (Thumb) {
2418 if (ST->isThumb1Only()) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002419 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2420 .add(predOps(ARMCC::AL))
2421 .addReg(ScratchReg0);
2422 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2423 .addReg(ScratchReg0)
2424 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002425 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002426 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2427 .addReg(ARM::LR, RegState::Define)
2428 .addReg(ARM::SP, RegState::Define)
2429 .addReg(ARM::SP)
2430 .addImm(4)
2431 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002432 }
2433 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002434 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2435 .addReg(ARM::SP, RegState::Define)
2436 .addReg(ARM::SP)
2437 .add(predOps(ARMCC::AL))
2438 .addReg(ARM::LR);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002439 }
2440
2441 // Restore SR0 and SR1 in case of __morestack() was called.
2442 // __morestack() will skip PostStackMBB block so we need to restore
2443 // scratch registers from here.
2444 // pop {SR0, SR1}
2445 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002446 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2447 .add(predOps(ARMCC::AL))
2448 .addReg(ScratchReg0)
2449 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002450 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002451 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2452 .addReg(ARM::SP, RegState::Define)
2453 .addReg(ARM::SP)
2454 .add(predOps(ARMCC::AL))
2455 .addReg(ScratchReg0)
2456 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002457 }
2458
2459 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002460 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002461 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2462 .addCFIIndex(CFIIndex);
2463
Joerg Sonnenberger0f76a352017-08-28 20:20:47 +00002464 // Return from this function.
2465 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002466
2467 // Restore SR0 and SR1 in case of __morestack() was not called.
2468 // pop {SR0, SR1}
2469 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002470 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2471 .add(predOps(ARMCC::AL))
2472 .addReg(ScratchReg0)
2473 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002474 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002475 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2476 .addReg(ARM::SP, RegState::Define)
2477 .addReg(ARM::SP)
2478 .add(predOps(ARMCC::AL))
2479 .addReg(ScratchReg0)
2480 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002481 }
2482
2483 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002484 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002485 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2486 .addCFIIndex(CFIIndex);
2487
2488 // Tell debuggers that r4 and r5 are now the same as they were in the
2489 // previous function, that they're the "Same Value".
Matthias Braunf23ef432016-11-30 23:48:42 +00002490 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002491 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2492 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2493 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002494 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002495 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2496 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2497 .addCFIIndex(CFIIndex);
2498
2499 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002500 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002501
2502 AllocMBB->addSuccessor(PostStackMBB);
2503
2504 GetMBB->addSuccessor(PostStackMBB);
2505 GetMBB->addSuccessor(AllocMBB);
2506
2507 McrMBB->addSuccessor(GetMBB);
2508
2509 PrevStackMBB->addSuccessor(McrMBB);
2510
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002511#ifdef EXPENSIVE_CHECKS
Oliver Stannardb14c6252014-04-02 16:10:33 +00002512 MF.verify();
2513#endif
2514}