blob: 03681d5634cc5ee14fedc92acc242b35a80d966b [file] [log] [blame]
Eugene Zelenko076468c2017-09-20 21:35:51 +00001//===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00006//
7//===----------------------------------------------------------------------===//
8//
Anton Korobeynikov2f931282011-01-10 12:39:04 +00009// This file contains the ARM implementation of TargetFrameLowering class.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000010//
11//===----------------------------------------------------------------------===//
12
Anton Korobeynikov2f931282011-01-10 12:39:04 +000013#include "ARMFrameLowering.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000014#include "ARMBaseInstrInfo.h"
Evan Chenge45d6852011-01-11 21:46:47 +000015#include "ARMBaseRegisterInfo.h"
Oliver Stannardb14c6252014-04-02 16:10:33 +000016#include "ARMConstantPoolValue.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000017#include "ARMMachineFunctionInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000018#include "ARMSubtarget.h"
Evan Chenga20cde32011-07-20 23:34:39 +000019#include "MCTargetDesc/ARMAddressingModes.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000020#include "MCTargetDesc/ARMBaseInfo.h"
Eugene Zelenko076468c2017-09-20 21:35:51 +000021#include "Utils/ARMBaseInfo.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000022#include "llvm/ADT/BitVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000024#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +000030#include "llvm/CodeGen/MachineInstr.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Eli Friedman2596e8b2019-03-19 21:48:08 +000032#include "llvm/CodeGen/MachineJumpTableInfo.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
Francis Visoiu Mistrihb7cef812019-01-14 10:55:55 +000082bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000083 // 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.
Francis Visoiu Mistrihb7cef812019-01-14 10:55:55 +000086 return MF.getSubtarget<ARMSubtarget>().useFastISel();
Akira Hatanakaddf76aa2015-05-23 01:14:08 +000087}
88
Tim Northovere25e4582018-04-07 10:57:03 +000089/// Returns true if the target can safely skip saving callee-saved registers
90/// for noreturn nounwind functions.
91bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
92 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
93 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
94 !MF.getFunction().hasFnAttribute(Attribute::UWTable));
95
96 // Frame pointer and link register are not treated as normal CSR, thus we
97 // can always skip CSR saves for nonreturning functions.
98 return true;
99}
100
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000101/// hasFP - Return true if the specified function should have a dedicated frame
102/// pointer register. This is true if the function has variable sized allocas
103/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000104bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +0000105 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000106 const MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000107
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000108 // ABI-required frame pointer.
109 if (MF.getTarget().Options.DisableFramePointerElim(MF))
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000110 return true;
111
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000112 // Frame pointer required for use within this function.
113 return (RegInfo->needsStackRealignment(MF) ||
Matthias Braun941a7052016-07-28 18:40:00 +0000114 MFI.hasVarSizedObjects() ||
115 MFI.isFrameAddressTaken());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000116}
117
Bob Wilson657f2272011-01-13 21:10:12 +0000118/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
119/// not required, we reserve argument space for call sites in the function
120/// immediately on entry to the current function. This eliminates the need for
121/// add/sub sp brackets around call sites. Returns true if the call frame is
122/// included as part of the stack frame.
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000123bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000124 const MachineFrameInfo &MFI = MF.getFrameInfo();
125 unsigned CFSize = MFI.getMaxCallFrameSize();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000126 // It's not always a good idea to include the call frame as part of the
127 // stack frame. ARM (especially Thumb) has small immediate offset to
128 // address the stack frame. So a large call frame can cause poor codegen
129 // and may even makes it impossible to scavenge a register.
130 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
131 return false;
132
Matthias Braun941a7052016-07-28 18:40:00 +0000133 return !MFI.hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000134}
135
Bob Wilson657f2272011-01-13 21:10:12 +0000136/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
137/// call frame pseudos can be simplified. Unlike most targets, having a FP
138/// is not sufficient here since we still may reference some objects via SP
139/// even when FP is available in Thumb2 mode.
140bool
141ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000142 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000143}
144
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000145static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
Craig Topper840beec2014-04-04 05:16:06 +0000146 const MCPhysReg *CSRegs) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000147 // Integer spill area is handled with "pop".
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000148 if (isPopOpcode(MI.getOpcode())) {
Eric Christopherb006fc92010-11-18 19:40:05 +0000149 // The first two operands are predicates. The last two are
150 // imp-def and imp-use of SP. Check everything in between.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000151 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
152 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
Eric Christopherb006fc92010-11-18 19:40:05 +0000153 return false;
154 return true;
155 }
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000156 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
157 MI.getOpcode() == ARM::LDR_POST_REG ||
158 MI.getOpcode() == ARM::t2LDR_POST) &&
159 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
160 MI.getOperand(1).getReg() == ARM::SP)
Jim Grosbachbdb7ed12010-12-10 18:41:15 +0000161 return true;
Eric Christopherb006fc92010-11-18 19:40:05 +0000162
163 return false;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000164}
165
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000166static void emitRegPlusImmediate(
167 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
168 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
169 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
170 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000171 if (isARM)
Tim Northoverc9432eb2013-11-04 23:04:15 +0000172 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000173 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000174 else
Tim Northoverc9432eb2013-11-04 23:04:15 +0000175 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
Eli Bendersky8da87162013-02-21 20:05:00 +0000176 Pred, PredReg, TII, MIFlags);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000177}
178
Tim Northoverc9432eb2013-11-04 23:04:15 +0000179static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000180 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
Tim Northoverc9432eb2013-11-04 23:04:15 +0000181 const ARMBaseInstrInfo &TII, int NumBytes,
182 unsigned MIFlags = MachineInstr::NoFlags,
183 ARMCC::CondCodes Pred = ARMCC::AL,
184 unsigned PredReg = 0) {
185 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
186 MIFlags, Pred, PredReg);
187}
188
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000189static int sizeOfSPAdjustment(const MachineInstr &MI) {
Tim Northover603d3162014-11-14 22:45:33 +0000190 int RegSize;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000191 switch (MI.getOpcode()) {
Tim Northover603d3162014-11-14 22:45:33 +0000192 case ARM::VSTMDDB_UPD:
193 RegSize = 8;
194 break;
195 case ARM::STMDB_UPD:
196 case ARM::t2STMDB_UPD:
197 RegSize = 4;
198 break;
199 case ARM::t2STR_PRE:
200 case ARM::STR_PRE_IMM:
201 return 4;
202 default:
203 llvm_unreachable("Unknown push or pop like instruction");
204 }
205
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000206 int count = 0;
207 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
208 // pred) so the list starts at 4.
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000209 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
Tim Northover603d3162014-11-14 22:45:33 +0000210 count += RegSize;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000211 return count;
212}
213
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000214static bool WindowsRequiresStackProbe(const MachineFunction &MF,
215 size_t StackSizeInBytes) {
Matthias Braun941a7052016-07-28 18:40:00 +0000216 const MachineFrameInfo &MFI = MF.getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +0000217 const Function &F = MF.getFunction();
Matthias Braun941a7052016-07-28 18:40:00 +0000218 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
Matthias Braunf1caa282017-12-15 22:22:58 +0000219 if (F.hasFnAttribute("stack-probe-size"))
220 F.getFnAttribute("stack-probe-size")
Saleem Abdulrasoolfb8a66f2015-01-31 02:26:37 +0000221 .getValueAsString()
222 .getAsInteger(0, StackProbeSize);
Hans Wennborg89c35fc2018-02-23 13:46:25 +0000223 return (StackSizeInBytes >= StackProbeSize) &&
224 !F.hasFnAttribute("no-stack-arg-probe");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000225}
226
Tim Northover603d3162014-11-14 22:45:33 +0000227namespace {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000228
Tim Northover603d3162014-11-14 22:45:33 +0000229struct StackAdjustingInsts {
230 struct InstInfo {
231 MachineBasicBlock::iterator I;
232 unsigned SPAdjust;
233 bool BeforeFPSet;
234 };
235
236 SmallVector<InstInfo, 4> Insts;
237
238 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
239 bool BeforeFPSet = false) {
240 InstInfo Info = {I, SPAdjust, BeforeFPSet};
241 Insts.push_back(Info);
242 }
243
244 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000245 auto Info =
246 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
Tim Northover603d3162014-11-14 22:45:33 +0000247 assert(Info != Insts.end() && "invalid sp adjusting instruction");
248 Info->SPAdjust += ExtraBytes;
249 }
250
Matthias Braunf23ef432016-11-30 23:48:42 +0000251 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
252 const ARMBaseInstrInfo &TII, bool HasFP) {
253 MachineFunction &MF = *MBB.getParent();
Tim Northover603d3162014-11-14 22:45:33 +0000254 unsigned CFAOffset = 0;
255 for (auto &Info : Insts) {
256 if (HasFP && !Info.BeforeFPSet)
257 return;
258
259 CFAOffset -= Info.SPAdjust;
Matthias Braunf23ef432016-11-30 23:48:42 +0000260 unsigned CFIIndex = MF.addFrameInst(
Tim Northover603d3162014-11-14 22:45:33 +0000261 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
262 BuildMI(MBB, std::next(Info.I), dl,
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000263 TII.get(TargetOpcode::CFI_INSTRUCTION))
264 .addCFIIndex(CFIIndex)
265 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000266 }
267 }
268};
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000269
270} // end anonymous namespace
Tim Northover603d3162014-11-14 22:45:33 +0000271
Kristof Beyls933de7a2015-01-08 15:09:14 +0000272/// Emit an instruction sequence that will align the address in
273/// register Reg by zero-ing out the lower bits. For versions of the
274/// architecture that support Neon, this must be done in a single
275/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
276/// single instruction. That function only gets called when optimizing
277/// spilling of D registers on a core with the Neon instruction set
278/// present.
279static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
280 const TargetInstrInfo &TII,
281 MachineBasicBlock &MBB,
282 MachineBasicBlock::iterator MBBI,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000283 const DebugLoc &DL, const unsigned Reg,
Kristof Beyls933de7a2015-01-08 15:09:14 +0000284 const unsigned Alignment,
285 const bool MustBeSingleInstruction) {
Eric Christopher1b21f002015-01-29 00:19:33 +0000286 const ARMSubtarget &AST =
287 static_cast<const ARMSubtarget &>(MF.getSubtarget());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000288 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
289 const unsigned AlignMask = Alignment - 1;
290 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
291 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
292 if (!AFI->isThumbFunction()) {
293 // if the BFC instruction is available, use that to zero the lower
294 // bits:
295 // bfc Reg, #0, log2(Alignment)
296 // otherwise use BIC, if the mask to zero the required number of bits
297 // can be encoded in the bic immediate field
298 // bic Reg, Reg, Alignment-1
299 // otherwise, emit
300 // lsr Reg, Reg, log2(Alignment)
301 // lsl Reg, Reg, log2(Alignment)
302 if (CanUseBFC) {
Diana Picus4f8c3e12017-01-13 09:37:56 +0000303 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
304 .addReg(Reg, RegState::Kill)
305 .addImm(~AlignMask)
306 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000307 } else if (AlignMask <= 255) {
Diana Picus8a73f552017-01-13 10:18:01 +0000308 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
309 .addReg(Reg, RegState::Kill)
310 .addImm(AlignMask)
311 .add(predOps(ARMCC::AL))
312 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000313 } else {
314 assert(!MustBeSingleInstruction &&
315 "Shouldn't call emitAligningInstructions demanding a single "
316 "instruction to be emitted for large stack alignment for a target "
317 "without BFC.");
Diana Picus8a73f552017-01-13 10:18:01 +0000318 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
319 .addReg(Reg, RegState::Kill)
320 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
321 .add(predOps(ARMCC::AL))
322 .add(condCodeOp());
323 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
324 .addReg(Reg, RegState::Kill)
325 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
326 .add(predOps(ARMCC::AL))
327 .add(condCodeOp());
Kristof Beyls933de7a2015-01-08 15:09:14 +0000328 }
329 } else {
330 // Since this is only reached for Thumb-2 targets, the BFC instruction
331 // should always be available.
332 assert(CanUseBFC);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000333 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
334 .addReg(Reg, RegState::Kill)
335 .addImm(~AlignMask)
336 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000337 }
338}
339
Matthias Braun8aaa3682017-04-19 21:11:44 +0000340/// We need the offset of the frame pointer relative to other MachineFrameInfo
341/// offsets which are encoded relative to SP at function begin.
342/// See also emitPrologue() for how the FP is set up.
343/// Unfortunately we cannot determine this value in determineCalleeSaves() yet
344/// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
345/// this to produce a conservative estimate that we check in an assert() later.
346static int getMaxFPOffset(const Function &F, const ARMFunctionInfo &AFI) {
Eli Friedmanab1d73e2019-06-26 23:46:51 +0000347 // For Thumb1, push.w isn't available, so the first push will always push
348 // r7 and lr onto the stack first.
349 if (AFI.isThumb1OnlyFunction())
350 return -AFI.getArgRegsSaveSize() - (2 * 4);
Matthias Braun8aaa3682017-04-19 21:11:44 +0000351 // This is a conservative estimation: Assume the frame pointer being r7 and
352 // pc("r15") up to r8 getting spilled before (= 8 registers).
353 return -AFI.getArgRegsSaveSize() - (8 * 4);
354}
355
Quentin Colombet61b305e2015-05-05 17:38:16 +0000356void ARMFrameLowering::emitPrologue(MachineFunction &MF,
357 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000358 MachineBasicBlock::iterator MBBI = MBB.begin();
Matthias Braun941a7052016-07-28 18:40:00 +0000359 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000360 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000361 MachineModuleInfo &MMI = MF.getMMI();
362 MCContext &Context = MMI.getContext();
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000363 const TargetMachine &TM = MF.getTarget();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000364 const MCRegisterInfo *MRI = Context.getRegisterInfo();
Eric Christopher1b21f002015-01-29 00:19:33 +0000365 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
366 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000367 assert(!AFI->isThumb1OnlyFunction() &&
368 "This emitPrologue does not support Thumb1!");
369 bool isARM = !AFI->isThumbFunction();
Eric Christopher1b21f002015-01-29 00:19:33 +0000370 unsigned Align = STI.getFrameLowering()->getStackAlignment();
Tim Northover775aaeb2015-11-05 21:54:58 +0000371 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000372 unsigned NumBytes = MFI.getStackSize();
373 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000374
375 // Debug location must be unknown since the first debug location is used
376 // to determine the end of the prologue.
377 DebugLoc dl;
Fangrui Songf78650a2018-07-30 19:41:25 +0000378
Daniel Sanders0c476112019-08-15 19:22:08 +0000379 Register FramePtr = RegInfo->getFrameRegister(MF);
Tim Northover775aaeb2015-11-05 21:54:58 +0000380
381 // Determine the sizes of each callee-save spill areas and record which frame
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000382 // belongs to which callee-save spill areas.
383 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
384 int FramePtrSpillFI = 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000385 int D8SpillFI = 0;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000386
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000387 // All calls are tail calls in GHC calling conv, and functions have no
388 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000389 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000390 return;
391
Tim Northover603d3162014-11-14 22:45:33 +0000392 StackAdjustingInsts DefCFAOffsetCandidates;
Sergey Dmitrouk3cc62b32015-04-08 10:10:12 +0000393 bool HasFP = hasFP(MF);
Tim Northover603d3162014-11-14 22:45:33 +0000394
Oliver Stannardd55e1152014-03-05 15:25:27 +0000395 // Allocate the vararg register save area.
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000396 if (ArgRegsSaveSize) {
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000397 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000398 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000399 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000400 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000401
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000402 if (!AFI->hasStackFrame() &&
403 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000404 if (NumBytes - ArgRegsSaveSize != 0) {
405 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000406 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000407 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
408 NumBytes - ArgRegsSaveSize, true);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000409 }
Matthias Braunf23ef432016-11-30 23:48:42 +0000410 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000411 return;
412 }
413
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000414 // Determine spill area sizes.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000415 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
416 unsigned Reg = CSI[i].getReg();
417 int FI = CSI[i].getFrameIdx();
418 switch (Reg) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000419 case ARM::R8:
420 case ARM::R9:
421 case ARM::R10:
422 case ARM::R11:
423 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000424 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000425 GPRCS2Size += 4;
426 break;
427 }
Justin Bognerb03fd122016-08-17 05:10:15 +0000428 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +0000429 case ARM::R0:
430 case ARM::R1:
431 case ARM::R2:
432 case ARM::R3:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000433 case ARM::R4:
434 case ARM::R5:
435 case ARM::R6:
436 case ARM::R7:
437 case ARM::LR:
438 if (Reg == FramePtr)
439 FramePtrSpillFI = FI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000440 GPRCS1Size += 4;
441 break;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000442 default:
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000443 // This is a DPR. Exclude the aligned DPRCS2 spills.
444 if (Reg == ARM::D8)
445 D8SpillFI = FI;
Tim Northoverc9432eb2013-11-04 23:04:15 +0000446 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000447 DPRCSSize += 8;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000448 }
449 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000450
Eric Christopherb006fc92010-11-18 19:40:05 +0000451 // Move past area 1.
Tim Northover603d3162014-11-14 22:45:33 +0000452 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
453 if (GPRCS1Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000454 GPRCS1Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000455 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
456 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000457
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000458 // Determine starting offsets of spill areas.
Tim Northover228c9432014-11-05 00:27:13 +0000459 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
460 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
461 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
462 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
463 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
Tim Northover93bcc662013-11-08 17:18:07 +0000464 int FramePtrOffsetInPush = 0;
465 if (HasFP) {
Matthias Braun8aaa3682017-04-19 21:11:44 +0000466 int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
Matthias Braunf1caa282017-12-15 22:22:58 +0000467 assert(getMaxFPOffset(MF.getFunction(), *AFI) <= FPOffset &&
Matthias Braun8aaa3682017-04-19 21:11:44 +0000468 "Max FP estimation is wrong");
469 FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize;
Matthias Braun941a7052016-07-28 18:40:00 +0000470 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000471 NumBytes);
Tim Northover93bcc662013-11-08 17:18:07 +0000472 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000473 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
474 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
475 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
476
Tim Northoverc9432eb2013-11-04 23:04:15 +0000477 // Move past area 2.
Tim Northover603d3162014-11-14 22:45:33 +0000478 if (GPRCS2Size > 0) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000479 GPRCS2Push = LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000480 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
481 }
Tim Northoverc9432eb2013-11-04 23:04:15 +0000482
Tim Northover228c9432014-11-05 00:27:13 +0000483 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
484 // .cfi_offset operations will reflect that.
485 if (DPRGapSize) {
486 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
Duncan P. N. Exon Smithec083b52016-08-17 00:53:04 +0000487 if (LastPush != MBB.end() &&
488 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
Tim Northover603d3162014-11-14 22:45:33 +0000489 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
490 else {
Tim Northover228c9432014-11-05 00:27:13 +0000491 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
492 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000493 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
494 }
Tim Northover228c9432014-11-05 00:27:13 +0000495 }
496
Eric Christopherb006fc92010-11-18 19:40:05 +0000497 // Move past area 3.
Evan Cheng70d29632011-02-25 00:24:46 +0000498 if (DPRCSSize > 0) {
Evan Cheng70d29632011-02-25 00:24:46 +0000499 // Since vpush register list cannot have gaps, there may be multiple vpush
Evan Chenga921dc52011-02-25 01:29:29 +0000500 // instructions in the prologue.
Matthias Braun5d01e702017-11-28 01:17:52 +0000501 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000502 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
Tim Northover93bcc662013-11-08 17:18:07 +0000503 LastPush = MBBI++;
Tim Northover603d3162014-11-14 22:45:33 +0000504 }
Evan Cheng70d29632011-02-25 00:24:46 +0000505 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000506
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000507 // Move past the aligned DPRCS2 area.
508 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
509 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
510 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
511 // leaves the stack pointer pointing to the DPRCS2 area.
512 //
513 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
Matthias Braun941a7052016-07-28 18:40:00 +0000514 NumBytes += MFI.getObjectOffset(D8SpillFI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000515 } else
516 NumBytes = DPRCSOffset;
517
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000518 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
519 uint32_t NumWords = NumBytes >> 2;
520
521 if (NumWords < 65536)
Diana Picus4f8c3e12017-01-13 09:37:56 +0000522 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
523 .addImm(NumWords)
524 .setMIFlags(MachineInstr::FrameSetup)
525 .add(predOps(ARMCC::AL));
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000526 else
527 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000528 .addImm(NumWords)
529 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000530
531 switch (TM.getCodeModel()) {
David Green9dd1d452018-08-22 11:31:39 +0000532 case CodeModel::Tiny:
533 llvm_unreachable("Tiny code model not available on ARM.");
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000534 case CodeModel::Small:
535 case CodeModel::Medium:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000536 case CodeModel::Kernel:
537 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000538 .add(predOps(ARMCC::AL))
539 .addExternalSymbol("__chkstk")
540 .addReg(ARM::R4, RegState::Implicit)
541 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000542 break;
543 case CodeModel::Large:
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000544 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
Saleem Abdulrasool985dcf12014-05-07 03:03:31 +0000545 .addExternalSymbol("__chkstk")
546 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool71583032014-05-01 04:19:59 +0000547
Saleem Abdulrasoolacd03382014-05-07 03:03:27 +0000548 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
Diana Picusbd66b7d2017-01-20 08:15:24 +0000549 .add(predOps(ARMCC::AL))
550 .addReg(ARM::R12, RegState::Kill)
551 .addReg(ARM::R4, RegState::Implicit)
552 .setMIFlags(MachineInstr::FrameSetup);
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000553 break;
554 }
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000555
Diana Picus8a73f552017-01-13 10:18:01 +0000556 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
557 .addReg(ARM::SP, RegState::Kill)
558 .addReg(ARM::R4, RegState::Kill)
559 .setMIFlags(MachineInstr::FrameSetup)
560 .add(predOps(ARMCC::AL))
561 .add(condCodeOp());
Saleem Abdulrasool25947c32014-04-30 07:05:07 +0000562 NumBytes = 0;
563 }
564
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000565 if (NumBytes) {
566 // Adjust SP after all the callee-save spills.
Tim Northoverbeb5bcc2015-09-23 22:21:09 +0000567 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000568 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
Tim Northover603d3162014-11-14 22:45:33 +0000569 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
570 else {
Tim Northover93bcc662013-11-08 17:18:07 +0000571 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
572 MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000573 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
574 }
Tim Northover93bcc662013-11-08 17:18:07 +0000575
Evan Chengeb56dca2010-11-22 18:12:04 +0000576 if (HasFP && isARM)
577 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
578 // Note it's not safe to do this in Thumb2 mode because it would have
579 // taken two instructions:
580 // mov sp, r7
581 // sub sp, #24
582 // If an interrupt is taken between the two instructions, then sp is in
583 // an inconsistent state (pointing to the middle of callee-saved area).
584 // The interrupt handler can end up clobbering the registers.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000585 AFI->setShouldRestoreSPFromFP(true);
586 }
587
Tim Northover603d3162014-11-14 22:45:33 +0000588 // Set FP to point to the stack slot that contains the previous FP.
589 // For iOS, FP is R7, which has now been stored in spill area 1.
590 // Otherwise, if this is not iOS, all the callee-saved registers go
591 // into spill area 1, including the FP in R11. In either case, it
592 // is in area one and the adjustment needs to take place just after
593 // that push.
594 if (HasFP) {
595 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000596 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
Tim Northover603d3162014-11-14 22:45:33 +0000597 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
598 dl, TII, FramePtr, ARM::SP,
599 PushSize + FramePtrOffsetInPush,
600 MachineInstr::FrameSetup);
601 if (FramePtrOffsetInPush + PushSize != 0) {
Matthias Braunf23ef432016-11-30 23:48:42 +0000602 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
Tim Northover603d3162014-11-14 22:45:33 +0000603 nullptr, MRI->getDwarfRegNum(FramePtr, true),
604 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
605 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000606 .addCFIIndex(CFIIndex)
607 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000608 } else {
609 unsigned CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +0000610 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
Tim Northover603d3162014-11-14 22:45:33 +0000611 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
612 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000613 .addCFIIndex(CFIIndex)
614 .setMIFlags(MachineInstr::FrameSetup);
Tim Northover603d3162014-11-14 22:45:33 +0000615 }
616 }
617
618 // Now that the prologue's actual instructions are finalised, we can insert
619 // the necessary DWARF cf instructions to describe the situation. Start by
620 // recording where each register ended up:
621 if (GPRCS1Size > 0) {
622 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
623 int CFIIndex;
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000624 for (const auto &Entry : CSI) {
625 unsigned Reg = Entry.getReg();
626 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000627 switch (Reg) {
628 case ARM::R8:
629 case ARM::R9:
630 case ARM::R10:
631 case ARM::R11:
632 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000633 if (STI.splitFramePushPop(MF))
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000634 break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000635 LLVM_FALLTHROUGH;
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000636 case ARM::R0:
637 case ARM::R1:
638 case ARM::R2:
639 case ARM::R3:
640 case ARM::R4:
641 case ARM::R5:
642 case ARM::R6:
643 case ARM::R7:
644 case ARM::LR:
Matthias Braunf23ef432016-11-30 23:48:42 +0000645 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Matthias Braun941a7052016-07-28 18:40:00 +0000646 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000647 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000648 .addCFIIndex(CFIIndex)
649 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000650 break;
651 }
652 }
653 }
654
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000655 if (GPRCS2Size > 0) {
Tim Northover603d3162014-11-14 22:45:33 +0000656 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000657 for (const auto &Entry : CSI) {
658 unsigned Reg = Entry.getReg();
659 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000660 switch (Reg) {
661 case ARM::R8:
662 case ARM::R9:
663 case ARM::R10:
664 case ARM::R11:
665 case ARM::R12:
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000666 if (STI.splitFramePushPop(MF)) {
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000667 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000668 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000669 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000670 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
671 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000672 .addCFIIndex(CFIIndex)
673 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000674 }
675 break;
676 }
677 }
678 }
679
680 if (DPRCSSize > 0) {
681 // Since vpush register list cannot have gaps, there may be multiple vpush
682 // instructions in the prologue.
Tim Northover603d3162014-11-14 22:45:33 +0000683 MachineBasicBlock::iterator Pos = std::next(LastPush);
Jim Grosbachf92e8f52014-04-04 02:10:55 +0000684 for (const auto &Entry : CSI) {
685 unsigned Reg = Entry.getReg();
686 int FI = Entry.getFrameIdx();
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000687 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
688 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
689 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Matthias Braun941a7052016-07-28 18:40:00 +0000690 unsigned Offset = MFI.getObjectOffset(FI);
Matthias Braunf23ef432016-11-30 23:48:42 +0000691 unsigned CFIIndex = MF.addFrameInst(
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000692 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Tim Northover603d3162014-11-14 22:45:33 +0000693 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
Adrian Prantlb9fa9452014-12-16 00:20:49 +0000694 .addCFIIndex(CFIIndex)
695 .setMIFlags(MachineInstr::FrameSetup);
Artyom Skrobovf6830f42014-02-14 17:19:07 +0000696 }
697 }
698 }
699
Tim Northover603d3162014-11-14 22:45:33 +0000700 // Now we can emit descriptions of where the canonical frame address was
701 // throughout the process. If we have a frame pointer, it takes over the job
702 // half-way through, so only the first few .cfi_def_cfa_offset instructions
703 // actually get emitted.
Matthias Braunf23ef432016-11-30 23:48:42 +0000704 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
Tim Northover93bcc662013-11-08 17:18:07 +0000705
Evan Chengeb56dca2010-11-22 18:12:04 +0000706 if (STI.isTargetELF() && hasFP(MF))
Matthias Braun941a7052016-07-28 18:40:00 +0000707 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
708 AFI->getFramePtrSpillOffset());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000709
710 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
711 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
Tim Northover228c9432014-11-05 00:27:13 +0000712 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000713 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
714
715 // If we need dynamic stack realignment, do it here. Be paranoid and make
716 // sure if we also have VLAs, we have a base pointer for frame access.
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +0000717 // If aligned NEON registers were spilled, the stack has already been
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000718 // realigned.
719 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
Matthias Braun941a7052016-07-28 18:40:00 +0000720 unsigned MaxAlign = MFI.getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +0000721 assert(!AFI->isThumb1OnlyFunction());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000722 if (!AFI->isThumbFunction()) {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000723 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
724 false);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000725 } else {
Kristof Beyls933de7a2015-01-08 15:09:14 +0000726 // We cannot use sp as source/dest register here, thus we're using r4 to
727 // perform the calculations. We're emitting the following sequence:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000728 // mov r4, sp
Kristof Beyls933de7a2015-01-08 15:09:14 +0000729 // -- use emitAligningInstructions to produce best sequence to zero
730 // -- out lower bits in r4
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000731 // mov sp, r4
732 // FIXME: It will be better just to find spare register here.
Diana Picus4f8c3e12017-01-13 09:37:56 +0000733 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
734 .addReg(ARM::SP, RegState::Kill)
735 .add(predOps(ARMCC::AL));
Kristof Beyls933de7a2015-01-08 15:09:14 +0000736 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
737 false);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000738 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
739 .addReg(ARM::R4, RegState::Kill)
740 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000741 }
742
743 AFI->setShouldRestoreSPFromFP(true);
744 }
745
746 // If we need a base pointer, set it up here. It's whatever the value
747 // of the stack pointer is at this point. Any variable size objects
748 // will be allocated after this, so we can still use the base pointer
749 // to reference locals.
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000750 // FIXME: Clarify FrameSetup flags here.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000751 if (RegInfo->hasBasePointer(MF)) {
752 if (isARM)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000753 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
754 .addReg(ARM::SP)
755 .add(predOps(ARMCC::AL))
756 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000757 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000758 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
759 .addReg(ARM::SP)
760 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000761 }
762
763 // If the frame has variable sized objects then the epilogue must restore
Eric Christopherd5bbeba2011-01-10 23:10:59 +0000764 // the sp from fp. We can assume there's an FP here since hasFP already
765 // checks for hasVarSizedObjects.
Matthias Braun941a7052016-07-28 18:40:00 +0000766 if (MFI.hasVarSizedObjects())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000767 AFI->setShouldRestoreSPFromFP(true);
768}
769
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000770void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
Bob Wilson657f2272011-01-13 21:10:12 +0000771 MachineBasicBlock &MBB) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000772 MachineFrameInfo &MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000773 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000774 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000775 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +0000776 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000777 assert(!AFI->isThumb1OnlyFunction() &&
778 "This emitEpilogue does not support Thumb1!");
779 bool isARM = !AFI->isThumbFunction();
780
Tim Northover8cda34f2015-03-11 18:54:22 +0000781 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
Matthias Braun941a7052016-07-28 18:40:00 +0000782 int NumBytes = (int)MFI.getStackSize();
Daniel Sanders0c476112019-08-15 19:22:08 +0000783 Register FramePtr = RegInfo->getFrameRegister(MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000784
Jakob Stoklund Olesene3801832012-10-26 21:46:57 +0000785 // All calls are tail calls in GHC calling conv, and functions have no
786 // prologue/epilogue.
Matthias Braunf1caa282017-12-15 22:22:58 +0000787 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
Eric Christopherb3322362012-08-03 00:05:53 +0000788 return;
Quentin Colombet71a71482015-07-20 21:42:14 +0000789
790 // First put ourselves on the first (from top) terminator instructions.
791 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
792 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
Eric Christopherb3322362012-08-03 00:05:53 +0000793
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000794 if (!AFI->hasStackFrame()) {
Oliver Stannardd55e1152014-03-05 15:25:27 +0000795 if (NumBytes - ArgRegsSaveSize != 0)
796 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000797 } else {
798 // Unwind MBBI to point to first LDR / VLDRD.
Craig Topper840beec2014-04-04 05:16:06 +0000799 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000800 if (MBBI != MBB.begin()) {
Tim Northover93bcc662013-11-08 17:18:07 +0000801 do {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000802 --MBBI;
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000803 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
804 if (!isCSRestore(*MBBI, TII, CSRegs))
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000805 ++MBBI;
806 }
807
808 // Move SP to start of FP callee save spill area.
Oliver Stannardd55e1152014-03-05 15:25:27 +0000809 NumBytes -= (ArgRegsSaveSize +
810 AFI->getGPRCalleeSavedArea1Size() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000811 AFI->getGPRCalleeSavedArea2Size() +
Tim Northover228c9432014-11-05 00:27:13 +0000812 AFI->getDPRCalleeSavedGapSize() +
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000813 AFI->getDPRCalleeSavedAreaSize());
814
815 // Reset SP based on frame pointer only if the stack frame extends beyond
816 // frame pointer stack slot or target is ELF and the function has FP.
817 if (AFI->shouldRestoreSPFromFP()) {
818 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
819 if (NumBytes) {
820 if (isARM)
821 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
822 ARMCC::AL, 0, TII);
Evan Chengeb56dca2010-11-22 18:12:04 +0000823 else {
824 // It's not possible to restore SP from FP in a single instruction.
Evan Cheng801d98b2012-01-04 01:55:04 +0000825 // For iOS, this looks like:
Evan Chengeb56dca2010-11-22 18:12:04 +0000826 // mov sp, r7
827 // sub sp, #24
828 // This is bad, if an interrupt is taken after the mov, sp is in an
829 // inconsistent state.
830 // Use the first callee-saved register as a scratch register.
Matthias Braun941a7052016-07-28 18:40:00 +0000831 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
Evan Chengeb56dca2010-11-22 18:12:04 +0000832 "No scratch register to restore SP from FP!");
833 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000834 ARMCC::AL, 0, TII);
Diana Picus4f8c3e12017-01-13 09:37:56 +0000835 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
836 .addReg(ARM::R4)
837 .add(predOps(ARMCC::AL));
Evan Chengeb56dca2010-11-22 18:12:04 +0000838 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000839 } else {
840 // Thumb2 or ARM.
841 if (isARM)
842 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
Diana Picusbd66b7d2017-01-20 08:15:24 +0000843 .addReg(FramePtr)
844 .add(predOps(ARMCC::AL))
845 .add(condCodeOp());
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000846 else
Diana Picus4f8c3e12017-01-13 09:37:56 +0000847 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
848 .addReg(FramePtr)
849 .add(predOps(ARMCC::AL));
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000850 }
Tim Northoverdee86042013-12-02 14:46:26 +0000851 } else if (NumBytes &&
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +0000852 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
853 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000854
Eric Christopherb006fc92010-11-18 19:40:05 +0000855 // Increment past our save areas.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000856 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
Evan Cheng70d29632011-02-25 00:24:46 +0000857 MBBI++;
858 // Since vpop register list cannot have gaps, there may be multiple vpop
859 // instructions in the epilogue.
Duncan P. N. Exon Smith8f44c982016-08-21 00:08:10 +0000860 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
Evan Cheng70d29632011-02-25 00:24:46 +0000861 MBBI++;
862 }
Tim Northover228c9432014-11-05 00:27:13 +0000863 if (AFI->getDPRCalleeSavedGapSize()) {
864 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
865 "unexpected DPR alignment gap");
866 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
867 }
868
Eric Christopherb006fc92010-11-18 19:40:05 +0000869 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
870 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000871 }
872
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +0000873 if (ArgRegsSaveSize)
874 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000875}
Anton Korobeynikov46877782010-11-20 15:59:32 +0000876
Bob Wilson657f2272011-01-13 21:10:12 +0000877/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
878/// debug info. It's the same as what we use for resolving the code-gen
879/// references for now. FIXME: This can go wrong when references are
880/// SP-relative and simple call frames aren't used.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000881int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000882ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
Bob Wilson657f2272011-01-13 21:10:12 +0000883 unsigned &FrameReg) const {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000884 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
885}
886
887int
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000888ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
Evan Chengc0d20042011-04-22 01:42:52 +0000889 int FI, unsigned &FrameReg,
Bob Wilson657f2272011-01-13 21:10:12 +0000890 int SPAdj) const {
Matthias Braun941a7052016-07-28 18:40:00 +0000891 const MachineFrameInfo &MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000892 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +0000893 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +0000894 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +0000895 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +0000896 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
Matthias Braun941a7052016-07-28 18:40:00 +0000897 bool isFixed = MFI.isFixedObjectIndex(FI);
Anton Korobeynikov46877782010-11-20 15:59:32 +0000898
899 FrameReg = ARM::SP;
900 Offset += SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000901
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000902 // SP can move around if there are allocas. We may also lose track of SP
903 // when emergency spilling inside a non-reserved call frame setup.
Bob Wilsonca690322012-03-20 19:28:22 +0000904 bool hasMovingSP = !hasReservedCallFrame(MF);
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000905
Anton Korobeynikov46877782010-11-20 15:59:32 +0000906 // When dynamically realigning the stack, use the frame pointer for
907 // parameters, and the stack/base pointer for locals.
908 if (RegInfo->needsStackRealignment(MF)) {
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +0000909 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000910 if (isFixed) {
911 FrameReg = RegInfo->getFrameRegister(MF);
912 Offset = FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000913 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000914 assert(RegInfo->hasBasePointer(MF) &&
915 "VLAs and dynamic stack alignment, but missing base pointer!");
916 FrameReg = RegInfo->getBaseRegister();
Tim Northover4bf394b2018-12-07 13:43:55 +0000917 Offset -= SPAdj;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000918 }
919 return Offset;
920 }
921
922 // If there is a frame pointer, use it when we can.
923 if (hasFP(MF) && AFI->hasStackFrame()) {
924 // Use frame pointer to reference fixed objects. Use it for locals if
925 // there are VLAs (and thus the SP isn't reliable as a base).
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000926 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000927 FrameReg = RegInfo->getFrameRegister(MF);
928 return FPOffset;
Jakob Stoklund Olesen92c15b22012-02-28 01:15:01 +0000929 } else if (hasMovingSP) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000930 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
Anton Korobeynikov46877782010-11-20 15:59:32 +0000931 if (AFI->isThumb2Function()) {
Evan Chengc0d20042011-04-22 01:42:52 +0000932 // Try to use the frame pointer if we can, else use the base pointer
933 // since it's available. This is handy for the emergency spill slot, in
934 // particular.
Anton Korobeynikov46877782010-11-20 15:59:32 +0000935 if (FPOffset >= -255 && FPOffset < 0) {
936 FrameReg = RegInfo->getFrameRegister(MF);
937 return FPOffset;
938 }
Evan Chengc0d20042011-04-22 01:42:52 +0000939 }
Momchil Velikov505614b2018-03-02 15:47:14 +0000940 } else if (AFI->isThumbFunction()) {
941 // Prefer SP to base pointer, if the offset is suitably aligned and in
942 // range as the effective range of the immediate offset is bigger when
943 // basing off SP.
Andrew Trickf7ecc162011-08-25 17:40:54 +0000944 // Use add <rd>, sp, #<imm8>
Evan Chengc0d20042011-04-22 01:42:52 +0000945 // ldr <rd>, [sp, #<imm8>]
Evan Chengc0d20042011-04-22 01:42:52 +0000946 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
947 return Offset;
Anton Korobeynikov46877782010-11-20 15:59:32 +0000948 // In Thumb2 mode, the negative offset is very limited. Try to avoid
Evan Chengc0d20042011-04-22 01:42:52 +0000949 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
Momchil Velikov505614b2018-03-02 15:47:14 +0000950 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000951 FrameReg = RegInfo->getFrameRegister(MF);
952 return FPOffset;
953 }
954 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
955 // Otherwise, use SP or FP, whichever is closer to the stack slot.
956 FrameReg = RegInfo->getFrameRegister(MF);
957 return FPOffset;
958 }
959 }
960 // Use the base pointer if we have one.
Eli Friedmanab1d73e2019-06-26 23:46:51 +0000961 // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
962 // That can happen if we forced a base pointer for a large call frame.
963 if (RegInfo->hasBasePointer(MF)) {
Anton Korobeynikov46877782010-11-20 15:59:32 +0000964 FrameReg = RegInfo->getBaseRegister();
Eli Friedmanab1d73e2019-06-26 23:46:51 +0000965 Offset -= SPAdj;
966 }
Anton Korobeynikov46877782010-11-20 15:59:32 +0000967 return Offset;
968}
969
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000970void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +0000971 MachineBasicBlock::iterator MI,
972 const std::vector<CalleeSavedInfo> &CSI,
973 unsigned StmOpc, unsigned StrOpc,
974 bool NoGap,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000975 bool(*Func)(unsigned, bool),
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000976 unsigned NumAlignedDPRCS2Regs,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +0000977 unsigned MIFlags) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000978 MachineFunction &MF = *MBB.getParent();
Tim Northover775aaeb2015-11-05 21:54:58 +0000979 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +0000980 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Tim Northover775aaeb2015-11-05 21:54:58 +0000981
982 DebugLoc DL;
983
Eugene Zelenko076468c2017-09-20 21:35:51 +0000984 using RegAndKill = std::pair<unsigned, bool>;
985
Tim Northover46a6f0f2016-11-14 20:28:24 +0000986 SmallVector<RegAndKill, 4> Regs;
Tim Northover775aaeb2015-11-05 21:54:58 +0000987 unsigned i = CSI.size();
Evan Cheng775ead32010-12-07 23:08:38 +0000988 while (i != 0) {
989 unsigned LastReg = 0;
990 for (; i != 0; --i) {
991 unsigned Reg = CSI[i-1].getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +0000992 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +0000993
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +0000994 // D-registers in the aligned area DPRCS2 are NOT spilled here.
995 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
996 continue;
997
Matthias Braun0dba4e32017-05-31 01:21:30 +0000998 const MachineRegisterInfo &MRI = MF.getRegInfo();
999 bool isLiveIn = MRI.isLiveIn(Reg);
1000 if (!isLiveIn && !MRI.isReserved(Reg))
Evan Cheng775ead32010-12-07 23:08:38 +00001001 MBB.addLiveIn(Reg);
Eric Christopher2a2e65c2010-12-09 01:57:45 +00001002 // If NoGap is true, push consecutive registers and then leave the rest
Evan Cheng9d54ae62010-12-08 06:29:02 +00001003 // for other instructions. e.g.
Eric Christopher2a2e65c2010-12-09 01:57:45 +00001004 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
Evan Cheng9d54ae62010-12-08 06:29:02 +00001005 if (NoGap && LastReg && LastReg != Reg-1)
1006 break;
Evan Cheng775ead32010-12-07 23:08:38 +00001007 LastReg = Reg;
Matthias Braun707e02c2016-04-13 21:43:25 +00001008 // Do not set a kill flag on values that are also marked as live-in. This
1009 // happens with the @llvm-returnaddress intrinsic and with arguments
1010 // passed in callee saved registers.
1011 // Omitting the kill flags is conservatively correct even if the live-in
1012 // is not used after all.
1013 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001014 }
1015
Jim Grosbach5fccad82010-12-09 18:31:13 +00001016 if (Regs.empty())
1017 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001018
Fangrui Song0cac7262018-09-27 02:13:45 +00001019 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +00001020 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1021 });
1022
Jim Grosbach5fccad82010-12-09 18:31:13 +00001023 if (Regs.size() > 1 || StrOpc== 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001024 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1025 .addReg(ARM::SP)
1026 .setMIFlags(MIFlags)
1027 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001028 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1029 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
Jim Grosbach5fccad82010-12-09 18:31:13 +00001030 } else if (Regs.size() == 1) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001031 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1032 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1033 .addReg(ARM::SP)
1034 .setMIFlags(MIFlags)
1035 .addImm(-4)
1036 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001037 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001038 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001039
1040 // Put any subsequent vpush instructions before this one: they will refer to
1041 // higher register numbers so need to be pushed first in order to preserve
1042 // monotonicity.
Quentin Colombet71a71482015-07-20 21:42:14 +00001043 if (MI != MBB.begin())
1044 --MI;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001045 }
Evan Cheng775ead32010-12-07 23:08:38 +00001046}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001047
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001048void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001049 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001050 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001051 unsigned LdmOpc, unsigned LdrOpc,
1052 bool isVarArg, bool NoGap,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001053 bool(*Func)(unsigned, bool),
1054 unsigned NumAlignedDPRCS2Regs) const {
Evan Cheng775ead32010-12-07 23:08:38 +00001055 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001056 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Tim Northover46a6f0f2016-11-14 20:28:24 +00001057 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
Evan Cheng775ead32010-12-07 23:08:38 +00001058 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet71a71482015-07-20 21:42:14 +00001059 DebugLoc DL;
1060 bool isTailCall = false;
1061 bool isInterrupt = false;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001062 bool isTrap = false;
Quentin Colombet71a71482015-07-20 21:42:14 +00001063 if (MBB.end() != MI) {
1064 DL = MI->getDebugLoc();
1065 unsigned RetOpcode = MI->getOpcode();
1066 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1067 isInterrupt =
1068 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001069 isTrap =
1070 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1071 RetOpcode == ARM::tTRAP;
Quentin Colombet71a71482015-07-20 21:42:14 +00001072 }
Evan Cheng775ead32010-12-07 23:08:38 +00001073
1074 SmallVector<unsigned, 4> Regs;
1075 unsigned i = CSI.size();
1076 while (i != 0) {
1077 unsigned LastReg = 0;
1078 bool DeleteRet = false;
1079 for (; i != 0; --i) {
Matthias Braun51687912017-09-28 23:12:06 +00001080 CalleeSavedInfo &Info = CSI[i-1];
1081 unsigned Reg = Info.getReg();
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001082 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
Evan Cheng775ead32010-12-07 23:08:38 +00001083
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001084 // The aligned reloads from area DPRCS2 are not inserted here.
1085 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1086 continue;
1087
Tim Northoverd8407452013-10-01 14:33:28 +00001088 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
Oleg Ranevskyy6389dd92015-10-23 17:17:59 +00001089 !isTrap && STI.hasV5TOps()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00001090 if (MBB.succ_empty()) {
1091 Reg = ARM::PC;
Thomas Preud'hommec699eaa2018-03-05 11:49:00 +00001092 // Fold the return instruction into the LDM.
Quentin Colombet71a71482015-07-20 21:42:14 +00001093 DeleteRet = true;
1094 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
Matthias Braun51687912017-09-28 23:12:06 +00001095 // We 'restore' LR into PC so it is not live out of the return block:
1096 // Clear Restored bit.
1097 Info.setRestored(false);
Quentin Colombet71a71482015-07-20 21:42:14 +00001098 } else
1099 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Evan Cheng775ead32010-12-07 23:08:38 +00001100 }
1101
Evan Cheng9d54ae62010-12-08 06:29:02 +00001102 // If NoGap is true, pop consecutive registers and then leave the rest
1103 // for other instructions. e.g.
1104 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1105 if (NoGap && LastReg && LastReg != Reg-1)
1106 break;
1107
Evan Cheng775ead32010-12-07 23:08:38 +00001108 LastReg = Reg;
1109 Regs.push_back(Reg);
1110 }
1111
Jim Grosbach5fccad82010-12-09 18:31:13 +00001112 if (Regs.empty())
1113 continue;
Tim Northover46a6f0f2016-11-14 20:28:24 +00001114
Fangrui Song0cac7262018-09-27 02:13:45 +00001115 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
Tim Northover46a6f0f2016-11-14 20:28:24 +00001116 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1117 });
1118
Jim Grosbach5fccad82010-12-09 18:31:13 +00001119 if (Regs.size() > 1 || LdrOpc == 0) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00001120 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1121 .addReg(ARM::SP)
1122 .add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001123 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1124 MIB.addReg(Regs[i], getDefRegState(true));
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001125 if (DeleteRet) {
1126 if (MI != MBB.end()) {
1127 MIB.copyImplicitOps(*MI);
1128 MI->eraseFromParent();
1129 }
Andrew Trick6446bf72011-08-25 17:50:53 +00001130 }
Evan Cheng775ead32010-12-07 23:08:38 +00001131 MI = MIB;
Jim Grosbach5fccad82010-12-09 18:31:13 +00001132 } else if (Regs.size() == 1) {
1133 // If we adjusted the reg to PC from LR above, switch it back here. We
1134 // only do that for LDM.
1135 if (Regs[0] == ARM::PC)
1136 Regs[0] = ARM::LR;
1137 MachineInstrBuilder MIB =
1138 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1139 .addReg(ARM::SP, RegState::Define)
1140 .addReg(ARM::SP);
1141 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1142 // that refactoring is complete (eventually).
Owen Anderson2aedba62011-07-26 20:54:26 +00001143 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
Jim Grosbach5fccad82010-12-09 18:31:13 +00001144 MIB.addReg(0);
1145 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1146 } else
1147 MIB.addImm(4);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001148 MIB.add(predOps(ARMCC::AL));
Evan Cheng775ead32010-12-07 23:08:38 +00001149 }
Jim Grosbach5fccad82010-12-09 18:31:13 +00001150 Regs.clear();
Tim Northover3cccc452014-03-12 11:29:23 +00001151
1152 // Put any subsequent vpop instructions after this one: they will refer to
1153 // higher register numbers so need to be popped afterwards.
Quentin Colombet71a71482015-07-20 21:42:14 +00001154 if (MI != MBB.end())
1155 ++MI;
Evan Chengc27c9562010-12-07 19:59:34 +00001156 }
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001157}
1158
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001159/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
Jakob Stoklund Olesen103318e2011-12-24 04:17:01 +00001160/// starting from d8. Also insert stack realignment code and leave the stack
1161/// pointer pointing to the d8 spill slot.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001162static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1163 MachineBasicBlock::iterator MI,
1164 unsigned NumAlignedDPRCS2Regs,
1165 const std::vector<CalleeSavedInfo> &CSI,
1166 const TargetRegisterInfo *TRI) {
1167 MachineFunction &MF = *MBB.getParent();
1168 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001169 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001170 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Matthias Braun941a7052016-07-28 18:40:00 +00001171 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001172
1173 // Mark the D-register spill slots as properly aligned. Since MFI computes
1174 // stack slot layout backwards, this can actually mean that the d-reg stack
1175 // slot offsets can be wrong. The offset for d8 will always be correct.
1176 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1177 unsigned DNum = CSI[i].getReg() - ARM::D8;
Tim Northovere0ccdc62015-10-28 22:46:43 +00001178 if (DNum > NumAlignedDPRCS2Regs - 1)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001179 continue;
1180 int FI = CSI[i].getFrameIdx();
1181 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1182 // registers will be 8-byte aligned.
1183 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1184
1185 // The stack slot for D8 needs to be maximally aligned because this is
1186 // actually the point where we align the stack pointer. MachineFrameInfo
1187 // computes all offsets relative to the incoming stack pointer which is a
1188 // bit weird when realigning the stack. Any extra padding for this
1189 // over-alignment is not realized because the code inserted below adjusts
1190 // the stack pointer by numregs * 8 before aligning the stack pointer.
1191 if (DNum == 0)
1192 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1193 }
1194
1195 // Move the stack pointer to the d8 spill slot, and align it at the same
1196 // time. Leave the stack slot address in the scratch register r4.
1197 //
1198 // sub r4, sp, #numregs * 8
1199 // bic r4, r4, #align - 1
1200 // mov sp, r4
1201 //
1202 bool isThumb = AFI->isThumbFunction();
1203 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1204 AFI->setShouldRestoreSPFromFP(true);
1205
1206 // sub r4, sp, #numregs * 8
1207 // The immediate is <= 64, so it doesn't need any special encoding.
1208 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
Diana Picus8a73f552017-01-13 10:18:01 +00001209 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1210 .addReg(ARM::SP)
1211 .addImm(8 * NumAlignedDPRCS2Regs)
1212 .add(predOps(ARMCC::AL))
1213 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001214
Matthias Braun941a7052016-07-28 18:40:00 +00001215 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
Kristof Beyls933de7a2015-01-08 15:09:14 +00001216 // We must set parameter MustBeSingleInstruction to true, since
1217 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1218 // stack alignment. Luckily, this can always be done since all ARM
1219 // architecture versions that support Neon also support the BFC
1220 // instruction.
1221 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001222
1223 // mov sp, r4
1224 // The stack pointer must be adjusted before spilling anything, otherwise
1225 // the stack slots could be clobbered by an interrupt handler.
1226 // Leave r4 live, it is used below.
1227 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1228 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001229 .addReg(ARM::R4)
1230 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001231 if (!isThumb)
Diana Picus8a73f552017-01-13 10:18:01 +00001232 MIB.add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001233
1234 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1235 // r4 holds the stack slot address.
1236 unsigned NextReg = ARM::D8;
1237
1238 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1239 // The writeback is only needed when emitting two vst1.64 instructions.
1240 if (NumAlignedDPRCS2Regs >= 6) {
1241 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001242 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001243 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001244 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1245 .addReg(ARM::R4, RegState::Kill)
1246 .addImm(16)
1247 .addReg(NextReg)
1248 .addReg(SupReg, RegState::ImplicitKill)
1249 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001250 NextReg += 4;
1251 NumAlignedDPRCS2Regs -= 4;
1252 }
1253
1254 // We won't modify r4 beyond this point. It currently points to the next
1255 // register to be spilled.
1256 unsigned R4BaseReg = NextReg;
1257
1258 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1259 if (NumAlignedDPRCS2Regs >= 4) {
1260 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001261 &ARM::QQPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001262 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001263 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1264 .addReg(ARM::R4)
1265 .addImm(16)
1266 .addReg(NextReg)
1267 .addReg(SupReg, RegState::ImplicitKill)
1268 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001269 NextReg += 4;
1270 NumAlignedDPRCS2Regs -= 4;
1271 }
1272
1273 // 16-byte aligned vst1.64 with 2 d-regs.
1274 if (NumAlignedDPRCS2Regs >= 2) {
1275 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001276 &ARM::QPRRegClass);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001277 MBB.addLiveIn(SupReg);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001278 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1279 .addReg(ARM::R4)
1280 .addImm(16)
1281 .addReg(SupReg)
1282 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001283 NextReg += 2;
1284 NumAlignedDPRCS2Regs -= 2;
1285 }
1286
1287 // Finally, use a vanilla vstr.64 for the odd last register.
1288 if (NumAlignedDPRCS2Regs) {
1289 MBB.addLiveIn(NextReg);
1290 // vstr.64 uses addrmode5 which has an offset scale of 4.
Diana Picus4f8c3e12017-01-13 09:37:56 +00001291 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1292 .addReg(NextReg)
1293 .addReg(ARM::R4)
1294 .addImm((NextReg - R4BaseReg) * 2)
1295 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001296 }
1297
1298 // The last spill instruction inserted should kill the scratch register r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001299 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001300}
1301
1302/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1303/// iterator to the following instruction.
1304static MachineBasicBlock::iterator
1305skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1306 unsigned NumAlignedDPRCS2Regs) {
1307 // sub r4, sp, #numregs * 8
1308 // bic r4, r4, #align - 1
1309 // mov sp, r4
1310 ++MI; ++MI; ++MI;
1311 assert(MI->mayStore() && "Expecting spill instruction");
1312
1313 // These switches all fall through.
1314 switch(NumAlignedDPRCS2Regs) {
1315 case 7:
1316 ++MI;
1317 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001318 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001319 default:
1320 ++MI;
1321 assert(MI->mayStore() && "Expecting spill instruction");
Florian Hahndb479522017-07-27 14:37:17 +00001322 LLVM_FALLTHROUGH;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001323 case 1:
1324 case 2:
1325 case 4:
1326 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1327 ++MI;
1328 }
1329 return MI;
1330}
1331
1332/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1333/// starting from d8. These instructions are assumed to execute while the
1334/// stack is still aligned, unlike the code inserted by emitPopInst.
1335static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1336 MachineBasicBlock::iterator MI,
1337 unsigned NumAlignedDPRCS2Regs,
1338 const std::vector<CalleeSavedInfo> &CSI,
1339 const TargetRegisterInfo *TRI) {
1340 MachineFunction &MF = *MBB.getParent();
1341 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Quentin Colombet5084e442015-10-15 00:41:26 +00001342 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
Eric Christopherfc6de422014-08-05 02:39:49 +00001343 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001344
1345 // Find the frame index assigned to d8.
1346 int D8SpillFI = 0;
1347 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1348 if (CSI[i].getReg() == ARM::D8) {
1349 D8SpillFI = CSI[i].getFrameIdx();
1350 break;
1351 }
1352
1353 // Materialize the address of the d8 spill slot into the scratch register r4.
1354 // This can be fairly complicated if the stack frame is large, so just use
1355 // the normal frame index elimination mechanism to do it. This code runs as
1356 // the initial part of the epilog where the stack and base pointers haven't
1357 // been changed yet.
1358 bool isThumb = AFI->isThumbFunction();
1359 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1360
1361 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
Diana Picus8a73f552017-01-13 10:18:01 +00001362 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1363 .addFrameIndex(D8SpillFI)
1364 .addImm(0)
1365 .add(predOps(ARMCC::AL))
1366 .add(condCodeOp());
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001367
1368 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1369 unsigned NextReg = ARM::D8;
1370
1371 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1372 if (NumAlignedDPRCS2Regs >= 6) {
1373 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001374 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001375 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1376 .addReg(ARM::R4, RegState::Define)
1377 .addReg(ARM::R4, RegState::Kill)
1378 .addImm(16)
1379 .addReg(SupReg, RegState::ImplicitDefine)
1380 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001381 NextReg += 4;
1382 NumAlignedDPRCS2Regs -= 4;
1383 }
1384
1385 // We won't modify r4 beyond this point. It currently points to the next
1386 // register to be spilled.
1387 unsigned R4BaseReg = NextReg;
1388
1389 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1390 if (NumAlignedDPRCS2Regs >= 4) {
1391 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001392 &ARM::QQPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001393 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1394 .addReg(ARM::R4)
1395 .addImm(16)
1396 .addReg(SupReg, RegState::ImplicitDefine)
1397 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001398 NextReg += 4;
1399 NumAlignedDPRCS2Regs -= 4;
1400 }
1401
1402 // 16-byte aligned vld1.64 with 2 d-regs.
1403 if (NumAlignedDPRCS2Regs >= 2) {
1404 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
Craig Topperc7242e02012-04-20 07:30:17 +00001405 &ARM::QPRRegClass);
Diana Picus4f8c3e12017-01-13 09:37:56 +00001406 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1407 .addReg(ARM::R4)
1408 .addImm(16)
1409 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001410 NextReg += 2;
1411 NumAlignedDPRCS2Regs -= 2;
1412 }
1413
1414 // Finally, use a vanilla vldr.64 for the remaining odd register.
1415 if (NumAlignedDPRCS2Regs)
Diana Picus4f8c3e12017-01-13 09:37:56 +00001416 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1417 .addReg(ARM::R4)
1418 .addImm(2 * (NextReg - R4BaseReg))
1419 .add(predOps(ARMCC::AL));
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001420
1421 // Last store kills r4.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001422 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001423}
1424
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001425bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001426 MachineBasicBlock::iterator MI,
1427 const std::vector<CalleeSavedInfo> &CSI,
1428 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001429 if (CSI.empty())
1430 return false;
1431
1432 MachineFunction &MF = *MBB.getParent();
1433 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001434
1435 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001436 unsigned PushOneOpc = AFI->isThumbFunction() ?
1437 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001438 unsigned FltOpc = ARM::VSTMDDB_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001439 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1440 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001441 MachineInstr::FrameSetup);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001442 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
Anton Korobeynikove7410dd2011-03-05 18:43:32 +00001443 MachineInstr::FrameSetup);
1444 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001445 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1446
1447 // The code above does not insert spill code for the aligned DPRCS2 registers.
1448 // The stack realignment code will be inserted between the push instructions
1449 // and these spills.
1450 if (NumAlignedDPRCS2Regs)
1451 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001452
1453 return true;
1454}
1455
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001456bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Bob Wilson657f2272011-01-13 21:10:12 +00001457 MachineBasicBlock::iterator MI,
Krzysztof Parzyszekbea30c62017-08-10 16:17:32 +00001458 std::vector<CalleeSavedInfo> &CSI,
Bob Wilson657f2272011-01-13 21:10:12 +00001459 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001460 if (CSI.empty())
1461 return false;
1462
1463 MachineFunction &MF = *MBB.getParent();
1464 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001465 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001466 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1467
1468 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1469 // registers. Do that here instead.
1470 if (NumAlignedDPRCS2Regs)
1471 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001472
1473 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
Jim Grosbach05dec8b12011-09-02 18:46:15 +00001474 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001475 unsigned FltOpc = ARM::VLDMDIA_UPD;
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001476 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1477 NumAlignedDPRCS2Regs);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001478 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001479 &isARMArea2Register, 0);
Jim Grosbach5fccad82010-12-09 18:31:13 +00001480 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001481 &isARMArea1Register, 0);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001482
1483 return true;
1484}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001485
1486// FIXME: Make generic?
Eli Friedman2596e8b2019-03-19 21:48:08 +00001487static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
1488 const ARMBaseInstrInfo &TII) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001489 unsigned FnSize = 0;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001490 for (auto &MBB : MF) {
1491 for (auto &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +00001492 FnSize += TII.getInstSizeInBytes(MI);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001493 }
Eli Friedman2596e8b2019-03-19 21:48:08 +00001494 if (MF.getJumpTableInfo())
1495 for (auto &Table: MF.getJumpTableInfo()->getJumpTables())
1496 FnSize += Table.MBBs.size() * 4;
1497 FnSize += MF.getConstantPool()->getConstants().size() * 4;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001498 return FnSize;
1499}
1500
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001501/// estimateRSStackSizeLimit - Look at each instruction that references stack
1502/// frames and return the stack size limit beyond which some of these
1503/// instructions will require a scratch register during their expansion later.
1504// FIXME: Move to TII?
1505static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
David Green1ff95532019-09-17 12:58:51 +00001506 const TargetFrameLowering *TFI,
1507 bool &HasNonSPFrameIndex) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001508 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
David Green1ff95532019-09-17 12:58:51 +00001509 const ARMBaseInstrInfo &TII =
1510 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1511 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001512 unsigned Limit = (1 << 12) - 1;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001513 for (auto &MBB : MF) {
1514 for (auto &MI : MBB) {
David Green22a22092019-09-17 15:23:09 +00001515 if (MI.isDebugInstr())
1516 continue;
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001517 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1518 if (!MI.getOperand(i).isFI())
1519 continue;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001520
1521 // When using ADDri to get the address of a stack object, 255 is the
1522 // largest offset guaranteed to fit in the immediate offset.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001523 if (MI.getOpcode() == ARM::ADDri) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001524 Limit = std::min(Limit, (1U << 8) - 1);
1525 break;
1526 }
David Green22a22092019-09-17 15:23:09 +00001527 // t2ADDri will not require an extra register, it can reuse the
1528 // destination.
1529 if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
1530 break;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001531
David Green1ff95532019-09-17 12:58:51 +00001532 const MCInstrDesc &MCID = MI.getDesc();
1533 const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF);
1534 if (RegClass && !RegClass->contains(ARM::SP))
1535 HasNonSPFrameIndex = true;
1536
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001537 // Otherwise check the addressing mode.
Jim Grosbachf92e8f52014-04-04 02:10:55 +00001538 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
David Green22a22092019-09-17 15:23:09 +00001539 case ARMII::AddrMode_i12:
1540 case ARMII::AddrMode2:
1541 // Default 12 bit limit.
1542 break;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001543 case ARMII::AddrMode3:
1544 case ARMII::AddrModeT2_i8:
1545 Limit = std::min(Limit, (1U << 8) - 1);
1546 break;
David Green22a22092019-09-17 15:23:09 +00001547 case ARMII::AddrMode5FP16:
1548 Limit = std::min(Limit, ((1U << 8) - 1) * 2);
1549 break;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001550 case ARMII::AddrMode5:
1551 case ARMII::AddrModeT2_i8s4:
Tim Northoverbb7d7b32018-09-07 09:21:25 +00001552 case ARMII::AddrModeT2_ldrex:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001553 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1554 break;
1555 case ARMII::AddrModeT2_i12:
1556 // i12 supports only positive offset so these will be converted to
1557 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1558 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1559 Limit = std::min(Limit, (1U << 8) - 1);
1560 break;
1561 case ARMII::AddrMode4:
1562 case ARMII::AddrMode6:
1563 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1564 // immediate offset for stack references.
1565 return 0;
David Green1ff95532019-09-17 12:58:51 +00001566 case ARMII::AddrModeT2_i7:
1567 Limit = std::min(Limit, ((1U << 7) - 1) * 1);
1568 break;
1569 case ARMII::AddrModeT2_i7s2:
1570 Limit = std::min(Limit, ((1U << 7) - 1) * 2);
1571 break;
1572 case ARMII::AddrModeT2_i7s4:
1573 Limit = std::min(Limit, ((1U << 7) - 1) * 4);
1574 break;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001575 default:
David Green22a22092019-09-17 15:23:09 +00001576 llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001577 }
1578 break; // At most one FI per instruction
1579 }
1580 }
1581 }
1582
1583 return Limit;
1584}
1585
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001586// In functions that realign the stack, it can be an advantage to spill the
1587// callee-saved vector registers after realigning the stack. The vst1 and vld1
1588// instructions take alignment hints that can improve performance.
Matthias Braun02564862015-07-14 17:17:13 +00001589static void
1590checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001591 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1592 if (!SpillAlignedNEONRegs)
1593 return;
1594
1595 // Naked functions don't spill callee-saved registers.
Matthias Braunf1caa282017-12-15 22:22:58 +00001596 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001597 return;
1598
1599 // We are planning to use NEON instructions vst1 / vld1.
Eric Christopher1b21f002015-01-29 00:19:33 +00001600 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001601 return;
1602
1603 // Don't bother if the default stack alignment is sufficiently high.
Eric Christopher1b21f002015-01-29 00:19:33 +00001604 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001605 return;
1606
1607 // Aligned spills require stack realignment.
Eric Christopher1b21f002015-01-29 00:19:33 +00001608 if (!static_cast<const ARMBaseRegisterInfo *>(
1609 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001610 return;
1611
1612 // We always spill contiguous d-registers starting from d8. Count how many
1613 // needs spilling. The register allocator will almost always use the
1614 // callee-saved registers in order, but it can happen that there are holes in
1615 // the range. Registers above the hole will be spilled to the standard DPRCS
1616 // area.
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001617 unsigned NumSpills = 0;
1618 for (; NumSpills < 8; ++NumSpills)
Matthias Braun02564862015-07-14 17:17:13 +00001619 if (!SavedRegs.test(ARM::D8 + NumSpills))
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001620 break;
1621
1622 // Don't do this for just one d-register. It's not worth it.
1623 if (NumSpills < 2)
1624 return;
1625
1626 // Spill the first NumSpills D-registers after realigning the stack.
1627 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1628
1629 // A scratch register is required for the vst1 / vld1 instructions.
Matthias Braun02564862015-07-14 17:17:13 +00001630 SavedRegs.set(ARM::R4);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001631}
1632
Matthias Braun02564862015-07-14 17:17:13 +00001633void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1634 BitVector &SavedRegs,
1635 RegScavenger *RS) const {
1636 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001637 // This tells PEI to spill the FP as if it is any other callee-save register
1638 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1639 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1640 // to combine multiple loads / stores.
1641 bool CanEliminateFrame = true;
1642 bool CS1Spilled = false;
1643 bool LRSpilled = false;
1644 unsigned NumGPRSpills = 0;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001645 unsigned NumFPRSpills = 0;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001646 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1647 SmallVector<unsigned, 4> UnspilledCS2GPRs;
Eric Christopherd9134482014-08-04 21:25:23 +00001648 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
Eric Christopherfc6de422014-08-05 02:39:49 +00001649 MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001650 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00001651 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001652 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
Matthias Braun941a7052016-07-28 18:40:00 +00001653 MachineFrameInfo &MFI = MF.getFrameInfo();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00001654 MachineRegisterInfo &MRI = MF.getRegInfo();
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001655 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1656 (void)TRI; // Silence unused warning in non-assert builds.
Daniel Sanders0c476112019-08-15 19:22:08 +00001657 Register FramePtr = RegInfo->getFrameRegister(MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001658
1659 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1660 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
Evan Cheng572756a2011-01-16 05:14:33 +00001661 // since it's not always possible to restore sp from fp in a single
1662 // instruction.
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001663 // FIXME: It will be better just to find spare register here.
1664 if (AFI->isThumb2Function() &&
Matthias Braun941a7052016-07-28 18:40:00 +00001665 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
Matthias Braun02564862015-07-14 17:17:13 +00001666 SavedRegs.set(ARM::R4);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001667
Martin Storsjoace7ae92018-05-14 21:32:52 +00001668 // If a stack probe will be emitted, spill R4 and LR, since they are
1669 // clobbered by the stack probe call.
1670 // This estimate should be a safe, conservative estimate. The actual
1671 // stack probe is enabled based on the size of the local objects;
1672 // this estimate also includes the varargs store size.
1673 if (STI.isTargetWindows() &&
1674 WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
1675 SavedRegs.set(ARM::R4);
1676 SavedRegs.set(ARM::LR);
1677 }
1678
Evan Cheng572756a2011-01-16 05:14:33 +00001679 if (AFI->isThumb1OnlyFunction()) {
1680 // Spill LR if Thumb1 function uses variable length argument lists.
Stepan Dyatkovskiyf5aa83d2013-04-30 07:19:58 +00001681 if (AFI->getArgRegsSaveSize() > 0)
Matthias Braun02564862015-07-14 17:17:13 +00001682 SavedRegs.set(ARM::LR);
Evan Cheng572756a2011-01-16 05:14:33 +00001683
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001684 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
1685 // requires stack alignment. We don't know for sure what the stack size
1686 // will be, but for this, an estimate is good enough. If there anything
1687 // changes it, it'll be a spill, which implies we've used all the registers
1688 // and so R4 is already used, so not marking it here will be OK.
Evan Cheng572756a2011-01-16 05:14:33 +00001689 // FIXME: It will be better just to find spare register here.
Momchil Velikovd6a4ab32017-10-22 11:56:35 +00001690 if (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF) ||
1691 MFI.estimateStackSize(MF) > 508)
Matthias Braun02564862015-07-14 17:17:13 +00001692 SavedRegs.set(ARM::R4);
Evan Cheng572756a2011-01-16 05:14:33 +00001693 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001694
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001695 // See if we can spill vector registers to aligned stack.
Matthias Braun02564862015-07-14 17:17:13 +00001696 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
Jakob Stoklund Olesen09655852011-12-23 00:36:18 +00001697
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001698 // Spill the BasePtr if it's used.
1699 if (RegInfo->hasBasePointer(MF))
Matthias Braun02564862015-07-14 17:17:13 +00001700 SavedRegs.set(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001701
1702 // Don't spill FP if the frame can be eliminated. This is determined
Matthias Braun02564862015-07-14 17:17:13 +00001703 // by scanning the callee-save registers to see if any is modified.
Craig Topper840beec2014-04-04 05:16:06 +00001704 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001705 for (unsigned i = 0; CSRegs[i]; ++i) {
1706 unsigned Reg = CSRegs[i];
1707 bool Spilled = false;
Matthias Braun02564862015-07-14 17:17:13 +00001708 if (SavedRegs.test(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001709 Spilled = true;
1710 CanEliminateFrame = false;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001711 }
1712
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001713 if (!ARM::GPRRegClass.contains(Reg)) {
1714 if (Spilled) {
1715 if (ARM::SPRRegClass.contains(Reg))
1716 NumFPRSpills++;
1717 else if (ARM::DPRRegClass.contains(Reg))
1718 NumFPRSpills += 2;
1719 else if (ARM::QPRRegClass.contains(Reg))
1720 NumFPRSpills += 4;
1721 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001722 continue;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001723 }
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001724
1725 if (Spilled) {
1726 NumGPRSpills++;
1727
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001728 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001729 if (Reg == ARM::LR)
1730 LRSpilled = true;
1731 CS1Spilled = true;
1732 continue;
1733 }
1734
1735 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1736 switch (Reg) {
1737 case ARM::LR:
1738 LRSpilled = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00001739 LLVM_FALLTHROUGH;
Tim Northoverd8407452013-10-01 14:33:28 +00001740 case ARM::R0: case ARM::R1:
1741 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001742 case ARM::R4: case ARM::R5:
1743 case ARM::R6: case ARM::R7:
1744 CS1Spilled = true;
1745 break;
1746 default:
1747 break;
1748 }
1749 } else {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001750 if (!STI.splitFramePushPop(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001751 UnspilledCS1GPRs.push_back(Reg);
1752 continue;
1753 }
1754
1755 switch (Reg) {
Tim Northoverd8407452013-10-01 14:33:28 +00001756 case ARM::R0: case ARM::R1:
1757 case ARM::R2: case ARM::R3:
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001758 case ARM::R4: case ARM::R5:
1759 case ARM::R6: case ARM::R7:
1760 case ARM::LR:
1761 UnspilledCS1GPRs.push_back(Reg);
1762 break;
1763 default:
1764 UnspilledCS2GPRs.push_back(Reg);
1765 break;
1766 }
1767 }
1768 }
1769
1770 bool ForceLRSpill = false;
1771 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
Eli Friedman2596e8b2019-03-19 21:48:08 +00001772 unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001773 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1774 // use of BL to implement far jump. If it turns out that it's not needed
1775 // then the branch fix up path will undo it.
1776 if (FnSize >= (1 << 11)) {
1777 CanEliminateFrame = false;
1778 ForceLRSpill = true;
1779 }
1780 }
1781
1782 // If any of the stack slot references may be out of range of an immediate
1783 // offset, make sure a register (or a spill slot) is available for the
1784 // register scavenger. Note that if we're indexing off the frame pointer, the
1785 // effective stack size is 4 bytes larger since the FP points to the stack
1786 // slot of the previous FP. Also, if we have variable sized objects in the
1787 // function, stack slot references will often be negative, and some of
1788 // our instructions are positive-offset only, so conservatively consider
1789 // that case to want a spill slot (or register) as well. Similarly, if
1790 // the function adjusts the stack pointer during execution and the
1791 // adjustments aren't already part of our stack size estimate, our offset
1792 // calculations may be off, so be conservative.
1793 // FIXME: We could add logic to be more precise about negative offsets
1794 // and which instructions will need a scratch register for them. Is it
1795 // worth the effort and added fragility?
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001796 unsigned EstimatedStackSize =
Matthias Braun941a7052016-07-28 18:40:00 +00001797 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
Matthias Braun8aaa3682017-04-19 21:11:44 +00001798
1799 // Determine biggest (positive) SP offset in MachineFrameInfo.
1800 int MaxFixedOffset = 0;
1801 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1802 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1803 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1804 }
1805
Matthias Braun44047422017-04-05 16:58:41 +00001806 bool HasFP = hasFP(MF);
1807 if (HasFP) {
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001808 if (AFI->hasStackFrame())
1809 EstimatedStackSize += 4;
1810 } else {
1811 // If FP is not used, SP will be used to access arguments, so count the
1812 // size of arguments into the estimation.
Matthias Braun8aaa3682017-04-19 21:11:44 +00001813 EstimatedStackSize += MaxFixedOffset;
Weiming Zhao5b5501e2016-05-08 05:11:54 +00001814 }
1815 EstimatedStackSize += 16; // For possible paddings.
1816
Eli Friedmanab1d73e2019-06-26 23:46:51 +00001817 unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
David Green1ff95532019-09-17 12:58:51 +00001818 bool HasNonSPFrameIndex = false;
Eli Friedmanab1d73e2019-06-26 23:46:51 +00001819 if (AFI->isThumb1OnlyFunction()) {
1820 // For Thumb1, don't bother to iterate over the function. The only
1821 // instruction that requires an emergency spill slot is a store to a
1822 // frame index.
1823 //
1824 // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
1825 // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
1826 // a 5-bit unsigned immediate.
1827 //
1828 // We could try to check if the function actually contains a tSTRspi
1829 // that might need the spill slot, but it's not really important.
1830 // Functions with VLAs or extremely large call frames are rare, and
1831 // if a function is allocating more than 1KB of stack, an extra 4-byte
1832 // slot probably isn't relevant.
1833 if (RegInfo->hasBasePointer(MF))
1834 EstimatedRSStackSizeLimit = (1U << 5) * 4;
1835 else
1836 EstimatedRSStackSizeLimit = (1U << 8) * 4;
1837 EstimatedRSFixedSizeLimit = (1U << 5) * 4;
1838 } else {
David Green1ff95532019-09-17 12:58:51 +00001839 EstimatedRSStackSizeLimit =
1840 estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
Eli Friedmanab1d73e2019-06-26 23:46:51 +00001841 EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
1842 }
1843 // Final estimate of whether sp or bp-relative accesses might require
1844 // scavenging.
1845 bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
1846
1847 // If the stack pointer moves and we don't have a base pointer, the
1848 // estimate logic doesn't work. The actual offsets might be larger when
1849 // we're constructing a call frame, or we might need to use negative
1850 // offsets from fp.
1851 bool HasMovingSP = MFI.hasVarSizedObjects() ||
1852 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
1853 bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
1854
1855 // If we have a frame pointer, we assume arguments will be accessed
1856 // relative to the frame pointer. Check whether fp-relative accesses to
1857 // arguments require scavenging.
1858 //
1859 // We could do slightly better on Thumb1; in some cases, an sp-relative
1860 // offset would be legal even though an fp-relative offset is not.
Matthias Braunf1caa282017-12-15 22:22:58 +00001861 int MaxFPOffset = getMaxFPOffset(MF.getFunction(), *AFI);
Eli Friedmanab1d73e2019-06-26 23:46:51 +00001862 bool HasLargeArgumentList =
1863 HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
1864
1865 bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
David Green1ff95532019-09-17 12:58:51 +00001866 HasLargeArgumentList || HasNonSPFrameIndex;
Eli Friedmanab1d73e2019-06-26 23:46:51 +00001867 LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
David Green1ff95532019-09-17 12:58:51 +00001868 << "; EstimatedStack: " << EstimatedStackSize
1869 << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
1870 << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
Matthias Braun8aaa3682017-04-19 21:11:44 +00001871 if (BigFrameOffsets ||
1872 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001873 AFI->setHasStackFrame(true);
1874
Matthias Braun44047422017-04-05 16:58:41 +00001875 if (HasFP) {
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001876 SavedRegs.set(FramePtr);
1877 // If the frame pointer is required by the ABI, also spill LR so that we
1878 // emit a complete frame record.
1879 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1880 SavedRegs.set(ARM::LR);
1881 LRSpilled = true;
1882 NumGPRSpills++;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001883 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001884 if (LRPos != UnspilledCS1GPRs.end())
1885 UnspilledCS1GPRs.erase(LRPos);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001886 }
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00001887 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
Oliver Stannard9aa6f012016-08-23 09:19:22 +00001888 if (FPPos != UnspilledCS1GPRs.end())
1889 UnspilledCS1GPRs.erase(FPPos);
1890 NumGPRSpills++;
1891 if (FramePtr == ARM::R7)
1892 CS1Spilled = true;
1893 }
1894
Eli Friedmanab1d73e2019-06-26 23:46:51 +00001895 // This is true when we inserted a spill for a callee-save GPR which is
1896 // not otherwise used by the function. This guaranteees it is possible
1897 // to scavenge a register to hold the address of a stack slot. On Thumb1,
1898 // the register must be a valid operand to tSTRi, i.e. r4-r7. For other
1899 // subtargets, this is any GPR, i.e. r4-r11 or lr.
1900 //
1901 // If we don't insert a spill, we instead allocate an emergency spill
1902 // slot, which can be used by scavenging to spill an arbitrary register.
1903 //
1904 // We currently don't try to figure out whether any specific instruction
1905 // requires scavening an additional register.
Matthias Braunc618a462017-07-28 01:36:32 +00001906 bool ExtraCSSpill = false;
1907
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001908 if (AFI->isThumb1OnlyFunction()) {
1909 // For Thumb1-only targets, we need some low registers when we save and
1910 // restore the high registers (which aren't allocatable, but could be
1911 // used by inline assembly) because the push/pop instructions can not
1912 // access high registers. If necessary, we might need to push more low
1913 // registers to ensure that there is at least one free that can be used
1914 // for the saving & restoring, and preferably we should ensure that as
1915 // many as are needed are available so that fewer push/pop instructions
1916 // are required.
1917
1918 // Low registers which are not currently pushed, but could be (r4-r7).
1919 SmallVector<unsigned, 4> AvailableRegs;
1920
1921 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1922 // free.
1923 int EntryRegDeficit = 0;
1924 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1925 if (!MF.getRegInfo().isLiveIn(Reg)) {
1926 --EntryRegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001927 LLVM_DEBUG(dbgs()
1928 << printReg(Reg, TRI)
1929 << " is unused argument register, EntryRegDeficit = "
1930 << EntryRegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001931 }
1932 }
1933
1934 // Unused return registers can be clobbered in the epilogue for free.
1935 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001936 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
1937 << " return regs used, ExitRegDeficit = "
1938 << ExitRegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001939
1940 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001941 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001942
1943 // r4-r6 can be used in the prologue if they are pushed by the first push
1944 // instruction.
1945 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1946 if (SavedRegs.test(Reg)) {
1947 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001948 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1949 << " is saved low register, RegDeficit = "
1950 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001951 } else {
1952 AvailableRegs.push_back(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001953 LLVM_DEBUG(
1954 dbgs()
1955 << printReg(Reg, TRI)
1956 << " is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001957 }
1958 }
1959
1960 // r7 can be used if it is not being used as the frame pointer.
Matthias Braun44047422017-04-05 16:58:41 +00001961 if (!HasFP) {
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001962 if (SavedRegs.test(ARM::R7)) {
1963 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001964 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
1965 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001966 } else {
1967 AvailableRegs.push_back(ARM::R7);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001968 LLVM_DEBUG(
1969 dbgs()
1970 << "%r7 is non-saved low register, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001971 }
1972 }
1973
1974 // Each of r8-r11 needs to be copied to a low register, then pushed.
1975 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1976 if (SavedRegs.test(Reg)) {
1977 ++RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001978 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
1979 << " is saved high register, RegDeficit = "
1980 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001981 }
1982 }
1983
1984 // LR can only be used by PUSH, not POP, and can't be used at all if the
1985 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1986 // are more limited at function entry than exit.
1987 if ((EntryRegDeficit > ExitRegDeficit) &&
1988 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1989 MF.getFrameInfo().isReturnAddressTaken())) {
1990 if (SavedRegs.test(ARM::LR)) {
1991 --RegDeficit;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001992 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
1993 << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001994 } else {
1995 AvailableRegs.push_back(ARM::LR);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001996 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00001997 }
1998 }
1999
2000 // If there are more high registers that need pushing than low registers
2001 // available, push some more low registers so that we can use fewer push
2002 // instructions. This might not reduce RegDeficit all the way to zero,
2003 // because we can only guarantee that r4-r6 are available, but r8-r11 may
2004 // need saving.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002005 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00002006 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
2007 unsigned Reg = AvailableRegs.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002008 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2009 << " to make up reg deficit\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00002010 SavedRegs.set(Reg);
2011 NumGPRSpills++;
2012 CS1Spilled = true;
Matthias Braunc618a462017-07-28 01:36:32 +00002013 assert(!MRI.isReserved(Reg) && "Should not be reserved");
Eli Friedmanab1d73e2019-06-26 23:46:51 +00002014 if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
Matthias Braunc618a462017-07-28 01:36:32 +00002015 ExtraCSSpill = true;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00002016 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00002017 if (Reg == ARM::LR)
2018 LRSpilled = true;
2019 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002020 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
2021 << "\n");
Reid Klecknerbdfc05f2016-10-11 21:14:03 +00002022 }
2023
Eli Friedman5b45a392018-08-08 20:03:10 +00002024 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
2025 // restore LR in that case.
2026 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
2027
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002028 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
2029 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
Eli Friedman5b45a392018-08-08 20:03:10 +00002030 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
Matthias Braun02564862015-07-14 17:17:13 +00002031 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002032 NumGPRSpills++;
Tim Northoverd8407452013-10-01 14:33:28 +00002033 SmallVectorImpl<unsigned>::iterator LRPos;
Eugene Zelenkoe6cf4372017-01-26 23:40:06 +00002034 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
Tim Northoverd8407452013-10-01 14:33:28 +00002035 if (LRPos != UnspilledCS1GPRs.end())
2036 UnspilledCS1GPRs.erase(LRPos);
2037
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002038 ForceLRSpill = false;
Eli Friedmanab1d73e2019-06-26 23:46:51 +00002039 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
2040 !AFI->isThumb1OnlyFunction())
Matthias Braunc618a462017-07-28 01:36:32 +00002041 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002042 }
2043
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002044 // If stack and double are 8-byte aligned and we are spilling an odd number
2045 // of GPRs, spill one extra callee save GPR so we won't have to pad between
2046 // the integer and double callee save areas.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002047 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
Anton Korobeynikov2f931282011-01-10 12:39:04 +00002048 unsigned TargetAlign = getStackAlignment();
Tim Northoverdc0d9e42014-11-05 00:27:20 +00002049 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002050 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
2051 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
2052 unsigned Reg = UnspilledCS1GPRs[i];
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00002053 // Don't spill high register if the function is thumb. In the case of
2054 // Windows on ARM, accept R11 (frame pointer)
Peter Collingbourne78f1ecc2015-04-23 20:31:26 +00002055 if (!AFI->isThumbFunction() ||
Saleem Abdulrasool1825fac2015-10-09 03:19:03 +00002056 (STI.isTargetWindows() && Reg == ARM::R11) ||
Eli Friedman5b45a392018-08-08 20:03:10 +00002057 isARMLowRegister(Reg) ||
2058 (Reg == ARM::LR && !ExpensiveLRRestore)) {
Matthias Braun02564862015-07-14 17:17:13 +00002059 SavedRegs.set(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002060 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2061 << " to make up alignment\n");
Eli Friedmanab1d73e2019-06-26 23:46:51 +00002062 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
2063 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002064 ExtraCSSpill = true;
2065 break;
2066 }
2067 }
2068 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
2069 unsigned Reg = UnspilledCS2GPRs.front();
Matthias Braun02564862015-07-14 17:17:13 +00002070 SavedRegs.set(Reg);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002071 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2072 << " to make up alignment\n");
Matthias Braunc618a462017-07-28 01:36:32 +00002073 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002074 ExtraCSSpill = true;
2075 }
2076 }
2077
2078 // Estimate if we might need to scavenge a register at some point in order
2079 // to materialize a stack offset. If so, either spill one additional
2080 // callee-saved register or reserve a special spill slot to facilitate
2081 // register scavenging. Thumb1 needs a spill slot for stack pointer
2082 // adjustments also, even when the frame itself is small.
Matthias Braun8aaa3682017-04-19 21:11:44 +00002083 if (BigFrameOffsets && !ExtraCSSpill) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002084 // If any non-reserved CS register isn't spilled, just spill one or two
2085 // extra. That should take care of it!
2086 unsigned NumExtras = TargetAlign / 4;
2087 SmallVector<unsigned, 2> Extras;
2088 while (NumExtras && !UnspilledCS1GPRs.empty()) {
2089 unsigned Reg = UnspilledCS1GPRs.back();
2090 UnspilledCS1GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00002091 if (!MRI.isReserved(Reg) &&
Eli Friedmanab1d73e2019-06-26 23:46:51 +00002092 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002093 Extras.push_back(Reg);
2094 NumExtras--;
2095 }
2096 }
2097 // For non-Thumb1 functions, also check for hi-reg CS registers
2098 if (!AFI->isThumb1OnlyFunction()) {
2099 while (NumExtras && !UnspilledCS2GPRs.empty()) {
2100 unsigned Reg = UnspilledCS2GPRs.back();
2101 UnspilledCS2GPRs.pop_back();
Jakob Stoklund Olesen410eae52012-10-26 21:43:05 +00002102 if (!MRI.isReserved(Reg)) {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002103 Extras.push_back(Reg);
2104 NumExtras--;
2105 }
2106 }
2107 }
Matthias Braunc618a462017-07-28 01:36:32 +00002108 if (NumExtras == 0) {
2109 for (unsigned Reg : Extras) {
2110 SavedRegs.set(Reg);
2111 if (!MRI.isPhysRegUsed(Reg))
2112 ExtraCSSpill = true;
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002113 }
Matthias Braunc618a462017-07-28 01:36:32 +00002114 }
Oliver Stannard8ed83532019-08-05 09:04:10 +00002115 if (!ExtraCSSpill && RS) {
Eli Friedmanab1d73e2019-06-26 23:46:51 +00002116 // Reserve a slot closest to SP or frame pointer.
Eli Friedmanab1d73e2019-06-26 23:46:51 +00002117 LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
Krzysztof Parzyszek44e25f32017-04-24 18:55:33 +00002118 const TargetRegisterClass &RC = ARM::GPRRegClass;
2119 unsigned Size = TRI->getSpillSize(RC);
2120 unsigned Align = TRI->getSpillAlignment(RC);
2121 RS->addScavengingFrameIndex(MFI.CreateStackObject(Size, Align, false));
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002122 }
2123 }
2124 }
2125
2126 if (ForceLRSpill) {
Matthias Braun02564862015-07-14 17:17:13 +00002127 SavedRegs.set(ARM::LR);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002128 AFI->setLRIsSpilledForFarJump(true);
2129 }
Eli Friedman2596e8b2019-03-19 21:48:08 +00002130 AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
Oliver Stannard6771a892019-07-22 08:44:36 +00002131
2132 // If we have the "returned" parameter attribute which guarantees that we
2133 // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
2134 // record that fact for IPRA.
2135 if (AFI->getPreservesR0())
2136 SavedRegs.set(ARM::R0);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00002137}
Eli Bendersky8da87162013-02-21 20:05:00 +00002138
Hans Wennborge1a2e902016-03-31 18:33:38 +00002139MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
2140 MachineFunction &MF, MachineBasicBlock &MBB,
2141 MachineBasicBlock::iterator I) const {
Eli Bendersky8da87162013-02-21 20:05:00 +00002142 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002143 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00002144 if (!hasReservedCallFrame(MF)) {
2145 // If we have alloca, convert as follows:
2146 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
2147 // ADJCALLSTACKUP -> add, sp, sp, amount
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002148 MachineInstr &Old = *I;
2149 DebugLoc dl = Old.getDebugLoc();
Serge Pavlov5943a962017-04-19 03:12:05 +00002150 unsigned Amount = TII.getFrameSize(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002151 if (Amount != 0) {
2152 // We need to keep the stack aligned properly. To do this, we round the
2153 // amount of space needed for the outgoing arguments up to the next
2154 // alignment boundary.
Guozhi Weif66d3842015-08-17 22:36:27 +00002155 Amount = alignSPAdjust(Amount);
Eli Bendersky8da87162013-02-21 20:05:00 +00002156
2157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2158 assert(!AFI->isThumb1OnlyFunction() &&
2159 "This eliminateCallFramePseudoInstr does not support Thumb1!");
2160 bool isARM = !AFI->isThumbFunction();
2161
2162 // Replace the pseudo instruction with a new instruction...
Duncan P. N. Exon Smith29c52492016-07-08 20:21:17 +00002163 unsigned Opc = Old.getOpcode();
2164 int PIdx = Old.findFirstPredOperandIdx();
2165 ARMCC::CondCodes Pred =
2166 (PIdx == -1) ? ARMCC::AL
2167 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
Serge Pavlov5943a962017-04-19 03:12:05 +00002168 unsigned PredReg = TII.getFramePred(Old);
Eli Bendersky8da87162013-02-21 20:05:00 +00002169 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
Eli Bendersky8da87162013-02-21 20:05:00 +00002170 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2171 Pred, PredReg);
2172 } else {
Eli Bendersky8da87162013-02-21 20:05:00 +00002173 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2174 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2175 Pred, PredReg);
2176 }
2177 }
2178 }
Hans Wennborge1a2e902016-03-31 18:33:38 +00002179 return MBB.erase(I);
Eli Bendersky8da87162013-02-21 20:05:00 +00002180}
2181
Oliver Stannardb14c6252014-04-02 16:10:33 +00002182/// Get the minimum constant for ARM that is greater than or equal to the
2183/// argument. In ARM, constants can have any value that can be produced by
2184/// rotating an 8-bit value to the right by an even number of bits within a
2185/// 32-bit word.
2186static uint32_t alignToARMConstant(uint32_t Value) {
2187 unsigned Shifted = 0;
2188
2189 if (Value == 0)
2190 return 0;
2191
2192 while (!(Value & 0xC0000000)) {
2193 Value = Value << 2;
2194 Shifted += 2;
2195 }
2196
2197 bool Carry = (Value & 0x00FFFFFF);
2198 Value = ((Value & 0xFF000000) >> 24) + Carry;
2199
2200 if (Value & 0x0000100)
2201 Value = Value & 0x000001FC;
2202
2203 if (Shifted > 24)
2204 Value = Value >> (Shifted - 24);
2205 else
2206 Value = Value << (24 - Shifted);
2207
2208 return Value;
2209}
2210
2211// The stack limit in the TCB is set to this many bytes above the actual
2212// stack limit.
2213static const uint64_t kSplitStackAvailable = 256;
2214
2215// Adjust the function prologue to enable split stacks. This currently only
2216// supports android and linux.
2217//
2218// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2219// must be well defined in order to allow for consistent implementations of the
2220// __morestack helper function. The ABI is also not a normal ABI in that it
2221// doesn't follow the normal calling conventions because this allows the
2222// prologue of each function to be optimized further.
2223//
2224// Currently, the ABI looks like (when calling __morestack)
2225//
2226// * r4 holds the minimum stack size requested for this function call
2227// * r5 holds the stack size of the arguments to the function
2228// * the beginning of the function is 3 instructions after the call to
2229// __morestack
2230//
2231// Implementations of __morestack should use r4 to allocate a new stack, r5 to
2232// place the arguments on to the new stack, and the 3-instruction knowledge to
2233// jump directly to the body of the function when working on the new stack.
2234//
2235// An old (and possibly no longer compatible) implementation of __morestack for
2236// ARM can be found at [1].
2237//
2238// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
Quentin Colombet61b305e2015-05-05 17:38:16 +00002239void ARMFrameLowering::adjustForSegmentedStacks(
2240 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Oliver Stannardb14c6252014-04-02 16:10:33 +00002241 unsigned Opcode;
2242 unsigned CFIIndex;
Eric Christopher22b2ad22015-02-20 08:24:37 +00002243 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002244 bool Thumb = ST->isThumb();
2245
2246 // Sadly, this currently doesn't support varargs, platforms other than
2247 // android/linux. Note that thumb1/thumb2 are support for android/linux.
Matthias Braunf1caa282017-12-15 22:22:58 +00002248 if (MF.getFunction().isVarArg())
Oliver Stannardb14c6252014-04-02 16:10:33 +00002249 report_fatal_error("Segmented stacks do not support vararg functions.");
2250 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
Alp Toker16f98b22014-04-09 14:47:27 +00002251 report_fatal_error("Segmented stacks not supported on this platform.");
Oliver Stannardb14c6252014-04-02 16:10:33 +00002252
Matthias Braun941a7052016-07-28 18:40:00 +00002253 MachineFrameInfo &MFI = MF.getFrameInfo();
Oliver Stannardb14c6252014-04-02 16:10:33 +00002254 MachineModuleInfo &MMI = MF.getMMI();
2255 MCContext &Context = MMI.getContext();
2256 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2257 const ARMBaseInstrInfo &TII =
Eric Christopherfc6de422014-08-05 02:39:49 +00002258 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002259 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2260 DebugLoc DL;
2261
Matthias Braun941a7052016-07-28 18:40:00 +00002262 uint64_t StackSize = MFI.getStackSize();
Tim Northoverf9e798b2014-05-22 13:03:43 +00002263
Than McIntosh31909932018-06-26 14:11:30 +00002264 // Do not generate a prologue for leaf functions with a stack of size zero.
2265 // For non-leaf functions we have to allow for the possibility that the
Sterling Augustine9cc1ffa2018-11-26 23:26:31 +00002266 // callis to a non-split function, as in PR37807. This function could also
2267 // take the address of a non-split function. When the linker tries to adjust
2268 // its non-existent prologue, it would fail with an error. Mark the object
2269 // file so that such failures are not errors. See this Go language bug-report
2270 // https://go-review.googlesource.com/c/go/+/148819/
2271 if (StackSize == 0 && !MFI.hasTailCall()) {
2272 MF.getMMI().setHasNosplitStack(true);
Tim Northoverf9e798b2014-05-22 13:03:43 +00002273 return;
Sterling Augustine9cc1ffa2018-11-26 23:26:31 +00002274 }
Tim Northoverf9e798b2014-05-22 13:03:43 +00002275
Oliver Stannardb14c6252014-04-02 16:10:33 +00002276 // Use R4 and R5 as scratch registers.
2277 // We save R4 and R5 before use and restore them before leaving the function.
2278 unsigned ScratchReg0 = ARM::R4;
2279 unsigned ScratchReg1 = ARM::R5;
2280 uint64_t AlignedStackSize;
2281
2282 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2283 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2284 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2285 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2286 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2287
Quentin Colombet71a71482015-07-20 21:42:14 +00002288 // Grab everything that reaches PrologueMBB to update there liveness as well.
2289 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2290 SmallVector<MachineBasicBlock *, 2> WalkList;
2291 WalkList.push_back(&PrologueMBB);
2292
2293 do {
2294 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2295 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2296 if (BeforePrologueRegion.insert(PredBB).second)
2297 WalkList.push_back(PredBB);
2298 }
2299 } while (!WalkList.empty());
2300
2301 // The order in that list is important.
2302 // The blocks will all be inserted before PrologueMBB using that order.
2303 // Therefore the block that should appear first in the CFG should appear
2304 // first in the list.
2305 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2306 PostStackMBB};
Quentin Colombet71a71482015-07-20 21:42:14 +00002307
Craig Topper80720812015-12-01 06:13:01 +00002308 for (MachineBasicBlock *B : AddedBlocks)
2309 BeforePrologueRegion.insert(B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002310
Matthias Braund9da1622015-09-09 18:08:03 +00002311 for (const auto &LI : PrologueMBB.liveins()) {
Quentin Colombet71a71482015-07-20 21:42:14 +00002312 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
Matthias Braunb2b7ef12015-08-24 22:59:52 +00002313 PredBB->addLiveIn(LI);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002314 }
2315
Quentin Colombet71a71482015-07-20 21:42:14 +00002316 // Remove the newly added blocks from the list, since we know
2317 // we do not have to do the following updates for them.
Craig Topper80720812015-12-01 06:13:01 +00002318 for (MachineBasicBlock *B : AddedBlocks) {
2319 BeforePrologueRegion.erase(B);
2320 MF.insert(PrologueMBB.getIterator(), B);
Quentin Colombet71a71482015-07-20 21:42:14 +00002321 }
2322
2323 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2324 // Make sure the LiveIns are still sorted and unique.
2325 MBB->sortUniqueLiveIns();
2326 // Replace the edges to PrologueMBB by edges to the sequences
2327 // we are about to add.
2328 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2329 }
Oliver Stannardb14c6252014-04-02 16:10:33 +00002330
2331 // The required stack size that is aligned to ARM constant criterion.
Oliver Stannardb14c6252014-04-02 16:10:33 +00002332 AlignedStackSize = alignToARMConstant(StackSize);
2333
2334 // When the frame size is less than 256 we just compare the stack
2335 // boundary directly to the value of the stack pointer, per gcc.
2336 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2337
2338 // We will use two of the callee save registers as scratch registers so we
2339 // need to save those registers onto the stack.
2340 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2341 // requested and arguments for __morestack().
2342 // SR0: Scratch Register #0
2343 // SR1: Scratch Register #1
2344 // push {SR0, SR1}
2345 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002346 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2347 .add(predOps(ARMCC::AL))
2348 .addReg(ScratchReg0)
2349 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002350 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002351 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2352 .addReg(ARM::SP, RegState::Define)
2353 .addReg(ARM::SP)
2354 .add(predOps(ARMCC::AL))
2355 .addReg(ScratchReg0)
2356 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002357 }
2358
2359 // Emit the relevant DWARF information about the change in stack pointer as
2360 // well as where to find both r4 and r5 (the callee-save registers)
2361 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002362 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002363 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2364 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002365 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002366 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2367 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2368 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002369 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002370 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2371 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2372 .addCFIIndex(CFIIndex);
2373
2374 // mov SR1, sp
2375 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002376 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2377 .addReg(ARM::SP)
2378 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002379 } else if (CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002380 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2381 .addReg(ARM::SP)
2382 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002383 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002384 }
2385
2386 // sub SR1, sp, #StackSize
2387 if (!CompareStackPointer && Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002388 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2389 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002390 .addReg(ScratchReg1)
2391 .addImm(AlignedStackSize)
2392 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002393 } else if (!CompareStackPointer) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002394 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2395 .addReg(ARM::SP)
2396 .addImm(AlignedStackSize)
2397 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002398 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002399 }
2400
2401 if (Thumb && ST->isThumb1Only()) {
2402 unsigned PCLabelId = ARMFI->createPICLabelUId();
2403 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
Matthias Braunf1caa282017-12-15 22:22:58 +00002404 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002405 MachineConstantPool *MCP = MF.getConstantPool();
Tim Northover956b0082015-10-02 18:07:13 +00002406 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002407
2408 // ldr SR0, [pc, offset(STACK_LIMIT)]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002409 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2410 .addConstantPoolIndex(CPI)
2411 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002412
2413 // ldr SR0, [SR0]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002414 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2415 .addReg(ScratchReg0)
2416 .addImm(0)
2417 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002418 } else {
2419 // Get TLS base address from the coprocessor
2420 // mrc p15, #0, SR0, c13, c0, #3
Diana Picus4f8c3e12017-01-13 09:37:56 +00002421 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2422 .addImm(15)
2423 .addImm(0)
2424 .addImm(13)
2425 .addImm(0)
2426 .addImm(3)
2427 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002428
2429 // Use the last tls slot on android and a private field of the TCP on linux.
2430 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2431 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2432
2433 // Get the stack limit from the right offset
2434 // ldr SR0, [sr0, #4 * TlsOffset]
Diana Picus4f8c3e12017-01-13 09:37:56 +00002435 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2436 .addReg(ScratchReg0)
2437 .addImm(4 * TlsOffset)
2438 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002439 }
2440
2441 // Compare stack limit with stack size requested.
2442 // cmp SR0, SR1
2443 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
Diana Picus4f8c3e12017-01-13 09:37:56 +00002444 BuildMI(GetMBB, DL, TII.get(Opcode))
2445 .addReg(ScratchReg0)
2446 .addReg(ScratchReg1)
2447 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002448
2449 // This jump is taken if StackLimit < SP - stack required.
2450 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2451 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2452 .addImm(ARMCC::LO)
2453 .addReg(ARM::CPSR);
2454
2455
2456 // Calling __morestack(StackSize, Size of stack arguments).
2457 // __morestack knows that the stack size requested is in SR0(r4)
2458 // and amount size of stack arguments is in SR1(r5).
2459
2460 // Pass first argument for the __morestack by Scratch Register #0.
2461 // The amount size of stack required
2462 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002463 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2464 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002465 .addImm(AlignedStackSize)
2466 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002467 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002468 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2469 .addImm(AlignedStackSize)
2470 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002471 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002472 }
2473 // Pass second argument for the __morestack by Scratch Register #1.
2474 // The amount size of stack consumed to save function arguments.
2475 if (Thumb) {
Diana Picus8a73f552017-01-13 10:18:01 +00002476 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2477 .add(condCodeOp())
Diana Picus4f8c3e12017-01-13 09:37:56 +00002478 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2479 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002480 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002481 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2482 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2483 .add(predOps(ARMCC::AL))
Diana Picusbd66b7d2017-01-20 08:15:24 +00002484 .add(condCodeOp());
Oliver Stannardb14c6252014-04-02 16:10:33 +00002485 }
2486
2487 // push {lr} - Save return address of this function.
2488 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002489 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2490 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002491 .addReg(ARM::LR);
2492 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002493 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2494 .addReg(ARM::SP, RegState::Define)
2495 .addReg(ARM::SP)
2496 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002497 .addReg(ARM::LR);
2498 }
2499
2500 // Emit the DWARF info about the change in stack as well as where to find the
2501 // previous link register
2502 CFIIndex =
Matthias Braunf23ef432016-11-30 23:48:42 +00002503 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002504 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2505 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002506 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002507 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2508 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2509 .addCFIIndex(CFIIndex);
2510
2511 // Call __morestack().
2512 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002513 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2514 .add(predOps(ARMCC::AL))
Oliver Stannardb14c6252014-04-02 16:10:33 +00002515 .addExternalSymbol("__morestack");
2516 } else {
2517 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2518 .addExternalSymbol("__morestack");
2519 }
2520
2521 // pop {lr} - Restore return address of this original function.
2522 if (Thumb) {
2523 if (ST->isThumb1Only()) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002524 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2525 .add(predOps(ARMCC::AL))
2526 .addReg(ScratchReg0);
2527 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2528 .addReg(ScratchReg0)
2529 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002530 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002531 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2532 .addReg(ARM::LR, RegState::Define)
2533 .addReg(ARM::SP, RegState::Define)
2534 .addReg(ARM::SP)
2535 .addImm(4)
2536 .add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002537 }
2538 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002539 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2540 .addReg(ARM::SP, RegState::Define)
2541 .addReg(ARM::SP)
2542 .add(predOps(ARMCC::AL))
2543 .addReg(ARM::LR);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002544 }
2545
2546 // Restore SR0 and SR1 in case of __morestack() was called.
2547 // __morestack() will skip PostStackMBB block so we need to restore
2548 // scratch registers from here.
2549 // pop {SR0, SR1}
2550 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002551 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2552 .add(predOps(ARMCC::AL))
2553 .addReg(ScratchReg0)
2554 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002555 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002556 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2557 .addReg(ARM::SP, RegState::Define)
2558 .addReg(ARM::SP)
2559 .add(predOps(ARMCC::AL))
2560 .addReg(ScratchReg0)
2561 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002562 }
2563
2564 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002565 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002566 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2567 .addCFIIndex(CFIIndex);
2568
Joerg Sonnenberger0f76a352017-08-28 20:20:47 +00002569 // Return from this function.
2570 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002571
2572 // Restore SR0 and SR1 in case of __morestack() was not called.
2573 // pop {SR0, SR1}
2574 if (Thumb) {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002575 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2576 .add(predOps(ARMCC::AL))
2577 .addReg(ScratchReg0)
2578 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002579 } else {
Diana Picus4f8c3e12017-01-13 09:37:56 +00002580 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2581 .addReg(ARM::SP, RegState::Define)
2582 .addReg(ARM::SP)
2583 .add(predOps(ARMCC::AL))
2584 .addReg(ScratchReg0)
2585 .addReg(ScratchReg1);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002586 }
2587
2588 // Update the CFA offset now that we've popped
Matthias Braunf23ef432016-11-30 23:48:42 +00002589 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
Oliver Stannardb14c6252014-04-02 16:10:33 +00002590 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2591 .addCFIIndex(CFIIndex);
2592
2593 // Tell debuggers that r4 and r5 are now the same as they were in the
2594 // previous function, that they're the "Same Value".
Matthias Braunf23ef432016-11-30 23:48:42 +00002595 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002596 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2597 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2598 .addCFIIndex(CFIIndex);
Matthias Braunf23ef432016-11-30 23:48:42 +00002599 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
Oliver Stannardb14c6252014-04-02 16:10:33 +00002600 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2601 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2602 .addCFIIndex(CFIIndex);
2603
2604 // Organizing MBB lists
Quentin Colombet61b305e2015-05-05 17:38:16 +00002605 PostStackMBB->addSuccessor(&PrologueMBB);
Oliver Stannardb14c6252014-04-02 16:10:33 +00002606
2607 AllocMBB->addSuccessor(PostStackMBB);
2608
2609 GetMBB->addSuccessor(PostStackMBB);
2610 GetMBB->addSuccessor(AllocMBB);
2611
2612 McrMBB->addSuccessor(GetMBB);
2613
2614 PrevStackMBB->addSuccessor(McrMBB);
2615
Filipe Cabecinhas0da99372016-04-29 15:22:48 +00002616#ifdef EXPENSIVE_CHECKS
Oliver Stannardb14c6252014-04-02 16:10:33 +00002617 MF.verify();
2618#endif
2619}