1//===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the ARM implementation of TargetFrameLowering class.
10//
11//===----------------------------------------------------------------------===//
12//
13// This file contains the ARM implementation of TargetFrameLowering class.
14//
15// On ARM, stack frames are structured as follows:
16//
17// The stack grows downward.
18//
19// All of the individual frame areas on the frame below are optional, i.e. it's
20// possible to create a function so that the particular area isn't present
21// in the frame.
22//
23// At function entry, the "frame" looks as follows:
24//
25// | | Higher address
26// |-----------------------------------|
27// | |
28// | arguments passed on the stack |
29// | |
30// |-----------------------------------| <- sp
31// | | Lower address
32//
33//
34// After the prologue has run, the frame has the following general structure.
35// Technically the last frame area (VLAs) doesn't get created until in the
36// main function body, after the prologue is run. However, it's depicted here
37// for completeness.
38//
39// | | Higher address
40// |-----------------------------------|
41// | |
42// | arguments passed on the stack |
43// | |
44// |-----------------------------------| <- (sp at function entry)
45// | |
46// | varargs from registers |
47// | |
48// |-----------------------------------|
49// | |
50// | prev_lr |
51// | prev_fp |
52// | (a.k.a. "frame record") |
53// | |
54// |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11)
55// | |
56// | callee-saved gpr registers |
57// | |
58// |-----------------------------------|
59// | |
60// | callee-saved fp/simd regs |
61// | |
62// |-----------------------------------|
63// |.empty.space.to.make.part.below....|
64// |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
65// |.the.standard.8-byte.alignment.....| compile time; if present)
66// |-----------------------------------|
67// | |
68// | local variables of fixed size |
69// | including spill slots |
70// |-----------------------------------| <- base pointer (not defined by ABI,
71// |.variable-sized.local.variables....| LLVM chooses r6)
72// |.(VLAs)............................| (size of this area is unknown at
73// |...................................| compile time)
74// |-----------------------------------| <- sp
75// | | Lower address
76//
77//
78// To access the data in a frame, at-compile time, a constant offset must be
79// computable from one of the pointers (fp, bp, sp) to access it. The size
80// of the areas with a dotted background cannot be computed at compile-time
81// if they are present, making it required to have all three of fp, bp and
82// sp to be set up to be able to access all contents in the frame areas,
83// assuming all of the frame areas are non-empty.
84//
85// For most functions, some of the frame areas are empty. For those functions,
86// it may not be necessary to set up fp or bp:
87// * A base pointer is definitely needed when there are both VLAs and local
88// variables with more-than-default alignment requirements.
89// * A frame pointer is definitely needed when there are local variables with
90// more-than-default alignment requirements.
91//
92// In some cases when a base pointer is not strictly needed, it is generated
93// anyway when offsets from the frame pointer to access local variables become
94// so large that the offset can't be encoded in the immediate fields of loads
95// or stores.
96//
97// The frame pointer might be chosen to be r7 or r11, depending on the target
98// architecture and operating system. See ARMSubtarget::getFramePointerReg for
99// details.
100//
101// Outgoing function arguments must be at the bottom of the stack frame when
102// calling another function. If we do not have variable-sized stack objects, we
103// can allocate a "reserved call frame" area at the bottom of the local
104// variable area, large enough for all outgoing calls. If we do have VLAs, then
105// the stack pointer must be decremented and incremented around each call to
106// make space for the arguments below the VLAs.
107//
108//===----------------------------------------------------------------------===//
109
110#include "ARMFrameLowering.h"
111#include "ARMBaseInstrInfo.h"
112#include "ARMBaseRegisterInfo.h"
113#include "ARMConstantPoolValue.h"
114#include "ARMMachineFunctionInfo.h"
115#include "ARMSubtarget.h"
116#include "MCTargetDesc/ARMAddressingModes.h"
117#include "MCTargetDesc/ARMBaseInfo.h"
118#include "Utils/ARMBaseInfo.h"
119#include "llvm/ADT/BitVector.h"
120#include "llvm/ADT/STLExtras.h"
121#include "llvm/ADT/SmallPtrSet.h"
122#include "llvm/ADT/SmallVector.h"
123#include "llvm/CodeGen/CFIInstBuilder.h"
124#include "llvm/CodeGen/MachineBasicBlock.h"
125#include "llvm/CodeGen/MachineConstantPool.h"
126#include "llvm/CodeGen/MachineFrameInfo.h"
127#include "llvm/CodeGen/MachineFunction.h"
128#include "llvm/CodeGen/MachineInstr.h"
129#include "llvm/CodeGen/MachineInstrBuilder.h"
130#include "llvm/CodeGen/MachineJumpTableInfo.h"
131#include "llvm/CodeGen/MachineModuleInfo.h"
132#include "llvm/CodeGen/MachineOperand.h"
133#include "llvm/CodeGen/MachineRegisterInfo.h"
134#include "llvm/CodeGen/RegisterScavenging.h"
135#include "llvm/CodeGen/TargetInstrInfo.h"
136#include "llvm/CodeGen/TargetRegisterInfo.h"
137#include "llvm/CodeGen/TargetSubtargetInfo.h"
138#include "llvm/IR/Attributes.h"
139#include "llvm/IR/CallingConv.h"
140#include "llvm/IR/DebugLoc.h"
141#include "llvm/IR/Function.h"
142#include "llvm/IR/Module.h"
143#include "llvm/MC/MCAsmInfo.h"
144#include "llvm/MC/MCInstrDesc.h"
145#include "llvm/Support/CodeGen.h"
146#include "llvm/Support/CommandLine.h"
147#include "llvm/Support/Compiler.h"
148#include "llvm/Support/Debug.h"
149#include "llvm/Support/ErrorHandling.h"
150#include "llvm/Support/raw_ostream.h"
151#include "llvm/Target/TargetMachine.h"
152#include <algorithm>
153#include <cassert>
154#include <cstddef>
155#include <cstdint>
156#include <iterator>
157#include <utility>
158#include <vector>
159
160#define DEBUG_TYPE "arm-frame-lowering"
161
162using namespace llvm;
163
164static cl::opt<bool>
165SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(Val: true),
166 cl::desc("Align ARM NEON spills in prolog and epilog"));
167
168static MachineBasicBlock::iterator
169skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
170 unsigned NumAlignedDPRCS2Regs);
171
172enum class SpillArea {
173 GPRCS1,
174 GPRCS2,
175 FPStatus,
176 DPRCS1,
177 DPRCS2,
178 GPRCS3,
179 FPCXT,
180};
181
182/// Get the spill area that Reg should be saved into in the prologue.
183SpillArea getSpillArea(Register Reg,
184 ARMSubtarget::PushPopSplitVariation Variation,
185 unsigned NumAlignedDPRCS2Regs,
186 const ARMBaseRegisterInfo *RegInfo) {
187 // NoSplit:
188 // push {r0-r12, lr} GPRCS1
189 // vpush {r8-d15} DPRCS1
190 //
191 // SplitR7:
192 // push {r0-r7, lr} GPRCS1
193 // push {r8-r12} GPRCS2
194 // vpush {r8-d15} DPRCS1
195 //
196 // SplitR11WindowsSEH:
197 // push {r0-r10, r12} GPRCS1
198 // vpush {r8-d15} DPRCS1
199 // push {r11, lr} GPRCS3
200 //
201 // SplitR11AAPCSSignRA:
202 // push {r0-r10, r12} GPRSC1
203 // push {r11, lr} GPRCS2
204 // vpush {r8-d15} DPRCS1
205
206 // If FPCXTNS is spilled (for CMSE secure entryfunctions), it is always at
207 // the top of the stack frame.
208 // The DPRCS2 region is used for ABIs which only guarantee 4-byte alignment
209 // of SP. If used, it will be below the other save areas, after the stack has
210 // been re-aligned.
211
212 switch (Reg) {
213 default:
214 dbgs() << "Don't know where to spill " << printReg(Reg, TRI: RegInfo) << "\n";
215 llvm_unreachable("Don't know where to spill this register");
216 break;
217
218 case ARM::FPCXTNS:
219 return SpillArea::FPCXT;
220
221 case ARM::FPSCR:
222 case ARM::FPEXC:
223 return SpillArea::FPStatus;
224
225 case ARM::R0:
226 case ARM::R1:
227 case ARM::R2:
228 case ARM::R3:
229 case ARM::R4:
230 case ARM::R5:
231 case ARM::R6:
232 case ARM::R7:
233 return SpillArea::GPRCS1;
234
235 case ARM::R8:
236 case ARM::R9:
237 case ARM::R10:
238 if (Variation == ARMSubtarget::SplitR7)
239 return SpillArea::GPRCS2;
240 else
241 return SpillArea::GPRCS1;
242
243 case ARM::R11:
244 if (Variation == ARMSubtarget::SplitR7 ||
245 Variation == ARMSubtarget::SplitR11AAPCSSignRA)
246 return SpillArea::GPRCS2;
247 if (Variation == ARMSubtarget::SplitR11WindowsSEH)
248 return SpillArea::GPRCS3;
249
250 return SpillArea::GPRCS1;
251
252 case ARM::R12:
253 if (Variation == ARMSubtarget::SplitR7)
254 return SpillArea::GPRCS2;
255 else
256 return SpillArea::GPRCS1;
257
258 case ARM::LR:
259 if (Variation == ARMSubtarget::SplitR11AAPCSSignRA)
260 return SpillArea::GPRCS2;
261 if (Variation == ARMSubtarget::SplitR11WindowsSEH)
262 return SpillArea::GPRCS3;
263
264 return SpillArea::GPRCS1;
265
266 case ARM::D0:
267 case ARM::D1:
268 case ARM::D2:
269 case ARM::D3:
270 case ARM::D4:
271 case ARM::D5:
272 case ARM::D6:
273 case ARM::D7:
274 return SpillArea::DPRCS1;
275
276 case ARM::D8:
277 case ARM::D9:
278 case ARM::D10:
279 case ARM::D11:
280 case ARM::D12:
281 case ARM::D13:
282 case ARM::D14:
283 case ARM::D15:
284 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
285 return SpillArea::DPRCS2;
286 else
287 return SpillArea::DPRCS1;
288
289 case ARM::D16:
290 case ARM::D17:
291 case ARM::D18:
292 case ARM::D19:
293 case ARM::D20:
294 case ARM::D21:
295 case ARM::D22:
296 case ARM::D23:
297 case ARM::D24:
298 case ARM::D25:
299 case ARM::D26:
300 case ARM::D27:
301 case ARM::D28:
302 case ARM::D29:
303 case ARM::D30:
304 case ARM::D31:
305 return SpillArea::DPRCS1;
306 }
307}
308
309ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
310 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
311 STI(sti) {}
312
313bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
314 // iOS always has a FP for backtracking, force other targets to keep their FP
315 // when doing FastISel. The emitted code is currently superior, and in cases
316 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
317 return MF.getSubtarget<ARMSubtarget>().useFastISel();
318}
319
320/// Returns true if the target can safely skip saving callee-saved registers
321/// for noreturn nounwind functions.
322bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
323 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
324 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
325 !MF.getFunction().hasFnAttribute(Attribute::UWTable));
326
327 // Frame pointer and link register are not treated as normal CSR, thus we
328 // can always skip CSR saves for nonreturning functions.
329 return true;
330}
331
332/// hasFPImpl - Return true if the specified function should have a dedicated
333/// frame pointer register. This is true if the function has variable sized
334/// allocas or if frame pointer elimination is disabled.
335bool ARMFrameLowering::hasFPImpl(const MachineFunction &MF) const {
336 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
337 const MachineFrameInfo &MFI = MF.getFrameInfo();
338
339 // Check to see if the target want to forcibly keep frame pointer.
340 if (keepFramePointer(MF))
341 return true;
342
343 // ABI-required frame pointer.
344 if (MF.disableFramePointerElim())
345 return true;
346
347 // Frame pointer required for use within this function.
348 return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
349 MFI.isFrameAddressTaken());
350}
351
352/// isFPReserved - Return true if the frame pointer register should be
353/// considered a reserved register on the scope of the specified function.
354bool ARMFrameLowering::isFPReserved(const MachineFunction &MF) const {
355 return hasFP(MF) || MF.framePointerIsReserved();
356}
357
358/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
359/// not required, we reserve argument space for call sites in the function
360/// immediately on entry to the current function. This eliminates the need for
361/// add/sub sp brackets around call sites. Returns true if the call frame is
362/// included as part of the stack frame.
363bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
364 const MachineFrameInfo &MFI = MF.getFrameInfo();
365 unsigned CFSize = MFI.getMaxCallFrameSize();
366 // It's not always a good idea to include the call frame as part of the
367 // stack frame. ARM (especially Thumb) has small immediate offset to
368 // address the stack frame. So a large call frame can cause poor codegen
369 // and may even makes it impossible to scavenge a register.
370 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
371 return false;
372
373 return !MFI.hasVarSizedObjects();
374}
375
376/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
377/// call frame pseudos can be simplified. Unlike most targets, having a FP
378/// is not sufficient here since we still may reference some objects via SP
379/// even when FP is available in Thumb2 mode.
380bool
381ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
382 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
383}
384
385// Returns how much of the incoming argument stack area we should clean up in an
386// epilogue. For the C calling convention this will be 0, for guaranteed tail
387// call conventions it can be positive (a normal return or a tail call to a
388// function that uses less stack space for arguments) or negative (for a tail
389// call to a function that needs more stack space than us for arguments).
390static int getArgumentStackToRestore(MachineFunction &MF,
391 MachineBasicBlock &MBB) {
392 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
393 bool IsTailCallReturn = false;
394 if (MBB.end() != MBBI) {
395 unsigned RetOpcode = MBBI->getOpcode();
396 IsTailCallReturn = RetOpcode == ARM::TCRETURNdi ||
397 RetOpcode == ARM::TCRETURNri ||
398 RetOpcode == ARM::TCRETURNrinotr12;
399 }
400 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
401
402 int ArgumentPopSize = 0;
403 if (IsTailCallReturn) {
404 MachineOperand &StackAdjust = MBBI->getOperand(i: 1);
405
406 // For a tail-call in a callee-pops-arguments environment, some or all of
407 // the stack may actually be in use for the call's arguments, this is
408 // calculated during LowerCall and consumed here...
409 ArgumentPopSize = StackAdjust.getImm();
410 } else {
411 // ... otherwise the amount to pop is *all* of the argument space,
412 // conveniently stored in the MachineFunctionInfo by
413 // LowerFormalArguments. This will, of course, be zero for the C calling
414 // convention.
415 ArgumentPopSize = AFI->getArgumentStackToRestore();
416 }
417
418 return ArgumentPopSize;
419}
420
421// Given a load or a store instruction, generate an appropriate unwinding SEH
422// code on Windows.
423static MachineBasicBlock::iterator insertSEH(MachineBasicBlock::iterator MBBI,
424 const TargetInstrInfo &TII,
425 unsigned Flags) {
426 unsigned Opc = MBBI->getOpcode();
427 MachineBasicBlock *MBB = MBBI->getParent();
428 MachineFunction &MF = *MBB->getParent();
429 DebugLoc DL = MBBI->getDebugLoc();
430 MachineInstrBuilder MIB;
431 const ARMSubtarget &Subtarget = MF.getSubtarget<ARMSubtarget>();
432 const ARMBaseRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
433
434 Flags |= MachineInstr::NoMerge;
435
436 switch (Opc) {
437 default:
438 report_fatal_error(reason: "No SEH Opcode for instruction " + TII.getName(Opcode: Opc));
439 break;
440 case ARM::t2ADDri: // add.w r11, sp, #xx
441 case ARM::t2ADDri12: // add.w r11, sp, #xx
442 case ARM::t2MOVTi16: // movt r4, #xx
443 case ARM::tBL: // bl __chkstk
444 // These are harmless if used for just setting up a frame pointer,
445 // but that frame pointer can't be relied upon for unwinding, unless
446 // set up with SEH_SaveSP.
447 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
448 .addImm(/*Wide=*/Val: 1)
449 .setMIFlags(Flags);
450 break;
451
452 case ARM::t2MOVi16: { // mov(w) r4, #xx
453 bool Wide = MBBI->getOperand(i: 1).getImm() >= 256;
454 if (!Wide) {
455 MachineInstrBuilder NewInstr =
456 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVi8)).setMIFlags(MBBI->getFlags());
457 NewInstr.add(MO: MBBI->getOperand(i: 0));
458 NewInstr.add(MO: t1CondCodeOp(/*isDead=*/true));
459 for (MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MBBI->operands()))
460 NewInstr.add(MO);
461 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(I: MBBI, MI: NewInstr);
462 MBB->erase(I: MBBI);
463 MBBI = NewMBBI;
464 }
465 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop)).addImm(Val: Wide).setMIFlags(Flags);
466 break;
467 }
468
469 case ARM::tBLXr: // blx r12 (__chkstk)
470 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
471 .addImm(/*Wide=*/Val: 0)
472 .setMIFlags(Flags);
473 break;
474
475 case ARM::t2MOVi32imm: // movw+movt
476 // This pseudo instruction expands into two mov instructions. If the
477 // second operand is a symbol reference, this will stay as two wide
478 // instructions, movw+movt. If they're immediates, the first one can
479 // end up as a narrow mov though.
480 // As two SEH instructions are appended here, they won't get interleaved
481 // between the two final movw/movt instructions, but it doesn't make any
482 // practical difference.
483 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
484 .addImm(/*Wide=*/Val: 1)
485 .setMIFlags(Flags);
486 MBB->insertAfter(I: MBBI, MI: MIB);
487 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop))
488 .addImm(/*Wide=*/Val: 1)
489 .setMIFlags(Flags);
490 break;
491
492 case ARM::t2STR_PRE:
493 if (MBBI->getOperand(i: 0).getReg() == ARM::SP &&
494 MBBI->getOperand(i: 2).getReg() == ARM::SP &&
495 MBBI->getOperand(i: 3).getImm() == -4) {
496 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 1).getReg());
497 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveRegs))
498 .addImm(Val: 1ULL << Reg)
499 .addImm(/*Wide=*/Val: 1)
500 .setMIFlags(Flags);
501 } else {
502 report_fatal_error(reason: "No matching SEH Opcode for t2STR_PRE");
503 }
504 break;
505
506 case ARM::t2LDR_POST:
507 if (MBBI->getOperand(i: 1).getReg() == ARM::SP &&
508 MBBI->getOperand(i: 2).getReg() == ARM::SP &&
509 MBBI->getOperand(i: 3).getImm() == 4) {
510 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 0).getReg());
511 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveRegs))
512 .addImm(Val: 1ULL << Reg)
513 .addImm(/*Wide=*/Val: 1)
514 .setMIFlags(Flags);
515 } else {
516 report_fatal_error(reason: "No matching SEH Opcode for t2LDR_POST");
517 }
518 break;
519
520 case ARM::t2LDMIA_RET:
521 case ARM::t2LDMIA_UPD:
522 case ARM::t2STMDB_UPD: {
523 unsigned Mask = 0;
524 bool Wide = false;
525 for (unsigned i = 4, NumOps = MBBI->getNumOperands(); i != NumOps; ++i) {
526 const MachineOperand &MO = MBBI->getOperand(i);
527 if (!MO.isReg() || MO.isImplicit())
528 continue;
529 unsigned Reg = RegInfo->getSEHRegNum(i: MO.getReg());
530 if (Reg == 15)
531 Reg = 14;
532 if (Reg >= 8 && Reg <= 13)
533 Wide = true;
534 else if (Opc == ARM::t2LDMIA_UPD && Reg == 14)
535 Wide = true;
536 Mask |= 1 << Reg;
537 }
538 if (!Wide) {
539 unsigned NewOpc;
540 switch (Opc) {
541 case ARM::t2LDMIA_RET:
542 NewOpc = ARM::tPOP_RET;
543 break;
544 case ARM::t2LDMIA_UPD:
545 NewOpc = ARM::tPOP;
546 break;
547 case ARM::t2STMDB_UPD:
548 NewOpc = ARM::tPUSH;
549 break;
550 default:
551 llvm_unreachable("");
552 }
553 MachineInstrBuilder NewInstr =
554 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: NewOpc)).setMIFlags(MBBI->getFlags());
555 for (unsigned i = 2, NumOps = MBBI->getNumOperands(); i != NumOps; ++i)
556 NewInstr.add(MO: MBBI->getOperand(i));
557 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(I: MBBI, MI: NewInstr);
558 MBB->erase(I: MBBI);
559 MBBI = NewMBBI;
560 }
561 unsigned SEHOpc =
562 (Opc == ARM::t2LDMIA_RET) ? ARM::SEH_SaveRegs_Ret : ARM::SEH_SaveRegs;
563 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: SEHOpc))
564 .addImm(Val: Mask)
565 .addImm(Val: Wide ? 1 : 0)
566 .setMIFlags(Flags);
567 break;
568 }
569 case ARM::VSTMDDB_UPD:
570 case ARM::VLDMDIA_UPD: {
571 int First = -1, Last = 0;
572 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MBBI->operands(), N: 4)) {
573 unsigned Reg = RegInfo->getSEHRegNum(i: MO.getReg());
574 if (First == -1)
575 First = Reg;
576 Last = Reg;
577 }
578 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveFRegs))
579 .addImm(Val: First)
580 .addImm(Val: Last)
581 .setMIFlags(Flags);
582 break;
583 }
584 case ARM::tSUBspi:
585 case ARM::tADDspi:
586 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_StackAlloc))
587 .addImm(Val: MBBI->getOperand(i: 2).getImm() * 4)
588 .addImm(/*Wide=*/Val: 0)
589 .setMIFlags(Flags);
590 break;
591 case ARM::t2SUBspImm:
592 case ARM::t2SUBspImm12:
593 case ARM::t2ADDspImm:
594 case ARM::t2ADDspImm12:
595 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_StackAlloc))
596 .addImm(Val: MBBI->getOperand(i: 2).getImm())
597 .addImm(/*Wide=*/Val: 1)
598 .setMIFlags(Flags);
599 break;
600
601 case ARM::tMOVr:
602 if (MBBI->getOperand(i: 1).getReg() == ARM::SP &&
603 (Flags & MachineInstr::FrameSetup)) {
604 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 0).getReg());
605 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveSP))
606 .addImm(Val: Reg)
607 .setMIFlags(Flags);
608 } else if (MBBI->getOperand(i: 0).getReg() == ARM::SP &&
609 (Flags & MachineInstr::FrameDestroy)) {
610 unsigned Reg = RegInfo->getSEHRegNum(i: MBBI->getOperand(i: 1).getReg());
611 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_SaveSP))
612 .addImm(Val: Reg)
613 .setMIFlags(Flags);
614 } else {
615 report_fatal_error(reason: "No SEH Opcode for MOV");
616 }
617 break;
618
619 case ARM::tBX_RET:
620 case ARM::t2BXAUT_RET:
621 case ARM::CLEANUPRET:
622 case ARM::CATCHRET:
623 case ARM::TCRETURNri:
624 case ARM::TCRETURNrinotr12:
625 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop_Ret))
626 .addImm(/*Wide=*/Val: 0)
627 .setMIFlags(Flags);
628 break;
629
630 case ARM::TCRETURNdi:
631 MIB = BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: ARM::SEH_Nop_Ret))
632 .addImm(/*Wide=*/Val: 1)
633 .setMIFlags(Flags);
634 break;
635 }
636 return MBB->insertAfter(I: MBBI, MI: MIB);
637}
638
639static MachineBasicBlock::iterator
640initMBBRange(MachineBasicBlock &MBB, const MachineBasicBlock::iterator &MBBI) {
641 if (MBBI == MBB.begin())
642 return MachineBasicBlock::iterator();
643 return std::prev(x: MBBI);
644}
645
646static void insertSEHRange(MachineBasicBlock &MBB,
647 MachineBasicBlock::iterator Start,
648 const MachineBasicBlock::iterator &End,
649 const ARMBaseInstrInfo &TII, unsigned MIFlags) {
650 if (Start.isValid())
651 Start = std::next(x: Start);
652 else
653 Start = MBB.begin();
654
655 for (auto MI = Start; MI != End;) {
656 auto Next = std::next(x: MI);
657 // Check if this instruction already has got a SEH opcode added. In that
658 // case, don't do this generic mapping.
659 if (Next != End && isSEHInstruction(MI: *Next)) {
660 MI = std::next(x: Next);
661 while (MI != End && isSEHInstruction(MI: *MI))
662 ++MI;
663 continue;
664 }
665 insertSEH(MBBI: MI, TII, Flags: MIFlags);
666 MI = Next;
667 }
668}
669
670static void emitRegPlusImmediate(
671 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
672 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
673 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
674 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
675 if (isARM)
676 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, BaseReg: SrcReg, NumBytes,
677 Pred, PredReg, TII, MIFlags);
678 else
679 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, BaseReg: SrcReg, NumBytes,
680 Pred, PredReg, TII, MIFlags);
681}
682
683static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
684 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
685 const ARMBaseInstrInfo &TII, int NumBytes,
686 unsigned MIFlags = MachineInstr::NoFlags,
687 ARMCC::CondCodes Pred = ARMCC::AL,
688 unsigned PredReg = 0) {
689 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, DestReg: ARM::SP, SrcReg: ARM::SP, NumBytes,
690 MIFlags, Pred, PredReg);
691}
692
693static int sizeOfSPAdjustment(const MachineInstr &MI) {
694 int RegSize;
695 switch (MI.getOpcode()) {
696 case ARM::VSTMDDB_UPD:
697 RegSize = 8;
698 break;
699 case ARM::STMDB_UPD:
700 case ARM::t2STMDB_UPD:
701 RegSize = 4;
702 break;
703 case ARM::t2STR_PRE:
704 case ARM::STR_PRE_IMM:
705 return 4;
706 default:
707 llvm_unreachable("Unknown push or pop like instruction");
708 }
709
710 int count = 0;
711 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
712 // pred) so the list starts at 4.
713 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
714 count += RegSize;
715 return count;
716}
717
718static bool WindowsRequiresStackProbe(const MachineFunction &MF,
719 size_t StackSizeInBytes) {
720 const MachineFrameInfo &MFI = MF.getFrameInfo();
721 const Function &F = MF.getFunction();
722 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
723
724 StackProbeSize =
725 F.getFnAttributeAsParsedInteger(Kind: "stack-probe-size", Default: StackProbeSize);
726 return (StackSizeInBytes >= StackProbeSize) &&
727 !F.hasFnAttribute(Kind: "no-stack-arg-probe");
728}
729
730namespace {
731
732struct StackAdjustingInsts {
733 struct InstInfo {
734 MachineBasicBlock::iterator I;
735 unsigned SPAdjust;
736 bool BeforeFPSet;
737
738#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
739 void dump() {
740 dbgs() << " " << (BeforeFPSet ? "before-fp " : " ")
741 << "sp-adjust=" << SPAdjust;
742 I->dump();
743 }
744#endif
745 };
746
747 SmallVector<InstInfo, 4> Insts;
748
749 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
750 bool BeforeFPSet = false) {
751 InstInfo Info = {.I: I, .SPAdjust: SPAdjust, .BeforeFPSet: BeforeFPSet};
752 Insts.push_back(Elt: Info);
753 }
754
755 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
756 auto Info =
757 llvm::find_if(Range&: Insts, P: [&](InstInfo &Info) { return Info.I == I; });
758 assert(Info != Insts.end() && "invalid sp adjusting instruction");
759 Info->SPAdjust += ExtraBytes;
760 }
761
762 void emitDefCFAOffsets(MachineBasicBlock &MBB, bool HasFP) {
763 CFIInstBuilder CFIBuilder(MBB, MBB.end(), MachineInstr::FrameSetup);
764 unsigned CFAOffset = 0;
765 for (auto &Info : Insts) {
766 if (HasFP && !Info.BeforeFPSet)
767 return;
768
769 CFAOffset += Info.SPAdjust;
770 CFIBuilder.setInsertPoint(std::next(x: Info.I));
771 CFIBuilder.buildDefCFAOffset(Offset: CFAOffset);
772 }
773 }
774
775#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
776 void dump() {
777 dbgs() << "StackAdjustingInsts:\n";
778 for (auto &Info : Insts)
779 Info.dump();
780 }
781#endif
782};
783
784} // end anonymous namespace
785
786/// Emit an instruction sequence that will align the address in
787/// register Reg by zero-ing out the lower bits. For versions of the
788/// architecture that support Neon, this must be done in a single
789/// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
790/// single instruction. That function only gets called when optimizing
791/// spilling of D registers on a core with the Neon instruction set
792/// present.
793static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
794 const TargetInstrInfo &TII,
795 MachineBasicBlock &MBB,
796 MachineBasicBlock::iterator MBBI,
797 const DebugLoc &DL, const unsigned Reg,
798 const Align Alignment,
799 const bool MustBeSingleInstruction) {
800 const ARMSubtarget &AST = MF.getSubtarget<ARMSubtarget>();
801 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
802 const unsigned AlignMask = Alignment.value() - 1U;
803 const unsigned NrBitsToZero = Log2(A: Alignment);
804 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
805 if (!AFI->isThumbFunction()) {
806 // if the BFC instruction is available, use that to zero the lower
807 // bits:
808 // bfc Reg, #0, log2(Alignment)
809 // otherwise use BIC, if the mask to zero the required number of bits
810 // can be encoded in the bic immediate field
811 // bic Reg, Reg, Alignment-1
812 // otherwise, emit
813 // lsr Reg, Reg, log2(Alignment)
814 // lsl Reg, Reg, log2(Alignment)
815 if (CanUseBFC) {
816 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::BFC), DestReg: Reg)
817 .addReg(RegNo: Reg, Flags: RegState::Kill)
818 .addImm(Val: ~AlignMask)
819 .add(MOs: predOps(Pred: ARMCC::AL));
820 } else if (AlignMask <= 255) {
821 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::BICri), DestReg: Reg)
822 .addReg(RegNo: Reg, Flags: RegState::Kill)
823 .addImm(Val: AlignMask)
824 .add(MOs: predOps(Pred: ARMCC::AL))
825 .add(MO: condCodeOp());
826 } else {
827 assert(!MustBeSingleInstruction &&
828 "Shouldn't call emitAligningInstructions demanding a single "
829 "instruction to be emitted for large stack alignment for a target "
830 "without BFC.");
831 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVsi), DestReg: Reg)
832 .addReg(RegNo: Reg, Flags: RegState::Kill)
833 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsr, Imm: NrBitsToZero))
834 .add(MOs: predOps(Pred: ARMCC::AL))
835 .add(MO: condCodeOp());
836 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVsi), DestReg: Reg)
837 .addReg(RegNo: Reg, Flags: RegState::Kill)
838 .addImm(Val: ARM_AM::getSORegOpc(ShOp: ARM_AM::lsl, Imm: NrBitsToZero))
839 .add(MOs: predOps(Pred: ARMCC::AL))
840 .add(MO: condCodeOp());
841 }
842 } else {
843 // Since this is only reached for Thumb-2 targets, the BFC instruction
844 // should always be available.
845 assert(CanUseBFC);
846 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ARM::t2BFC), DestReg: Reg)
847 .addReg(RegNo: Reg, Flags: RegState::Kill)
848 .addImm(Val: ~AlignMask)
849 .add(MOs: predOps(Pred: ARMCC::AL));
850 }
851}
852
853/// We need the offset of the frame pointer relative to other MachineFrameInfo
854/// offsets which are encoded relative to SP at function begin.
855/// See also emitPrologue() for how the FP is set up.
856/// Unfortunately we cannot determine this value in determineCalleeSaves() yet
857/// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
858/// this to produce a conservative estimate that we check in an assert() later.
859static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI,
860 const MachineFunction &MF) {
861 ARMSubtarget::PushPopSplitVariation PushPopSplit =
862 STI.getPushPopSplitVariation(MF);
863 // For Thumb1, push.w isn't available, so the first push will always push
864 // r7 and lr onto the stack first.
865 if (AFI.isThumb1OnlyFunction())
866 return -AFI.getArgRegsSaveSize() - (2 * 4);
867 // This is a conservative estimation: Assume the frame pointer being r7 and
868 // pc("r15") up to r8 getting spilled before (= 8 registers).
869 int MaxRegBytes = 8 * 4;
870 if (PushPopSplit == ARMSubtarget::SplitR11AAPCSSignRA)
871 // Here, r11 can be stored below all of r4-r15.
872 MaxRegBytes = 11 * 4;
873 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) {
874 // Here, r11 can be stored below all of r4-r15 plus d8-d15.
875 MaxRegBytes = 11 * 4 + 8 * 8;
876 }
877 int FPCXTSaveSize =
878 (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0;
879 return -FPCXTSaveSize - AFI.getArgRegsSaveSize() - MaxRegBytes;
880}
881
882void ARMFrameLowering::emitPrologue(MachineFunction &MF,
883 MachineBasicBlock &MBB) const {
884 MachineBasicBlock::iterator MBBI = MBB.begin();
885 MachineFrameInfo &MFI = MF.getFrameInfo();
886 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
887 const TargetMachine &TM = MF.getTarget();
888 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
889 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
890 assert(!AFI->isThumb1OnlyFunction() &&
891 "This emitPrologue does not support Thumb1!");
892 bool isARM = !AFI->isThumbFunction();
893 Align Alignment = STI.getFrameLowering()->getStackAlign();
894 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
895 unsigned NumBytes = MFI.getStackSize();
896 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
897 int FPCXTSaveSize = 0;
898 bool NeedsWinCFI = MF.needsWinCFI();
899 ARMSubtarget::PushPopSplitVariation PushPopSplit =
900 STI.getPushPopSplitVariation(MF);
901
902 LLVM_DEBUG(dbgs() << "Emitting prologue for " << MF.getName() << "\n");
903
904 // Debug location must be unknown since the first debug location is used
905 // to determine the end of the prologue.
906 DebugLoc dl;
907
908 Register FramePtr = RegInfo->getFrameRegister(MF);
909
910 // Determine the sizes of each callee-save spill areas and record which frame
911 // belongs to which callee-save spill areas.
912 unsigned GPRCS1Size = 0, GPRCS2Size = 0, FPStatusSize = 0,
913 DPRCS1Size = 0, GPRCS3Size = 0, DPRCS2Size = 0;
914 int FramePtrSpillFI = 0;
915 int D8SpillFI = 0;
916
917 // All calls are tail calls in GHC calling conv, and functions have no
918 // prologue/epilogue.
919 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
920 return;
921
922 StackAdjustingInsts DefCFAOffsetCandidates;
923 bool HasFP = hasFP(MF);
924
925 if (!AFI->hasStackFrame() &&
926 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, StackSizeInBytes: NumBytes))) {
927 if (NumBytes != 0) {
928 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -NumBytes,
929 MIFlags: MachineInstr::FrameSetup);
930 DefCFAOffsetCandidates.addInst(I: std::prev(x: MBBI), SPAdjust: NumBytes, BeforeFPSet: true);
931 }
932 if (!NeedsWinCFI)
933 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, HasFP);
934 if (NeedsWinCFI && MBBI != MBB.begin()) {
935 insertSEHRange(MBB, Start: {}, End: MBBI, TII, MIFlags: MachineInstr::FrameSetup);
936 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_PrologEnd))
937 .setMIFlag(MachineInstr::FrameSetup);
938 MF.setHasWinCFI(true);
939 }
940 return;
941 }
942
943 // Determine spill area sizes, and some important frame indices.
944 SpillArea FramePtrSpillArea = SpillArea::GPRCS1;
945 bool BeforeFPPush = true;
946 for (const CalleeSavedInfo &I : CSI) {
947 MCRegister Reg = I.getReg();
948 int FI = I.getFrameIdx();
949
950 SpillArea Area = getSpillArea(Reg, Variation: PushPopSplit,
951 NumAlignedDPRCS2Regs: AFI->getNumAlignedDPRCS2Regs(), RegInfo);
952
953 if (Reg == FramePtr.asMCReg()) {
954 FramePtrSpillFI = FI;
955 FramePtrSpillArea = Area;
956 }
957 if (Reg == ARM::D8)
958 D8SpillFI = FI;
959
960 switch (Area) {
961 case SpillArea::FPCXT:
962 FPCXTSaveSize += 4;
963 break;
964 case SpillArea::GPRCS1:
965 GPRCS1Size += 4;
966 break;
967 case SpillArea::GPRCS2:
968 GPRCS2Size += 4;
969 break;
970 case SpillArea::FPStatus:
971 FPStatusSize += 4;
972 break;
973 case SpillArea::DPRCS1:
974 DPRCS1Size += 8;
975 break;
976 case SpillArea::GPRCS3:
977 GPRCS3Size += 4;
978 break;
979 case SpillArea::DPRCS2:
980 DPRCS2Size += 8;
981 break;
982 }
983 }
984
985 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
986 DPRCS1Push, GPRCS3Push;
987
988 // Move past the PAC computation.
989 if (AFI->shouldSignReturnAddress())
990 LastPush = MBBI++;
991
992 // Move past FPCXT area.
993 if (FPCXTSaveSize > 0) {
994 LastPush = MBBI++;
995 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: FPCXTSaveSize, BeforeFPSet: BeforeFPPush);
996 }
997
998 // Allocate the vararg register save area.
999 if (ArgRegsSaveSize) {
1000 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -ArgRegsSaveSize,
1001 MIFlags: MachineInstr::FrameSetup);
1002 LastPush = std::prev(x: MBBI);
1003 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: ArgRegsSaveSize, BeforeFPSet: BeforeFPPush);
1004 }
1005
1006 // Move past area 1.
1007 if (GPRCS1Size > 0) {
1008 GPRCS1Push = LastPush = MBBI++;
1009 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: GPRCS1Size, BeforeFPSet: BeforeFPPush);
1010 if (FramePtrSpillArea == SpillArea::GPRCS1)
1011 BeforeFPPush = false;
1012 }
1013
1014 // Determine starting offsets of spill areas. These offsets are all positive
1015 // offsets from the bottom of the lowest-addressed callee-save area
1016 // (excluding DPRCS2, which is th the re-aligned stack region) to the bottom
1017 // of the spill area in question.
1018 unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize;
1019 unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size;
1020 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
1021 unsigned FPStatusOffset = GPRCS2Offset - FPStatusSize;
1022
1023 Align DPRAlign = DPRCS1Size ? std::min(a: Align(8), b: Alignment) : Align(4);
1024 unsigned DPRGapSize = (ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1025 GPRCS2Size + FPStatusSize) %
1026 DPRAlign.value();
1027
1028 unsigned DPRCS1Offset = FPStatusOffset - DPRGapSize - DPRCS1Size;
1029
1030 if (HasFP) {
1031 // Offset from the CFA to the saved frame pointer, will be negative.
1032 [[maybe_unused]] int FPOffset = MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI);
1033 LLVM_DEBUG(dbgs() << "FramePtrSpillFI: " << FramePtrSpillFI
1034 << ", FPOffset: " << FPOffset << "\n");
1035 assert(getMaxFPOffset(STI, *AFI, MF) <= FPOffset &&
1036 "Max FP estimation is wrong");
1037 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI) +
1038 NumBytes);
1039 }
1040 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1041 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1042 AFI->setDPRCalleeSavedArea1Offset(DPRCS1Offset);
1043
1044 // Move past area 2.
1045 if (GPRCS2Size > 0) {
1046 assert(PushPopSplit != ARMSubtarget::SplitR11WindowsSEH);
1047 GPRCS2Push = LastPush = MBBI++;
1048 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: GPRCS2Size, BeforeFPSet: BeforeFPPush);
1049 if (FramePtrSpillArea == SpillArea::GPRCS2)
1050 BeforeFPPush = false;
1051 }
1052
1053 // Move past FP status save area.
1054 if (FPStatusSize > 0) {
1055 while (MBBI != MBB.end()) {
1056 unsigned Opc = MBBI->getOpcode();
1057 if (Opc == ARM::VMRS || Opc == ARM::VMRS_FPEXC)
1058 MBBI++;
1059 else
1060 break;
1061 }
1062 LastPush = MBBI++;
1063 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: FPStatusSize);
1064 }
1065
1066 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
1067 // .cfi_offset operations will reflect that.
1068 if (DPRGapSize) {
1069 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
1070 if (LastPush != MBB.end() &&
1071 tryFoldSPUpdateIntoPushPop(Subtarget: STI, MF, MI: &*LastPush, NumBytes: DPRGapSize))
1072 DefCFAOffsetCandidates.addExtraBytes(I: LastPush, ExtraBytes: DPRGapSize);
1073 else {
1074 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -DPRGapSize,
1075 MIFlags: MachineInstr::FrameSetup);
1076 DefCFAOffsetCandidates.addInst(I: std::prev(x: MBBI), SPAdjust: DPRGapSize, BeforeFPSet: BeforeFPPush);
1077 }
1078 }
1079
1080 // Move past DPRCS1Size.
1081 if (DPRCS1Size > 0) {
1082 // Since vpush register list cannot have gaps, there may be multiple vpush
1083 // instructions in the prologue.
1084 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
1085 DefCFAOffsetCandidates.addInst(I: MBBI, SPAdjust: sizeOfSPAdjustment(MI: *MBBI),
1086 BeforeFPSet: BeforeFPPush);
1087 DPRCS1Push = LastPush = MBBI++;
1088 }
1089 }
1090
1091 // Move past the aligned DPRCS2 area.
1092 if (DPRCS2Size > 0) {
1093 MBBI = skipAlignedDPRCS2Spills(MI: MBBI, NumAlignedDPRCS2Regs: AFI->getNumAlignedDPRCS2Regs());
1094 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
1095 // leaves the stack pointer pointing to the DPRCS2 area.
1096 //
1097 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
1098 NumBytes += MFI.getObjectOffset(ObjectIdx: D8SpillFI);
1099 } else
1100 NumBytes = DPRCS1Offset;
1101
1102 // Move GPRCS3, if using using SplitR11WindowsSEH.
1103 if (GPRCS3Size > 0) {
1104 assert(PushPopSplit == ARMSubtarget::SplitR11WindowsSEH);
1105 GPRCS3Push = LastPush = MBBI++;
1106 DefCFAOffsetCandidates.addInst(I: LastPush, SPAdjust: GPRCS3Size, BeforeFPSet: BeforeFPPush);
1107 if (FramePtrSpillArea == SpillArea::GPRCS3)
1108 BeforeFPPush = false;
1109 NumBytes -= GPRCS3Size;
1110 }
1111
1112 bool NeedsWinCFIStackAlloc = NeedsWinCFI;
1113 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH && HasFP)
1114 NeedsWinCFIStackAlloc = false;
1115
1116 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, StackSizeInBytes: NumBytes)) {
1117 uint32_t NumWords = NumBytes >> 2;
1118
1119 if (NumWords < 65536) {
1120 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVi16), DestReg: ARM::R4)
1121 .addImm(Val: NumWords)
1122 .setMIFlags(MachineInstr::FrameSetup)
1123 .add(MOs: predOps(Pred: ARMCC::AL));
1124 } else {
1125 // Split into two instructions here, instead of using t2MOVi32imm,
1126 // to allow inserting accurate SEH instructions (including accurate
1127 // instruction size for each of them).
1128 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVi16), DestReg: ARM::R4)
1129 .addImm(Val: NumWords & 0xffff)
1130 .setMIFlags(MachineInstr::FrameSetup)
1131 .add(MOs: predOps(Pred: ARMCC::AL));
1132 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVTi16), DestReg: ARM::R4)
1133 .addReg(RegNo: ARM::R4)
1134 .addImm(Val: NumWords >> 16)
1135 .setMIFlags(MachineInstr::FrameSetup)
1136 .add(MOs: predOps(Pred: ARMCC::AL));
1137 }
1138
1139 const ARMTargetLowering *TLI = STI.getTargetLowering();
1140 RTLIB::LibcallImpl ChkStkLibcall = TLI->getLibcallImpl(Call: RTLIB::STACK_PROBE);
1141 if (ChkStkLibcall == RTLIB::Unsupported)
1142 reportFatalUsageError(reason: "no available implementation of __chkstk");
1143 const char *ChkStk = TLI->getLibcallImplName(Call: ChkStkLibcall).data();
1144
1145 switch (TM.getCodeModel()) {
1146 case CodeModel::Tiny:
1147 llvm_unreachable("Tiny code model not available on ARM.");
1148 case CodeModel::Small:
1149 case CodeModel::Medium:
1150 case CodeModel::Kernel:
1151 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tBL))
1152 .add(MOs: predOps(Pred: ARMCC::AL))
1153 .addExternalSymbol(FnName: ChkStk)
1154 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit)
1155 .setMIFlags(MachineInstr::FrameSetup);
1156 break;
1157 case CodeModel::Large:
1158 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2MOVi32imm), DestReg: ARM::R12)
1159 .addExternalSymbol(FnName: ChkStk)
1160 .setMIFlags(MachineInstr::FrameSetup);
1161
1162 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tBLXr))
1163 .add(MOs: predOps(Pred: ARMCC::AL))
1164 .addReg(RegNo: ARM::R12, Flags: RegState::Kill)
1165 .addReg(RegNo: ARM::R4, Flags: RegState::Implicit)
1166 .setMIFlags(MachineInstr::FrameSetup);
1167 break;
1168 }
1169
1170 MachineInstrBuilder Instr, SEH;
1171 Instr = BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::t2SUBrr), DestReg: ARM::SP)
1172 .addReg(RegNo: ARM::SP, Flags: RegState::Kill)
1173 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
1174 .setMIFlags(MachineInstr::FrameSetup)
1175 .add(MOs: predOps(Pred: ARMCC::AL))
1176 .add(MO: condCodeOp());
1177 if (NeedsWinCFIStackAlloc) {
1178 SEH = BuildMI(MF, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_StackAlloc))
1179 .addImm(Val: NumBytes)
1180 .addImm(/*Wide=*/Val: 1)
1181 .setMIFlags(MachineInstr::FrameSetup);
1182 MBB.insertAfter(I: Instr, MI: SEH);
1183 }
1184 NumBytes = 0;
1185 }
1186
1187 if (NumBytes) {
1188 // Adjust SP after all the callee-save spills.
1189 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
1190 tryFoldSPUpdateIntoPushPop(Subtarget: STI, MF, MI: &*LastPush, NumBytes))
1191 DefCFAOffsetCandidates.addExtraBytes(I: LastPush, ExtraBytes: NumBytes);
1192 else {
1193 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: -NumBytes,
1194 MIFlags: MachineInstr::FrameSetup);
1195 DefCFAOffsetCandidates.addInst(I: std::prev(x: MBBI), SPAdjust: NumBytes);
1196 }
1197
1198 if (HasFP && isARM)
1199 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
1200 // Note it's not safe to do this in Thumb2 mode because it would have
1201 // taken two instructions:
1202 // mov sp, r7
1203 // sub sp, #24
1204 // If an interrupt is taken between the two instructions, then sp is in
1205 // an inconsistent state (pointing to the middle of callee-saved area).
1206 // The interrupt handler can end up clobbering the registers.
1207 AFI->setShouldRestoreSPFromFP(true);
1208 }
1209
1210 // Set FP to point to the stack slot that contains the previous FP.
1211 // For iOS, FP is R7, which has now been stored in spill area 1.
1212 // Otherwise, if this is not iOS, all the callee-saved registers go
1213 // into spill area 1, including the FP in R11. In either case, it
1214 // is in area one and the adjustment needs to take place just after
1215 // that push.
1216 MachineBasicBlock::iterator AfterPush;
1217 if (HasFP) {
1218 MachineBasicBlock::iterator FPPushInst;
1219 // Offset from SP immediately after the push which saved the FP to the FP
1220 // save slot.
1221 int64_t FPOffsetAfterPush;
1222 switch (FramePtrSpillArea) {
1223 case SpillArea::GPRCS1:
1224 FPPushInst = GPRCS1Push;
1225 FPOffsetAfterPush = MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI) +
1226 ArgRegsSaveSize + FPCXTSaveSize +
1227 sizeOfSPAdjustment(MI: *FPPushInst);
1228 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS1, offset "
1229 << FPOffsetAfterPush << " after that push\n");
1230 break;
1231 case SpillArea::GPRCS2:
1232 FPPushInst = GPRCS2Push;
1233 FPOffsetAfterPush = MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI) +
1234 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1235 sizeOfSPAdjustment(MI: *FPPushInst);
1236 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS2, offset "
1237 << FPOffsetAfterPush << " after that push\n");
1238 break;
1239 case SpillArea::GPRCS3:
1240 FPPushInst = GPRCS3Push;
1241 FPOffsetAfterPush = MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI) +
1242 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1243 FPStatusSize + GPRCS2Size + DPRCS1Size + DPRGapSize +
1244 sizeOfSPAdjustment(MI: *FPPushInst);
1245 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS3, offset "
1246 << FPOffsetAfterPush << " after that push\n");
1247 break;
1248 default:
1249 llvm_unreachable("frame pointer in unknown spill area");
1250 break;
1251 }
1252 AfterPush = std::next(x: FPPushInst);
1253 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH)
1254 assert(FPOffsetAfterPush == 0);
1255
1256 // Emit the MOV or ADD to set up the frame pointer register.
1257 emitRegPlusImmediate(isARM: !AFI->isThumbFunction(), MBB, MBBI&: AfterPush, dl, TII,
1258 DestReg: FramePtr, SrcReg: ARM::SP, NumBytes: FPOffsetAfterPush,
1259 MIFlags: MachineInstr::FrameSetup);
1260
1261 if (!NeedsWinCFI) {
1262 // Emit DWARF info to find the CFA using the frame pointer from this
1263 // point onward.
1264 CFIInstBuilder CFIBuilder(MBB, AfterPush, MachineInstr::FrameSetup);
1265 if (FPOffsetAfterPush != 0)
1266 CFIBuilder.buildDefCFA(Reg: FramePtr, Offset: -MFI.getObjectOffset(ObjectIdx: FramePtrSpillFI));
1267 else
1268 CFIBuilder.buildDefCFARegister(Reg: FramePtr);
1269 }
1270 }
1271
1272 // Emit a SEH opcode indicating the prologue end. The rest of the prologue
1273 // instructions below don't need to be replayed to unwind the stack.
1274 if (NeedsWinCFI && MBBI != MBB.begin()) {
1275 MachineBasicBlock::iterator End = MBBI;
1276 if (HasFP && PushPopSplit == ARMSubtarget::SplitR11WindowsSEH)
1277 End = AfterPush;
1278 insertSEHRange(MBB, Start: {}, End, TII, MIFlags: MachineInstr::FrameSetup);
1279 BuildMI(BB&: MBB, I: End, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_PrologEnd))
1280 .setMIFlag(MachineInstr::FrameSetup);
1281 MF.setHasWinCFI(true);
1282 }
1283
1284 // Now that the prologue's actual instructions are finalised, we can insert
1285 // the necessary DWARF cf instructions to describe the situation. Start by
1286 // recording where each register ended up:
1287 if (!NeedsWinCFI) {
1288 for (const auto &Entry : reverse(C: CSI)) {
1289 MCRegister Reg = Entry.getReg();
1290 int FI = Entry.getFrameIdx();
1291 MachineBasicBlock::iterator CFIPos;
1292 switch (getSpillArea(Reg, Variation: PushPopSplit, NumAlignedDPRCS2Regs: AFI->getNumAlignedDPRCS2Regs(),
1293 RegInfo)) {
1294 case SpillArea::GPRCS1:
1295 CFIPos = std::next(x: GPRCS1Push);
1296 break;
1297 case SpillArea::GPRCS2:
1298 CFIPos = std::next(x: GPRCS2Push);
1299 break;
1300 case SpillArea::DPRCS1:
1301 CFIPos = std::next(x: DPRCS1Push);
1302 break;
1303 case SpillArea::GPRCS3:
1304 CFIPos = std::next(x: GPRCS3Push);
1305 break;
1306 case SpillArea::FPStatus:
1307 case SpillArea::FPCXT:
1308 case SpillArea::DPRCS2:
1309 // FPCXT and DPRCS2 are not represented in the DWARF info.
1310 break;
1311 }
1312
1313 if (CFIPos.isValid()) {
1314 CFIInstBuilder(MBB, CFIPos, MachineInstr::FrameSetup)
1315 .buildOffset(Reg: Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg,
1316 Offset: MFI.getObjectOffset(ObjectIdx: FI));
1317 }
1318 }
1319 }
1320
1321 // Now we can emit descriptions of where the canonical frame address was
1322 // throughout the process. If we have a frame pointer, it takes over the job
1323 // half-way through, so only the first few .cfi_def_cfa_offset instructions
1324 // actually get emitted.
1325 if (!NeedsWinCFI) {
1326 LLVM_DEBUG(DefCFAOffsetCandidates.dump());
1327 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, HasFP);
1328 }
1329
1330 if (STI.isTargetELF() && hasFP(MF))
1331 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
1332 AFI->getFramePtrSpillOffset());
1333
1334 AFI->setFPCXTSaveAreaSize(FPCXTSaveSize);
1335 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1336 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1337 AFI->setFPStatusSavesSize(FPStatusSize);
1338 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
1339 AFI->setDPRCalleeSavedArea1Size(DPRCS1Size);
1340 AFI->setGPRCalleeSavedArea3Size(GPRCS3Size);
1341
1342 // If we need dynamic stack realignment, do it here. Be paranoid and make
1343 // sure if we also have VLAs, we have a base pointer for frame access.
1344 // If aligned NEON registers were spilled, the stack has already been
1345 // realigned.
1346 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) {
1347 Align MaxAlign = MFI.getMaxAlign();
1348 assert(!AFI->isThumb1OnlyFunction());
1349 if (!AFI->isThumbFunction()) {
1350 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, DL: dl, Reg: ARM::SP, Alignment: MaxAlign,
1351 MustBeSingleInstruction: false);
1352 } else {
1353 // We cannot use sp as source/dest register here, thus we're using r4 to
1354 // perform the calculations. We're emitting the following sequence:
1355 // mov r4, sp
1356 // -- use emitAligningInstructions to produce best sequence to zero
1357 // -- out lower bits in r4
1358 // mov sp, r4
1359 // FIXME: It will be better just to find spare register here.
1360 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::R4)
1361 .addReg(RegNo: ARM::SP, Flags: RegState::Kill)
1362 .add(MOs: predOps(Pred: ARMCC::AL));
1363 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, DL: dl, Reg: ARM::R4, Alignment: MaxAlign,
1364 MustBeSingleInstruction: false);
1365 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::SP)
1366 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
1367 .add(MOs: predOps(Pred: ARMCC::AL));
1368 }
1369
1370 AFI->setShouldRestoreSPFromFP(true);
1371 }
1372
1373 // If we need a base pointer, set it up here. It's whatever the value
1374 // of the stack pointer is at this point. Any variable size objects
1375 // will be allocated after this, so we can still use the base pointer
1376 // to reference locals.
1377 // FIXME: Clarify FrameSetup flags here.
1378 if (RegInfo->hasBasePointer(MF) && !MBB.isEHFuncletEntry()) {
1379 if (isARM)
1380 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::MOVr), DestReg: RegInfo->getBaseRegister())
1381 .addReg(RegNo: ARM::SP)
1382 .add(MOs: predOps(Pred: ARMCC::AL))
1383 .add(MO: condCodeOp());
1384 else
1385 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: RegInfo->getBaseRegister())
1386 .addReg(RegNo: ARM::SP)
1387 .add(MOs: predOps(Pred: ARMCC::AL));
1388 }
1389
1390 // If the frame has variable sized objects then the epilogue must restore
1391 // the sp from fp. We can assume there's an FP here since hasFP already
1392 // checks for hasVarSizedObjects.
1393 if (MFI.hasVarSizedObjects())
1394 AFI->setShouldRestoreSPFromFP(true);
1395}
1396
1397void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
1398 MachineBasicBlock &MBB) const {
1399 MachineFrameInfo &MFI = MF.getFrameInfo();
1400 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1401 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1402 const ARMBaseInstrInfo &TII =
1403 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1404 assert(!AFI->isThumb1OnlyFunction() &&
1405 "This emitEpilogue does not support Thumb1!");
1406 bool isARM = !AFI->isThumbFunction();
1407 ARMSubtarget::PushPopSplitVariation PushPopSplit =
1408 STI.getPushPopSplitVariation(MF);
1409
1410 LLVM_DEBUG(dbgs() << "Emitting epilogue for " << MF.getName() << "\n");
1411
1412 // Amount of stack space we reserved next to incoming args for either
1413 // varargs registers or stack arguments in tail calls made by this function.
1414 unsigned ReservedArgStack = AFI->getArgRegsSaveSize();
1415
1416 // How much of the stack used by incoming arguments this function is expected
1417 // to restore in this particular epilogue.
1418 int IncomingArgStackToRestore = getArgumentStackToRestore(MF, MBB);
1419 int NumBytes = (int)MFI.getStackSize();
1420 Register FramePtr = RegInfo->getFrameRegister(MF);
1421
1422 // All calls are tail calls in GHC calling conv, and functions have no
1423 // prologue/epilogue.
1424 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
1425 return;
1426
1427 // First put ourselves on the first (from top) terminator instructions.
1428 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1429 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1430
1431 MachineBasicBlock::iterator RangeStart;
1432 if (!AFI->hasStackFrame()) {
1433 if (MF.hasWinCFI()) {
1434 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_EpilogStart))
1435 .setMIFlag(MachineInstr::FrameDestroy);
1436 RangeStart = initMBBRange(MBB, MBBI);
1437 }
1438
1439 if (NumBytes + IncomingArgStackToRestore != 0)
1440 emitSPUpdate(isARM, MBB, MBBI, dl, TII,
1441 NumBytes: NumBytes + IncomingArgStackToRestore,
1442 MIFlags: MachineInstr::FrameDestroy);
1443 } else {
1444 // Unwind MBBI to point to first LDR / VLDRD.
1445 if (MBBI != MBB.begin()) {
1446 do {
1447 --MBBI;
1448 } while (MBBI != MBB.begin() &&
1449 MBBI->getFlag(Flag: MachineInstr::FrameDestroy));
1450 if (!MBBI->getFlag(Flag: MachineInstr::FrameDestroy))
1451 ++MBBI;
1452 }
1453
1454 if (MF.hasWinCFI()) {
1455 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_EpilogStart))
1456 .setMIFlag(MachineInstr::FrameDestroy);
1457 RangeStart = initMBBRange(MBB, MBBI);
1458 }
1459
1460 // Move SP to start of FP callee save spill area.
1461 NumBytes -=
1462 (ReservedArgStack + AFI->getFPCXTSaveAreaSize() +
1463 AFI->getGPRCalleeSavedArea1Size() + AFI->getGPRCalleeSavedArea2Size() +
1464 AFI->getFPStatusSavesSize() + AFI->getDPRCalleeSavedGapSize() +
1465 AFI->getDPRCalleeSavedArea1Size() + AFI->getGPRCalleeSavedArea3Size());
1466
1467 // Reset SP based on frame pointer only if the stack frame extends beyond
1468 // frame pointer stack slot or target is ELF and the function has FP.
1469 if (AFI->shouldRestoreSPFromFP()) {
1470 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1471 if (NumBytes) {
1472 if (isARM)
1473 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg: ARM::SP, BaseReg: FramePtr, NumBytes: -NumBytes,
1474 Pred: ARMCC::AL, PredReg: 0, TII,
1475 MIFlags: MachineInstr::FrameDestroy);
1476 else {
1477 // It's not possible to restore SP from FP in a single instruction.
1478 // For iOS, this looks like:
1479 // mov sp, r7
1480 // sub sp, #24
1481 // This is bad, if an interrupt is taken after the mov, sp is in an
1482 // inconsistent state.
1483 // Use the first callee-saved register as a scratch register.
1484 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
1485 "No scratch register to restore SP from FP!");
1486 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg: ARM::R4, BaseReg: FramePtr, NumBytes: -NumBytes,
1487 Pred: ARMCC::AL, PredReg: 0, TII, MIFlags: MachineInstr::FrameDestroy);
1488 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::SP)
1489 .addReg(RegNo: ARM::R4)
1490 .add(MOs: predOps(Pred: ARMCC::AL))
1491 .setMIFlag(MachineInstr::FrameDestroy);
1492 }
1493 } else {
1494 // Thumb2 or ARM.
1495 if (isARM)
1496 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::MOVr), DestReg: ARM::SP)
1497 .addReg(RegNo: FramePtr)
1498 .add(MOs: predOps(Pred: ARMCC::AL))
1499 .add(MO: condCodeOp())
1500 .setMIFlag(MachineInstr::FrameDestroy);
1501 else
1502 BuildMI(BB&: MBB, I: MBBI, MIMD: dl, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::SP)
1503 .addReg(RegNo: FramePtr)
1504 .add(MOs: predOps(Pred: ARMCC::AL))
1505 .setMIFlag(MachineInstr::FrameDestroy);
1506 }
1507 } else if (NumBytes &&
1508 !tryFoldSPUpdateIntoPushPop(Subtarget: STI, MF, MI: &*MBBI, NumBytes))
1509 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
1510 MIFlags: MachineInstr::FrameDestroy);
1511
1512 // Increment past our save areas.
1513 if (AFI->getGPRCalleeSavedArea3Size()) {
1514 assert(PushPopSplit == ARMSubtarget::SplitR11WindowsSEH);
1515 (void)PushPopSplit;
1516 MBBI++;
1517 }
1518
1519 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedArea1Size()) {
1520 MBBI++;
1521 // Since vpop register list cannot have gaps, there may be multiple vpop
1522 // instructions in the epilogue.
1523 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
1524 MBBI++;
1525 }
1526 if (AFI->getDPRCalleeSavedGapSize()) {
1527 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
1528 "unexpected DPR alignment gap");
1529 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes: AFI->getDPRCalleeSavedGapSize(),
1530 MIFlags: MachineInstr::FrameDestroy);
1531 }
1532
1533 if (AFI->getGPRCalleeSavedArea2Size()) {
1534 assert(PushPopSplit != ARMSubtarget::SplitR11WindowsSEH);
1535 (void)PushPopSplit;
1536 MBBI++;
1537 }
1538 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
1539
1540 if (ReservedArgStack || IncomingArgStackToRestore) {
1541 assert((int)ReservedArgStack + IncomingArgStackToRestore >= 0 &&
1542 "attempting to restore negative stack amount");
1543 emitSPUpdate(isARM, MBB, MBBI, dl, TII,
1544 NumBytes: ReservedArgStack + IncomingArgStackToRestore,
1545 MIFlags: MachineInstr::FrameDestroy);
1546 }
1547
1548 // Validate PAC, It should have been already popped into R12. For CMSE entry
1549 // function, the validation instruction is emitted during expansion of the
1550 // tBXNS_RET, since the validation must use the value of SP at function
1551 // entry, before saving, resp. after restoring, FPCXTNS.
1552 if (AFI->shouldSignReturnAddress() && !AFI->isCmseNSEntryFunction()) {
1553 bool CanUseBXAut =
1554 STI.isThumb() && STI.hasV8_1MMainlineOps() && STI.hasPACBTI();
1555 auto TMBBI = MBB.getFirstTerminator();
1556 bool IsBXReturn =
1557 TMBBI != MBB.end() && TMBBI->getOpcode() == ARM::tBX_RET;
1558 if (IsBXReturn && CanUseBXAut)
1559 TMBBI->setDesc(STI.getInstrInfo()->get(Opcode: ARM::t2BXAUT_RET));
1560 else
1561 BuildMI(BB&: MBB, I: MBBI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::t2AUT));
1562 }
1563 }
1564
1565 if (MF.hasWinCFI()) {
1566 insertSEHRange(MBB, Start: RangeStart, End: MBB.end(), TII, MIFlags: MachineInstr::FrameDestroy);
1567 BuildMI(BB&: MBB, I: MBB.end(), MIMD: dl, MCID: TII.get(Opcode: ARM::SEH_EpilogEnd))
1568 .setMIFlag(MachineInstr::FrameDestroy);
1569 }
1570}
1571
1572/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1573/// debug info. It's the same as what we use for resolving the code-gen
1574/// references for now. FIXME: This can go wrong when references are
1575/// SP-relative and simple call frames aren't used.
1576StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF,
1577 int FI,
1578 Register &FrameReg) const {
1579 return StackOffset::getFixed(Fixed: ResolveFrameIndexReference(MF, FI, FrameReg, SPAdj: 0));
1580}
1581
1582StackOffset
1583ARMFrameLowering::getNonLocalFrameIndexReference(const MachineFunction &MF,
1584 int FI) const {
1585 const MachineFrameInfo &MFI = MF.getFrameInfo();
1586 int Offset = MFI.getObjectOffset(ObjectIdx: FI) + MFI.getStackSize();
1587 return StackOffset::getFixed(Fixed: Offset);
1588}
1589
1590int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
1591 int FI, Register &FrameReg,
1592 int SPAdj) const {
1593 const MachineFrameInfo &MFI = MF.getFrameInfo();
1594 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1595 MF.getSubtarget().getRegisterInfo());
1596 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1597 int Offset = MFI.getObjectOffset(ObjectIdx: FI) + MFI.getStackSize();
1598 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
1599 bool isFixed = MFI.isFixedObjectIndex(ObjectIdx: FI);
1600
1601 FrameReg = ARM::SP;
1602 Offset += SPAdj;
1603
1604 // SP can move around if there are allocas. We may also lose track of SP
1605 // when emergency spilling inside a non-reserved call frame setup.
1606 bool hasMovingSP = !hasReservedCallFrame(MF);
1607
1608 // When dynamically realigning the stack, use the frame pointer for
1609 // parameters, and the stack/base pointer for locals.
1610 if (RegInfo->hasStackRealignment(MF)) {
1611 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
1612 if (isFixed) {
1613 FrameReg = RegInfo->getFrameRegister(MF);
1614 Offset = FPOffset;
1615 } else if (hasMovingSP) {
1616 assert(RegInfo->hasBasePointer(MF) &&
1617 "VLAs and dynamic stack alignment, but missing base pointer!");
1618 FrameReg = RegInfo->getBaseRegister();
1619 Offset -= SPAdj;
1620 }
1621 return Offset;
1622 }
1623
1624 // If there is a frame pointer, use it when we can.
1625 if (hasFP(MF) && AFI->hasStackFrame()) {
1626 // Use frame pointer to reference fixed objects. Use it for locals if
1627 // there are VLAs (and thus the SP isn't reliable as a base).
1628 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
1629 FrameReg = RegInfo->getFrameRegister(MF);
1630 return FPOffset;
1631 } else if (hasMovingSP) {
1632 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
1633 if (AFI->isThumb2Function()) {
1634 // Try to use the frame pointer if we can, else use the base pointer
1635 // since it's available. This is handy for the emergency spill slot, in
1636 // particular.
1637 if (FPOffset >= -255 && FPOffset < 0) {
1638 FrameReg = RegInfo->getFrameRegister(MF);
1639 return FPOffset;
1640 }
1641 }
1642 } else if (AFI->isThumbFunction()) {
1643 // Prefer SP to base pointer, if the offset is suitably aligned and in
1644 // range as the effective range of the immediate offset is bigger when
1645 // basing off SP.
1646 // Use add <rd>, sp, #<imm8>
1647 // ldr <rd>, [sp, #<imm8>]
1648 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
1649 return Offset;
1650 // In Thumb2 mode, the negative offset is very limited. Try to avoid
1651 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
1652 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
1653 FrameReg = RegInfo->getFrameRegister(MF);
1654 return FPOffset;
1655 }
1656 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
1657 // Otherwise, use SP or FP, whichever is closer to the stack slot.
1658 FrameReg = RegInfo->getFrameRegister(MF);
1659 return FPOffset;
1660 }
1661 }
1662 // Use the base pointer if we have one.
1663 // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
1664 // That can happen if we forced a base pointer for a large call frame.
1665 if (RegInfo->hasBasePointer(MF)) {
1666 FrameReg = RegInfo->getBaseRegister();
1667 Offset -= SPAdj;
1668 }
1669 return Offset;
1670}
1671
1672void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
1673 MachineBasicBlock::iterator MI,
1674 ArrayRef<CalleeSavedInfo> CSI,
1675 unsigned StmOpc, unsigned StrOpc,
1676 bool NoGap,
1677 function_ref<bool(unsigned)> Func) const {
1678 MachineFunction &MF = *MBB.getParent();
1679 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1680 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1681
1682 DebugLoc DL;
1683
1684 using RegAndKill = std::pair<unsigned, bool>;
1685
1686 SmallVector<RegAndKill, 4> Regs;
1687 unsigned i = CSI.size();
1688 while (i != 0) {
1689 unsigned LastReg = 0;
1690 for (; i != 0; --i) {
1691 MCRegister Reg = CSI[i-1].getReg();
1692 if (!Func(Reg))
1693 continue;
1694
1695 const MachineRegisterInfo &MRI = MF.getRegInfo();
1696 bool isLiveIn = MRI.isLiveIn(Reg);
1697 if (!isLiveIn && !MRI.isReserved(PhysReg: Reg))
1698 MBB.addLiveIn(PhysReg: Reg);
1699 // If NoGap is true, push consecutive registers and then leave the rest
1700 // for other instructions. e.g.
1701 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
1702 if (NoGap && LastReg && LastReg != Reg-1)
1703 break;
1704 LastReg = Reg;
1705 // Do not set a kill flag on values that are also marked as live-in. This
1706 // happens with the @llvm-returnaddress intrinsic and with arguments
1707 // passed in callee saved registers.
1708 // Omitting the kill flags is conservatively correct even if the live-in
1709 // is not used after all.
1710 Regs.push_back(Elt: std::make_pair(x&: Reg, /*isKill=*/y: !isLiveIn));
1711 }
1712
1713 if (Regs.empty())
1714 continue;
1715
1716 llvm::sort(C&: Regs, Comp: [&](const RegAndKill &LHS, const RegAndKill &RHS) {
1717 return TRI.getEncodingValue(Reg: LHS.first) < TRI.getEncodingValue(Reg: RHS.first);
1718 });
1719
1720 if (Regs.size() > 1 || StrOpc== 0) {
1721 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: StmOpc), DestReg: ARM::SP)
1722 .addReg(RegNo: ARM::SP)
1723 .setMIFlags(MachineInstr::FrameSetup)
1724 .add(MOs: predOps(Pred: ARMCC::AL));
1725 for (const auto &[Reg, Kill] : Regs)
1726 MIB.addReg(RegNo: Reg, Flags: getKillRegState(B: Kill));
1727 } else if (Regs.size() == 1) {
1728 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: StrOpc), DestReg: ARM::SP)
1729 .addReg(RegNo: Regs[0].first, Flags: getKillRegState(B: Regs[0].second))
1730 .addReg(RegNo: ARM::SP)
1731 .setMIFlags(MachineInstr::FrameSetup)
1732 .addImm(Val: -4)
1733 .add(MOs: predOps(Pred: ARMCC::AL));
1734 }
1735 Regs.clear();
1736
1737 // Put any subsequent vpush instructions before this one: they will refer to
1738 // higher register numbers so need to be pushed first in order to preserve
1739 // monotonicity.
1740 if (MI != MBB.begin())
1741 --MI;
1742 }
1743}
1744
1745void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1746 MachineBasicBlock::iterator MI,
1747 MutableArrayRef<CalleeSavedInfo> CSI,
1748 unsigned LdmOpc, unsigned LdrOpc,
1749 bool isVarArg, bool NoGap,
1750 function_ref<bool(unsigned)> Func) const {
1751 MachineFunction &MF = *MBB.getParent();
1752 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1753 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1754 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1755 bool hasPAC = AFI->shouldSignReturnAddress();
1756 DebugLoc DL;
1757 bool isTailCall = false;
1758 bool isInterrupt = false;
1759 bool isTrap = false;
1760 bool isCmseEntry = false;
1761 ARMSubtarget::PushPopSplitVariation PushPopSplit =
1762 STI.getPushPopSplitVariation(MF);
1763 if (MBB.end() != MI) {
1764 DL = MI->getDebugLoc();
1765 unsigned RetOpcode = MI->getOpcode();
1766 isTailCall =
1767 (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri ||
1768 RetOpcode == ARM::TCRETURNrinotr12);
1769 isInterrupt =
1770 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1771 isTrap = RetOpcode == ARM::TRAP || RetOpcode == ARM::tTRAP;
1772 isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET);
1773 }
1774
1775 SmallVector<unsigned, 4> Regs;
1776 unsigned i = CSI.size();
1777 while (i != 0) {
1778 unsigned LastReg = 0;
1779 bool DeleteRet = false;
1780 for (; i != 0; --i) {
1781 CalleeSavedInfo &Info = CSI[i-1];
1782 MCRegister Reg = Info.getReg();
1783 if (!Func(Reg))
1784 continue;
1785
1786 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1787 !isCmseEntry && !isTrap && AFI->getArgumentStackToRestore() == 0 &&
1788 STI.hasV5TOps() && MBB.succ_empty() && !hasPAC &&
1789 (PushPopSplit != ARMSubtarget::SplitR11WindowsSEH &&
1790 PushPopSplit != ARMSubtarget::SplitR11AAPCSSignRA)) {
1791 Reg = ARM::PC;
1792 // Fold the return instruction into the LDM.
1793 DeleteRet = true;
1794 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1795 }
1796
1797 // If NoGap is true, pop consecutive registers and then leave the rest
1798 // for other instructions. e.g.
1799 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1800 if (NoGap && LastReg && LastReg != Reg-1)
1801 break;
1802
1803 LastReg = Reg;
1804 Regs.push_back(Elt: Reg);
1805 }
1806
1807 if (Regs.empty())
1808 continue;
1809
1810 llvm::sort(C&: Regs, Comp: [&](unsigned LHS, unsigned RHS) {
1811 return TRI.getEncodingValue(Reg: LHS) < TRI.getEncodingValue(Reg: RHS);
1812 });
1813
1814 if (Regs.size() > 1 || LdrOpc == 0) {
1815 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: LdmOpc), DestReg: ARM::SP)
1816 .addReg(RegNo: ARM::SP)
1817 .add(MOs: predOps(Pred: ARMCC::AL))
1818 .setMIFlags(MachineInstr::FrameDestroy);
1819 for (unsigned Reg : Regs)
1820 MIB.addReg(RegNo: Reg, Flags: getDefRegState(B: true));
1821 if (DeleteRet) {
1822 if (MI != MBB.end()) {
1823 MIB.copyImplicitOps(OtherMI: *MI);
1824 MI->eraseFromParent();
1825 }
1826 }
1827 MI = MIB;
1828 } else if (Regs.size() == 1) {
1829 // If we adjusted the reg to PC from LR above, switch it back here. We
1830 // only do that for LDM.
1831 if (Regs[0] == ARM::PC)
1832 Regs[0] = ARM::LR;
1833 MachineInstrBuilder MIB =
1834 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: LdrOpc), DestReg: Regs[0])
1835 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
1836 .addReg(RegNo: ARM::SP)
1837 .setMIFlags(MachineInstr::FrameDestroy);
1838 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1839 // that refactoring is complete (eventually).
1840 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1841 MIB.addReg(RegNo: 0);
1842 MIB.addImm(Val: ARM_AM::getAM2Opc(Opc: ARM_AM::add, Imm12: 4, SO: ARM_AM::no_shift));
1843 } else
1844 MIB.addImm(Val: 4);
1845 MIB.add(MOs: predOps(Pred: ARMCC::AL));
1846 }
1847 Regs.clear();
1848
1849 // Put any subsequent vpop instructions after this one: they will refer to
1850 // higher register numbers so need to be popped afterwards.
1851 if (MI != MBB.end())
1852 ++MI;
1853 }
1854}
1855
1856void ARMFrameLowering::emitFPStatusSaves(MachineBasicBlock &MBB,
1857 MachineBasicBlock::iterator MI,
1858 ArrayRef<CalleeSavedInfo> CSI,
1859 unsigned PushOpc) const {
1860 MachineFunction &MF = *MBB.getParent();
1861 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1862
1863 SmallVector<MCRegister> Regs;
1864 auto RegPresent = [&CSI](MCRegister Reg) {
1865 return llvm::any_of(Range&: CSI, P: [Reg](const CalleeSavedInfo &C) {
1866 return C.getReg() == Reg;
1867 });
1868 };
1869
1870 // If we need to save FPSCR, then we must move FPSCR into R4 with the VMRS
1871 // instruction.
1872 if (RegPresent(ARM::FPSCR)) {
1873 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: ARM::VMRS), DestReg: ARM::R4)
1874 .add(MOs: predOps(Pred: ARMCC::AL))
1875 .setMIFlags(MachineInstr::FrameSetup);
1876
1877 Regs.push_back(Elt: ARM::R4);
1878 }
1879
1880 // If we need to save FPEXC, then we must move FPEXC into R5 with the
1881 // VMRS_FPEXC instruction.
1882 if (RegPresent(ARM::FPEXC)) {
1883 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: ARM::VMRS_FPEXC), DestReg: ARM::R5)
1884 .add(MOs: predOps(Pred: ARMCC::AL))
1885 .setMIFlags(MachineInstr::FrameSetup);
1886
1887 Regs.push_back(Elt: ARM::R5);
1888 }
1889
1890 // If neither FPSCR and FPEXC are present, then do nothing.
1891 if (Regs.size() == 0)
1892 return;
1893
1894 // Push both R4 and R5 onto the stack, if present.
1895 MachineInstrBuilder MIB =
1896 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: PushOpc), DestReg: ARM::SP)
1897 .addReg(RegNo: ARM::SP)
1898 .add(MOs: predOps(Pred: ARMCC::AL))
1899 .setMIFlags(MachineInstr::FrameSetup);
1900
1901 for (Register Reg : Regs) {
1902 MIB.addReg(RegNo: Reg);
1903 }
1904}
1905
1906void ARMFrameLowering::emitFPStatusRestores(
1907 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1908 MutableArrayRef<CalleeSavedInfo> CSI, unsigned LdmOpc) const {
1909 MachineFunction &MF = *MBB.getParent();
1910 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1911
1912 auto RegPresent = [&CSI](MCRegister Reg) {
1913 return llvm::any_of(Range&: CSI, P: [Reg](const CalleeSavedInfo &C) {
1914 return C.getReg() == Reg;
1915 });
1916 };
1917
1918 // Do nothing if we don't need to restore any FP status registers.
1919 if (!RegPresent(ARM::FPSCR) && !RegPresent(ARM::FPEXC))
1920 return;
1921
1922 // Pop registers off of the stack.
1923 MachineInstrBuilder MIB =
1924 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: TII.get(Opcode: LdmOpc), DestReg: ARM::SP)
1925 .addReg(RegNo: ARM::SP)
1926 .add(MOs: predOps(Pred: ARMCC::AL))
1927 .setMIFlags(MachineInstr::FrameDestroy);
1928
1929 // If FPSCR was saved, it will be popped into R4.
1930 if (RegPresent(ARM::FPSCR)) {
1931 MIB.addReg(RegNo: ARM::R4, Flags: RegState::Define);
1932 }
1933
1934 // If FPEXC was saved, it will be popped into R5.
1935 if (RegPresent(ARM::FPEXC)) {
1936 MIB.addReg(RegNo: ARM::R5, Flags: RegState::Define);
1937 }
1938
1939 // Move the FPSCR value back into the register with the VMSR instruction.
1940 if (RegPresent(ARM::FPSCR)) {
1941 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::VMSR))
1942 .addReg(RegNo: ARM::R4)
1943 .add(MOs: predOps(Pred: ARMCC::AL))
1944 .setMIFlags(MachineInstr::FrameDestroy);
1945 }
1946
1947 // Move the FPEXC value back into the register with the VMSR_FPEXC
1948 // instruction.
1949 if (RegPresent(ARM::FPEXC)) {
1950 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::VMSR_FPEXC))
1951 .addReg(RegNo: ARM::R5)
1952 .add(MOs: predOps(Pred: ARMCC::AL))
1953 .setMIFlags(MachineInstr::FrameDestroy);
1954 }
1955}
1956
1957/// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1958/// starting from d8. Also insert stack realignment code and leave the stack
1959/// pointer pointing to the d8 spill slot.
1960static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1961 MachineBasicBlock::iterator MI,
1962 unsigned NumAlignedDPRCS2Regs,
1963 ArrayRef<CalleeSavedInfo> CSI,
1964 const TargetRegisterInfo *TRI) {
1965 MachineFunction &MF = *MBB.getParent();
1966 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1967 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1968 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1969 MachineFrameInfo &MFI = MF.getFrameInfo();
1970
1971 // Mark the D-register spill slots as properly aligned. Since MFI computes
1972 // stack slot layout backwards, this can actually mean that the d-reg stack
1973 // slot offsets can be wrong. The offset for d8 will always be correct.
1974 for (const CalleeSavedInfo &I : CSI) {
1975 unsigned DNum = I.getReg() - ARM::D8;
1976 if (DNum > NumAlignedDPRCS2Regs - 1)
1977 continue;
1978 int FI = I.getFrameIdx();
1979 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1980 // registers will be 8-byte aligned.
1981 MFI.setObjectAlignment(ObjectIdx: FI, Alignment: DNum % 2 ? Align(8) : Align(16));
1982
1983 // The stack slot for D8 needs to be maximally aligned because this is
1984 // actually the point where we align the stack pointer. MachineFrameInfo
1985 // computes all offsets relative to the incoming stack pointer which is a
1986 // bit weird when realigning the stack. Any extra padding for this
1987 // over-alignment is not realized because the code inserted below adjusts
1988 // the stack pointer by numregs * 8 before aligning the stack pointer.
1989 if (DNum == 0)
1990 MFI.setObjectAlignment(ObjectIdx: FI, Alignment: MFI.getMaxAlign());
1991 }
1992
1993 // Move the stack pointer to the d8 spill slot, and align it at the same
1994 // time. Leave the stack slot address in the scratch register r4.
1995 //
1996 // sub r4, sp, #numregs * 8
1997 // bic r4, r4, #align - 1
1998 // mov sp, r4
1999 //
2000 bool isThumb = AFI->isThumbFunction();
2001 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
2002 AFI->setShouldRestoreSPFromFP(true);
2003
2004 // sub r4, sp, #numregs * 8
2005 // The immediate is <= 64, so it doesn't need any special encoding.
2006 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
2007 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: ARM::R4)
2008 .addReg(RegNo: ARM::SP)
2009 .addImm(Val: 8 * NumAlignedDPRCS2Regs)
2010 .add(MOs: predOps(Pred: ARMCC::AL))
2011 .add(MO: condCodeOp());
2012
2013 Align MaxAlign = MF.getFrameInfo().getMaxAlign();
2014 // We must set parameter MustBeSingleInstruction to true, since
2015 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
2016 // stack alignment. Luckily, this can always be done since all ARM
2017 // architecture versions that support Neon also support the BFC
2018 // instruction.
2019 emitAligningInstructions(MF, AFI, TII, MBB, MBBI: MI, DL, Reg: ARM::R4, Alignment: MaxAlign, MustBeSingleInstruction: true);
2020
2021 // mov sp, r4
2022 // The stack pointer must be adjusted before spilling anything, otherwise
2023 // the stack slots could be clobbered by an interrupt handler.
2024 // Leave r4 live, it is used below.
2025 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
2026 MachineInstrBuilder MIB = BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: ARM::SP)
2027 .addReg(RegNo: ARM::R4)
2028 .add(MOs: predOps(Pred: ARMCC::AL));
2029 if (!isThumb)
2030 MIB.add(MO: condCodeOp());
2031
2032 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
2033 // r4 holds the stack slot address.
2034 unsigned NextReg = ARM::D8;
2035
2036 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
2037 // The writeback is only needed when emitting two vst1.64 instructions.
2038 if (NumAlignedDPRCS2Regs >= 6) {
2039 MCRegister SupReg =
2040 TRI->getMatchingSuperReg(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2041 MBB.addLiveIn(PhysReg: SupReg);
2042 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VST1d64Qwb_fixed), DestReg: ARM::R4)
2043 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
2044 .addImm(Val: 16)
2045 .addReg(RegNo: NextReg)
2046 .addReg(RegNo: SupReg, Flags: RegState::ImplicitKill)
2047 .add(MOs: predOps(Pred: ARMCC::AL));
2048 NextReg += 4;
2049 NumAlignedDPRCS2Regs -= 4;
2050 }
2051
2052 // We won't modify r4 beyond this point. It currently points to the next
2053 // register to be spilled.
2054 unsigned R4BaseReg = NextReg;
2055
2056 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
2057 if (NumAlignedDPRCS2Regs >= 4) {
2058 MCRegister SupReg =
2059 TRI->getMatchingSuperReg(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2060 MBB.addLiveIn(PhysReg: SupReg);
2061 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VST1d64Q))
2062 .addReg(RegNo: ARM::R4)
2063 .addImm(Val: 16)
2064 .addReg(RegNo: NextReg)
2065 .addReg(RegNo: SupReg, Flags: RegState::ImplicitKill)
2066 .add(MOs: predOps(Pred: ARMCC::AL));
2067 NextReg += 4;
2068 NumAlignedDPRCS2Regs -= 4;
2069 }
2070
2071 // 16-byte aligned vst1.64 with 2 d-regs.
2072 if (NumAlignedDPRCS2Regs >= 2) {
2073 MCRegister SupReg =
2074 TRI->getMatchingSuperReg(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QPRRegClass);
2075 MBB.addLiveIn(PhysReg: SupReg);
2076 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VST1q64))
2077 .addReg(RegNo: ARM::R4)
2078 .addImm(Val: 16)
2079 .addReg(RegNo: SupReg)
2080 .add(MOs: predOps(Pred: ARMCC::AL));
2081 NextReg += 2;
2082 NumAlignedDPRCS2Regs -= 2;
2083 }
2084
2085 // Finally, use a vanilla vstr.64 for the odd last register.
2086 if (NumAlignedDPRCS2Regs) {
2087 MBB.addLiveIn(PhysReg: NextReg);
2088 // vstr.64 uses addrmode5 which has an offset scale of 4.
2089 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VSTRD))
2090 .addReg(RegNo: NextReg)
2091 .addReg(RegNo: ARM::R4)
2092 .addImm(Val: (NextReg - R4BaseReg) * 2)
2093 .add(MOs: predOps(Pred: ARMCC::AL));
2094 }
2095
2096 // The last spill instruction inserted should kill the scratch register r4.
2097 std::prev(x: MI)->addRegisterKilled(IncomingReg: ARM::R4, RegInfo: TRI);
2098}
2099
2100/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
2101/// iterator to the following instruction.
2102static MachineBasicBlock::iterator
2103skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
2104 unsigned NumAlignedDPRCS2Regs) {
2105 // sub r4, sp, #numregs * 8
2106 // bic r4, r4, #align - 1
2107 // mov sp, r4
2108 ++MI; ++MI; ++MI;
2109 assert(MI->mayStore() && "Expecting spill instruction");
2110
2111 // These switches all fall through.
2112 switch(NumAlignedDPRCS2Regs) {
2113 case 7:
2114 ++MI;
2115 assert(MI->mayStore() && "Expecting spill instruction");
2116 [[fallthrough]];
2117 default:
2118 ++MI;
2119 assert(MI->mayStore() && "Expecting spill instruction");
2120 [[fallthrough]];
2121 case 1:
2122 case 2:
2123 case 4:
2124 assert(MI->killsRegister(ARM::R4, /*TRI=*/nullptr) && "Missed kill flag");
2125 ++MI;
2126 }
2127 return MI;
2128}
2129
2130/// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
2131/// starting from d8. These instructions are assumed to execute while the
2132/// stack is still aligned, unlike the code inserted by emitPopInst.
2133static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
2134 MachineBasicBlock::iterator MI,
2135 unsigned NumAlignedDPRCS2Regs,
2136 ArrayRef<CalleeSavedInfo> CSI,
2137 const TargetRegisterInfo *TRI) {
2138 MachineFunction &MF = *MBB.getParent();
2139 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2140 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
2141 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
2142
2143 // Find the frame index assigned to d8.
2144 int D8SpillFI = 0;
2145 for (const CalleeSavedInfo &I : CSI)
2146 if (I.getReg() == ARM::D8) {
2147 D8SpillFI = I.getFrameIdx();
2148 break;
2149 }
2150
2151 // Materialize the address of the d8 spill slot into the scratch register r4.
2152 // This can be fairly complicated if the stack frame is large, so just use
2153 // the normal frame index elimination mechanism to do it. This code runs as
2154 // the initial part of the epilog where the stack and base pointers haven't
2155 // been changed yet.
2156 bool isThumb = AFI->isThumbFunction();
2157 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
2158
2159 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
2160 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: ARM::R4)
2161 .addFrameIndex(Idx: D8SpillFI)
2162 .addImm(Val: 0)
2163 .add(MOs: predOps(Pred: ARMCC::AL))
2164 .add(MO: condCodeOp());
2165
2166 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
2167 unsigned NextReg = ARM::D8;
2168
2169 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
2170 if (NumAlignedDPRCS2Regs >= 6) {
2171 MCRegister SupReg =
2172 TRI->getMatchingSuperReg(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2173 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLD1d64Qwb_fixed), DestReg: NextReg)
2174 .addReg(RegNo: ARM::R4, Flags: RegState::Define)
2175 .addReg(RegNo: ARM::R4, Flags: RegState::Kill)
2176 .addImm(Val: 16)
2177 .addReg(RegNo: SupReg, Flags: RegState::ImplicitDefine)
2178 .add(MOs: predOps(Pred: ARMCC::AL));
2179 NextReg += 4;
2180 NumAlignedDPRCS2Regs -= 4;
2181 }
2182
2183 // We won't modify r4 beyond this point. It currently points to the next
2184 // register to be spilled.
2185 unsigned R4BaseReg = NextReg;
2186
2187 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
2188 if (NumAlignedDPRCS2Regs >= 4) {
2189 MCRegister SupReg =
2190 TRI->getMatchingSuperReg(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QQPRRegClass);
2191 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLD1d64Q), DestReg: NextReg)
2192 .addReg(RegNo: ARM::R4)
2193 .addImm(Val: 16)
2194 .addReg(RegNo: SupReg, Flags: RegState::ImplicitDefine)
2195 .add(MOs: predOps(Pred: ARMCC::AL));
2196 NextReg += 4;
2197 NumAlignedDPRCS2Regs -= 4;
2198 }
2199
2200 // 16-byte aligned vld1.64 with 2 d-regs.
2201 if (NumAlignedDPRCS2Regs >= 2) {
2202 MCRegister SupReg =
2203 TRI->getMatchingSuperReg(Reg: NextReg, SubIdx: ARM::dsub_0, RC: &ARM::QPRRegClass);
2204 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLD1q64), DestReg: SupReg)
2205 .addReg(RegNo: ARM::R4)
2206 .addImm(Val: 16)
2207 .add(MOs: predOps(Pred: ARMCC::AL));
2208 NextReg += 2;
2209 NumAlignedDPRCS2Regs -= 2;
2210 }
2211
2212 // Finally, use a vanilla vldr.64 for the remaining odd register.
2213 if (NumAlignedDPRCS2Regs)
2214 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: ARM::VLDRD), DestReg: NextReg)
2215 .addReg(RegNo: ARM::R4)
2216 .addImm(Val: 2 * (NextReg - R4BaseReg))
2217 .add(MOs: predOps(Pred: ARMCC::AL));
2218
2219 // Last store kills r4.
2220 std::prev(x: MI)->addRegisterKilled(IncomingReg: ARM::R4, RegInfo: TRI);
2221}
2222
2223bool ARMFrameLowering::spillCalleeSavedRegisters(
2224 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2225 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2226 if (CSI.empty())
2227 return false;
2228
2229 MachineFunction &MF = *MBB.getParent();
2230 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2231 ARMSubtarget::PushPopSplitVariation PushPopSplit =
2232 STI.getPushPopSplitVariation(MF);
2233 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
2234
2235 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
2236 unsigned PushOneOpc = AFI->isThumbFunction() ?
2237 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
2238 unsigned FltOpc = ARM::VSTMDDB_UPD;
2239 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
2240 // Compute PAC in R12.
2241 if (AFI->shouldSignReturnAddress()) {
2242 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::t2PAC))
2243 .setMIFlags(MachineInstr::FrameSetup);
2244 }
2245 // Save the non-secure floating point context.
2246 if (llvm::any_of(Range&: CSI, P: [](const CalleeSavedInfo &C) {
2247 return C.getReg() == ARM::FPCXTNS;
2248 })) {
2249 BuildMI(BB&: MBB, I: MI, MIMD: DebugLoc(), MCID: STI.getInstrInfo()->get(Opcode: ARM::VSTR_FPCXTNS_pre),
2250 DestReg: ARM::SP)
2251 .addReg(RegNo: ARM::SP)
2252 .addImm(Val: -4)
2253 .add(MOs: predOps(Pred: ARMCC::AL));
2254 }
2255
2256 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs,
2257 RegInfo](unsigned Reg, SpillArea TestArea) {
2258 return getSpillArea(Reg, Variation: PushPopSplit, NumAlignedDPRCS2Regs, RegInfo) ==
2259 TestArea;
2260 };
2261 auto IsGPRCS1 = [&CheckRegArea](unsigned Reg) {
2262 return CheckRegArea(Reg, SpillArea::GPRCS1);
2263 };
2264 auto IsGPRCS2 = [&CheckRegArea](unsigned Reg) {
2265 return CheckRegArea(Reg, SpillArea::GPRCS2);
2266 };
2267 auto IsDPRCS1 = [&CheckRegArea](unsigned Reg) {
2268 return CheckRegArea(Reg, SpillArea::DPRCS1);
2269 };
2270 auto IsGPRCS3 = [&CheckRegArea](unsigned Reg) {
2271 return CheckRegArea(Reg, SpillArea::GPRCS3);
2272 };
2273
2274 emitPushInst(MBB, MI, CSI, StmOpc: PushOpc, StrOpc: PushOneOpc, NoGap: false, Func: IsGPRCS1);
2275 emitPushInst(MBB, MI, CSI, StmOpc: PushOpc, StrOpc: PushOneOpc, NoGap: false, Func: IsGPRCS2);
2276 emitFPStatusSaves(MBB, MI, CSI, PushOpc);
2277 emitPushInst(MBB, MI, CSI, StmOpc: FltOpc, StrOpc: 0, NoGap: true, Func: IsDPRCS1);
2278 emitPushInst(MBB, MI, CSI, StmOpc: PushOpc, StrOpc: PushOneOpc, NoGap: false, Func: IsGPRCS3);
2279
2280 // The code above does not insert spill code for the aligned DPRCS2 registers.
2281 // The stack realignment code will be inserted between the push instructions
2282 // and these spills.
2283 if (NumAlignedDPRCS2Regs)
2284 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
2285
2286 return true;
2287}
2288
2289bool ARMFrameLowering::restoreCalleeSavedRegisters(
2290 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2291 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2292 if (CSI.empty())
2293 return false;
2294
2295 MachineFunction &MF = *MBB.getParent();
2296 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2297 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
2298
2299 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
2300 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
2301 ARMSubtarget::PushPopSplitVariation PushPopSplit =
2302 STI.getPushPopSplitVariation(MF);
2303
2304 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
2305 // registers. Do that here instead.
2306 if (NumAlignedDPRCS2Regs)
2307 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
2308
2309 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
2310 unsigned LdrOpc =
2311 AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
2312 unsigned FltOpc = ARM::VLDMDIA_UPD;
2313
2314 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs,
2315 RegInfo](unsigned Reg, SpillArea TestArea) {
2316 return getSpillArea(Reg, Variation: PushPopSplit, NumAlignedDPRCS2Regs, RegInfo) ==
2317 TestArea;
2318 };
2319 auto IsGPRCS1 = [&CheckRegArea](unsigned Reg) {
2320 return CheckRegArea(Reg, SpillArea::GPRCS1);
2321 };
2322 auto IsGPRCS2 = [&CheckRegArea](unsigned Reg) {
2323 return CheckRegArea(Reg, SpillArea::GPRCS2);
2324 };
2325 auto IsDPRCS1 = [&CheckRegArea](unsigned Reg) {
2326 return CheckRegArea(Reg, SpillArea::DPRCS1);
2327 };
2328 auto IsGPRCS3 = [&CheckRegArea](unsigned Reg) {
2329 return CheckRegArea(Reg, SpillArea::GPRCS3);
2330 };
2331
2332 emitPopInst(MBB, MI, CSI, LdmOpc: PopOpc, LdrOpc, isVarArg, NoGap: false, Func: IsGPRCS3);
2333 emitPopInst(MBB, MI, CSI, LdmOpc: FltOpc, LdrOpc: 0, isVarArg, NoGap: true, Func: IsDPRCS1);
2334 emitFPStatusRestores(MBB, MI, CSI, LdmOpc: PopOpc);
2335 emitPopInst(MBB, MI, CSI, LdmOpc: PopOpc, LdrOpc, isVarArg, NoGap: false, Func: IsGPRCS2);
2336 emitPopInst(MBB, MI, CSI, LdmOpc: PopOpc, LdrOpc, isVarArg, NoGap: false, Func: IsGPRCS1);
2337
2338 return true;
2339}
2340
2341// FIXME: Make generic?
2342static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
2343 const ARMBaseInstrInfo &TII,
2344 const ARMSubtarget &STI,
2345 const ARMBaseRegisterInfo *RegInfo,
2346 BitVector &SavedRegs,
2347 bool BigFrameOffsets) {
2348 unsigned FnSize = 0;
2349
2350 bool KCFI = MF.getFunction().getParent()->getModuleFlag(Key: "kcfi");
2351
2352 if (MF.shouldSplitStack()) {
2353 // Split stack prologue saves r4,r5; makes a copy of sp and loads
2354 // a literal; compares the two, and if sp < literal, pushes
2355 // further registers and calls __morestack.
2356 FnSize += 0x24;
2357 }
2358
2359 // Count the number of saved high registers, which take more effort
2360 // to push and pop in the prologue and epilogue.
2361 unsigned SavedHighRegs = 0;
2362 for (auto Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11, ARM::R12})
2363 if (SavedRegs.test(Idx: Reg))
2364 ++SavedHighRegs;
2365
2366 // Size of a particularly large Thumb1 stack setup prologue:
2367 // update sp for variadic functions (2 bytes)
2368 // + push registers (2 bytes for PUSH {low regs} + 4 bytes per high register
2369 // that needs to be copied into a low reg and then pushed)
2370 // + frame pointer (might use r11, requiring pushing it first, 6 bytes)
2371 // + stack update (up to 12 bytes if a constant load is needed and a branch
2372 // required later to skip the constant)
2373 // + stack realignment (8, if needed)
2374 // + make base pointer (2).
2375 unsigned PrologueSize = 2 + 4 * SavedHighRegs + 6 + 12 + 2;
2376 if (RegInfo->hasStackRealignment(MF))
2377 PrologueSize += 8;
2378 FnSize += PrologueSize;
2379
2380 // Size of a large epilogue:
2381 // restore sp from frame pointer (6 bytes if it's in r11)
2382 // + pop registers (2 bytes + 4 per high register, as above)
2383 // + pop r11 if it was saved to make frame pointer (4 bytes)
2384 // + pop return address into a low reg (2 bytes)
2385 // + update sp to undo variadic function setup (2 bytes)
2386 // + BX to where you popped the return address (2 bytes)
2387 unsigned EpilogueSize = 6 + 2 + 4 * SavedHighRegs + 4 + 2 + 2;
2388
2389 bool FirstBlock = true;
2390 for (auto &MBB : MF) {
2391 if (!FirstBlock) {
2392 // We might have to insert padding to align the start of this basic
2393 // block.
2394 unsigned Alignment = MBB.getMaxBytesForAlignment();
2395 FnSize += Alignment;
2396 }
2397
2398 unsigned SizeBeforeThisBB = FnSize;
2399
2400 bool seenBranch = false, seenConstantLoad = false;
2401 for (auto &MI : MBB) {
2402 unsigned InstSize;
2403 switch (MI.getOpcode()) {
2404 case ARM::tADDframe:
2405 if (BigFrameOffsets)
2406 // We might need two ADD instructions, or even a constant
2407 // load. In the latter case we must count the constant as
2408 // well as the load instruction and the addition, for 8
2409 // bytes total.
2410 InstSize = 8;
2411 else
2412 InstSize = 2;
2413 break;
2414 case ARM::tLDRspi:
2415 case ARM::tSTRspi:
2416 if (BigFrameOffsets)
2417 // In a really nasty case, accessing a stack slot might
2418 // require saving and restoring a scratch register (4 bytes)
2419 // to make space to load (2 bytes) a constant (4 bytes) to
2420 // add to SP or FP (2 bytes) and then do the load/store to
2421 // the resulting register (2 bytes).
2422 InstSize = 14;
2423 else
2424 InstSize = 2;
2425 break;
2426 case TargetOpcode::COPY:
2427 // In some situations, COPY has to go via a high register, to
2428 // avoid corrupting the PSR flags: Thumb moves between low and
2429 // high registers don't write the PSR, whereas low/low moves
2430 // do.
2431 InstSize = 4; // may have to go via a high reg
2432 break;
2433 case ARM::MEMCPY:
2434 InstSize = 4; // becomes one LDMIA_UPD + STMIA_UPD pair
2435 break;
2436
2437 case ARM::Int_eh_sjlj_dispatchsetup:
2438 // Worst case is 6 bytes, loading a constant from a literal pool.
2439 InstSize = 6;
2440 break;
2441
2442 case ARM::tLDRpci_pic:
2443 InstSize = 4; // ordinary LDRpci + add to pc
2444 break;
2445
2446 case ARM::ADJCALLSTACKDOWN:
2447 case ARM::ADJCALLSTACKUP:
2448 InstSize = 2;
2449 break;
2450
2451 case ARM::tBLXNS_CALL:
2452 // A call across a CMSE trust boundary involves a lot of work. We must
2453 // clear all the registers that might contain our own secrets, which
2454 // means pushing them first. So first push low registers, then move
2455 // four high regs into them and push those too.
2456 InstSize = 2 + 2 * 4 + 2;
2457 // Then we must clear the low bit of the target register, because
2458 // instead of indicating Arm/Thumb it indicates the CMSE security
2459 // status. That takes two instructions.
2460 InstSize += 4;
2461 // Now actually clear all the registers, via a MOV for each one. This
2462 // includes argument registers as well as saved regs, so it can be
2463 // r1-r12 inclusive.
2464 InstSize += 2 * 12;
2465 // Clear the PSR flags (a wide instruction even in Armv8-M Baseline).
2466 InstSize += 4;
2467 // Perform the BLXNS call itself.
2468 InstSize += 2;
2469 // Now pop all the saved registers, which takes the same amount of
2470 // effort as pushing them did.
2471 InstSize += 2 + 2 * 4 + 2;
2472 break;
2473
2474 case ARM::tBXNS_RET:
2475 // When returning across a CMSE boundary, we must potentially clear all
2476 // the registers that we haven't restored to the caller's value: r0-r3
2477 // and r12. We also clear the PSR flags, and finally return via BXNS.
2478 InstSize = 5 * 2 + 4 + 2;
2479 break;
2480
2481 case TargetOpcode::LOAD_STACK_GUARD:
2482 if (STI.genExecuteOnly())
2483 // In execute-only code generation, it costs seven 2-byte
2484 // instructions (MOV + 3 ADD + 3 LSL) to load an arbitrary
2485 // 32-bit constant, plus two 4-byte MSRs to save/restore the
2486 // flags those instructions clobber. Then we load from the
2487 // resulting address with one more 2-byte instruction.
2488 InstSize = 7 * 2 + 2 * 4 + 8;
2489 else
2490 // If we're not generating execute-only code, the constant
2491 // just costs an LDR and a literal, and then another LDR is
2492 // needed to load from that address.
2493 InstSize = 2 * 2 + 4;
2494 break;
2495
2496 default:
2497 InstSize = TII.getInstSizeInBytes(MI);
2498 break;
2499 }
2500
2501 FnSize += InstSize;
2502
2503 // If the instruction loads a constant, score the size of the
2504 // constant, in case it can't be shared with other basic blocks.
2505 for (MachineMemOperand *MO : MI.memoperands()) {
2506 const PseudoSourceValue *PSV =
2507 dyn_cast_if_present<const PseudoSourceValue *>(
2508 Val: MO->getPointerInfo().V);
2509 if (PSV && PSV->kind() == PseudoSourceValue::ConstantPool) {
2510 unsigned ConstSize = MO->getType().getSizeInBytes();
2511 FnSize += ConstSize;
2512 seenConstantLoad = true;
2513 }
2514 }
2515
2516 // If the instruction is a return or a tailcall, count the size
2517 // of an epilogue. (We do this for each return, in case the
2518 // epilogue must be duplicated.)
2519 if (MI.isReturn() || TII.isTailCall(Inst: MI)) {
2520 FnSize += EpilogueSize;
2521 }
2522
2523 // If the instruction is a call, and KCFI is enabled, then count the
2524 // cost of a KCFI_CHECK_Thumb1 pseudo.
2525 if (KCFI && MI.isCall() && MI.getCFIType()) {
2526 const MCInstrDesc &MCID = TII.get(Opcode: ARM::KCFI_CHECK_Thumb1);
2527 FnSize += MCID.getSize();
2528 }
2529
2530 if (MI.isUnconditionalBranch())
2531 seenBranch = true;
2532 }
2533
2534 // If there's no branch instruction in the block and we saw a constant,
2535 // count a branch + realignment to 4 bytes, in case we have to branch round
2536 // it.
2537 if (seenConstantLoad && !seenBranch) {
2538 FnSize += 4;
2539 }
2540
2541 // Also, if the block is really, really big, then count an extra 4 bytes
2542 // (again branch + realignment) for potentially splitting it in order to
2543 // put constants in the middle, avoiding the problem of an LDR not being
2544 // able to reach all the way to the end. The LDR offset limit is 1024
2545 // bytes; the splitting itself adds some cost, but since any function this
2546 // large is likely to have already gone over the "must stack LR" limit, we
2547 // can keep things simple by assuming we split at half that rate.
2548 unsigned BBSize = FnSize - SizeBeforeThisBB;
2549 FnSize += 4 * BBSize / 512;
2550 }
2551 if (MF.getJumpTableInfo()) {
2552 for (auto &Table : MF.getJumpTableInfo()->getJumpTables()) {
2553 unsigned TableLen = Table.MBBs.size();
2554 unsigned TableSizeBytes = TableLen * 4;
2555 FnSize += TableSizeBytes;
2556 }
2557 }
2558 LLVM_DEBUG(dbgs() << "Estimated function size for " << MF.getName() << " = "
2559 << FnSize << " bytes\n");
2560 return FnSize;
2561}
2562
2563/// estimateRSStackSizeLimit - Look at each instruction that references stack
2564/// frames and return the stack size limit beyond which some of these
2565/// instructions will require a scratch register during their expansion later.
2566// FIXME: Move to TII?
2567static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
2568 const TargetFrameLowering *TFI,
2569 bool &HasNonSPFrameIndex) {
2570 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2571 const ARMBaseInstrInfo &TII =
2572 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2573 unsigned Limit = (1 << 12) - 1;
2574 for (auto &MBB : MF) {
2575 for (auto &MI : MBB) {
2576 if (MI.isDebugInstr())
2577 continue;
2578 if (MI.getOpcode() == TargetOpcode::LOCAL_ESCAPE)
2579 continue;
2580 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2581 if (!MI.getOperand(i).isFI())
2582 continue;
2583
2584 // When using ADDri to get the address of a stack object, 255 is the
2585 // largest offset guaranteed to fit in the immediate offset.
2586 if (MI.getOpcode() == ARM::ADDri) {
2587 Limit = std::min(a: Limit, b: (1U << 8) - 1);
2588 break;
2589 }
2590 // t2ADDri will not require an extra register, it can reuse the
2591 // destination.
2592 if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
2593 break;
2594
2595 const MCInstrDesc &MCID = MI.getDesc();
2596 const TargetRegisterClass *RegClass = TII.getRegClass(MCID, OpNum: i);
2597 if (RegClass && !RegClass->contains(Reg: ARM::SP))
2598 HasNonSPFrameIndex = true;
2599
2600 // Otherwise check the addressing mode.
2601 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
2602 case ARMII::AddrMode_i12:
2603 case ARMII::AddrMode2:
2604 // Default 12 bit limit.
2605 break;
2606 case ARMII::AddrMode3:
2607 case ARMII::AddrModeT2_i8neg:
2608 Limit = std::min(a: Limit, b: (1U << 8) - 1);
2609 break;
2610 case ARMII::AddrMode5FP16:
2611 Limit = std::min(a: Limit, b: ((1U << 8) - 1) * 2);
2612 break;
2613 case ARMII::AddrMode5:
2614 case ARMII::AddrModeT2_i8s4:
2615 case ARMII::AddrModeT2_ldrex:
2616 Limit = std::min(a: Limit, b: ((1U << 8) - 1) * 4);
2617 break;
2618 case ARMII::AddrModeT2_i12:
2619 // i12 supports only positive offset so these will be converted to
2620 // i8 opcodes. See llvm::rewriteT2FrameIndex.
2621 if (TFI->hasFP(MF) && AFI->hasStackFrame())
2622 Limit = std::min(a: Limit, b: (1U << 8) - 1);
2623 break;
2624 case ARMII::AddrMode4:
2625 case ARMII::AddrMode6:
2626 // Addressing modes 4 & 6 (load/store) instructions can't encode an
2627 // immediate offset for stack references.
2628 return 0;
2629 case ARMII::AddrModeT2_i7:
2630 Limit = std::min(a: Limit, b: ((1U << 7) - 1) * 1);
2631 break;
2632 case ARMII::AddrModeT2_i7s2:
2633 Limit = std::min(a: Limit, b: ((1U << 7) - 1) * 2);
2634 break;
2635 case ARMII::AddrModeT2_i7s4:
2636 Limit = std::min(a: Limit, b: ((1U << 7) - 1) * 4);
2637 break;
2638 default:
2639 llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
2640 }
2641 break; // At most one FI per instruction
2642 }
2643 }
2644 }
2645
2646 return Limit;
2647}
2648
2649// In functions that realign the stack, it can be an advantage to spill the
2650// callee-saved vector registers after realigning the stack. The vst1 and vld1
2651// instructions take alignment hints that can improve performance.
2652static void
2653checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
2654 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
2655 if (!SpillAlignedNEONRegs)
2656 return;
2657
2658 // Naked functions don't spill callee-saved registers.
2659 if (MF.getFunction().hasFnAttribute(Kind: Attribute::Naked))
2660 return;
2661
2662 // We are planning to use NEON instructions vst1 / vld1.
2663 if (!MF.getSubtarget<ARMSubtarget>().hasNEON())
2664 return;
2665
2666 // Don't bother if the default stack alignment is sufficiently high.
2667 if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8))
2668 return;
2669
2670 // Aligned spills require stack realignment.
2671 if (!static_cast<const ARMBaseRegisterInfo *>(
2672 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
2673 return;
2674
2675 // We always spill contiguous d-registers starting from d8. Count how many
2676 // needs spilling. The register allocator will almost always use the
2677 // callee-saved registers in order, but it can happen that there are holes in
2678 // the range. Registers above the hole will be spilled to the standard DPRCS
2679 // area.
2680 unsigned NumSpills = 0;
2681 for (; NumSpills < 8; ++NumSpills)
2682 if (!SavedRegs.test(Idx: ARM::D8 + NumSpills))
2683 break;
2684
2685 // Don't do this for just one d-register. It's not worth it.
2686 if (NumSpills < 2)
2687 return;
2688
2689 // Spill the first NumSpills D-registers after realigning the stack.
2690 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
2691
2692 // A scratch register is required for the vst1 / vld1 instructions.
2693 SavedRegs.set(ARM::R4);
2694}
2695
2696bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
2697 // For CMSE entry functions, we want to save the FPCXT_NS immediately
2698 // upon function entry (resp. restore it immediately before return)
2699 if (STI.hasV8_1MMainlineOps() &&
2700 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction())
2701 return false;
2702
2703 // We are disabling shrinkwrapping for now when PAC is enabled, as
2704 // shrinkwrapping can cause clobbering of r12 when the PAC code is
2705 // generated. A follow-up patch will fix this in a more performant manner.
2706 if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress(
2707 SpillsLR: true /* SpillsLR */))
2708 return false;
2709
2710 return true;
2711}
2712
2713bool ARMFrameLowering::requiresAAPCSFrameRecord(
2714 const MachineFunction &MF) const {
2715 const auto &Subtarget = MF.getSubtarget<ARMSubtarget>();
2716 return Subtarget.createAAPCSFrameChain() && hasFP(MF);
2717}
2718
2719// Thumb1 may require a spill when storing to a frame index through FP (or any
2720// access with execute-only), for cases where FP is a high register (R11). This
2721// scans the function for cases where this may happen.
2722static bool canSpillOnFrameIndexAccess(const MachineFunction &MF,
2723 const TargetFrameLowering &TFI) {
2724 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2725 if (!AFI->isThumb1OnlyFunction())
2726 return false;
2727
2728 const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
2729 for (const auto &MBB : MF)
2730 for (const auto &MI : MBB)
2731 if (MI.getOpcode() == ARM::tSTRspi || MI.getOpcode() == ARM::tSTRi ||
2732 STI.genExecuteOnly())
2733 for (const auto &Op : MI.operands())
2734 if (Op.isFI()) {
2735 Register Reg;
2736 TFI.getFrameIndexReference(MF, FI: Op.getIndex(), FrameReg&: Reg);
2737 if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::SP)
2738 return true;
2739 }
2740 return false;
2741}
2742
2743void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
2744 BitVector &SavedRegs,
2745 RegScavenger *RS) const {
2746 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2747 // This tells PEI to spill the FP as if it is any other callee-save register
2748 // to take advantage the eliminateFrameIndex machinery. This also ensures it
2749 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
2750 // to combine multiple loads / stores.
2751 bool CanEliminateFrame = !(requiresAAPCSFrameRecord(MF) && hasFP(MF)) &&
2752 !MF.disableFramePointerElim();
2753 bool CS1Spilled = false;
2754 bool LRSpilled = false;
2755 unsigned NumGPRSpills = 0;
2756 unsigned NumFPRSpills = 0;
2757 SmallVector<unsigned, 4> UnspilledCS1GPRs;
2758 SmallVector<unsigned, 4> UnspilledCS2GPRs;
2759 const Function &F = MF.getFunction();
2760 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
2761 MF.getSubtarget().getRegisterInfo());
2762 const ARMBaseInstrInfo &TII =
2763 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2764 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2765 MachineFrameInfo &MFI = MF.getFrameInfo();
2766 MachineRegisterInfo &MRI = MF.getRegInfo();
2767 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2768 (void)TRI; // Silence unused warning in non-assert builds.
2769 Register FramePtr = STI.getFramePointerReg();
2770 ARMSubtarget::PushPopSplitVariation PushPopSplit =
2771 STI.getPushPopSplitVariation(MF);
2772
2773 // For a floating point interrupt, save these registers always, since LLVM
2774 // currently doesn't model reads/writes to these registers.
2775 if (F.hasFnAttribute(Kind: "interrupt") && F.hasFnAttribute(Kind: "save-fp")) {
2776 SavedRegs.set(ARM::FPSCR);
2777 SavedRegs.set(ARM::R4);
2778
2779 // This register will only be present on non-MClass registers.
2780 if (STI.isMClass()) {
2781 SavedRegs.reset(Idx: ARM::FPEXC);
2782 } else {
2783 SavedRegs.set(ARM::FPEXC);
2784 SavedRegs.set(ARM::R5);
2785 }
2786 }
2787
2788 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
2789 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
2790 // since it's not always possible to restore sp from fp in a single
2791 // instruction.
2792 // FIXME: It will be better just to find spare register here.
2793 if (AFI->isThumb2Function() &&
2794 (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)))
2795 SavedRegs.set(ARM::R4);
2796
2797 // If a stack probe will be emitted, spill R4 and LR, since they are
2798 // clobbered by the stack probe call.
2799 // This estimate should be a safe, conservative estimate. The actual
2800 // stack probe is enabled based on the size of the local objects;
2801 // this estimate also includes the varargs store size.
2802 if (STI.isTargetWindows() &&
2803 WindowsRequiresStackProbe(MF, StackSizeInBytes: MFI.estimateStackSize(MF))) {
2804 SavedRegs.set(ARM::R4);
2805 SavedRegs.set(ARM::LR);
2806 }
2807
2808 if (AFI->isThumb1OnlyFunction()) {
2809 // Spill LR if Thumb1 function uses variable length argument lists.
2810 if (AFI->getArgRegsSaveSize() > 0)
2811 SavedRegs.set(ARM::LR);
2812
2813 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
2814 // requires stack alignment. We don't know for sure what the stack size
2815 // will be, but for this, an estimate is good enough. If there anything
2816 // changes it, it'll be a spill, which implies we've used all the registers
2817 // and so R4 is already used, so not marking it here will be OK.
2818 // FIXME: It will be better just to find spare register here.
2819 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) ||
2820 MFI.estimateStackSize(MF) > 508)
2821 SavedRegs.set(ARM::R4);
2822 }
2823
2824 // See if we can spill vector registers to aligned stack.
2825 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
2826
2827 // Spill the BasePtr if it's used.
2828 if (RegInfo->hasBasePointer(MF))
2829 SavedRegs.set(RegInfo->getBaseRegister());
2830
2831 // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
2832 if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
2833 CanEliminateFrame = false;
2834
2835 // When return address signing is enabled R12 is treated as callee-saved.
2836 if (AFI->shouldSignReturnAddress())
2837 CanEliminateFrame = false;
2838
2839 // Don't spill FP if the frame can be eliminated. This is determined
2840 // by scanning the callee-save registers to see if any is modified.
2841 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MF: &MF);
2842 for (unsigned i = 0; CSRegs[i]; ++i) {
2843 unsigned Reg = CSRegs[i];
2844 bool Spilled = false;
2845 if (SavedRegs.test(Idx: Reg)) {
2846 Spilled = true;
2847 CanEliminateFrame = false;
2848 }
2849
2850 if (!ARM::GPRRegClass.contains(Reg)) {
2851 if (Spilled) {
2852 if (ARM::SPRRegClass.contains(Reg))
2853 NumFPRSpills++;
2854 else if (ARM::DPRRegClass.contains(Reg))
2855 NumFPRSpills += 2;
2856 else if (ARM::QPRRegClass.contains(Reg))
2857 NumFPRSpills += 4;
2858 }
2859 continue;
2860 }
2861
2862 if (Spilled) {
2863 NumGPRSpills++;
2864
2865 if (PushPopSplit != ARMSubtarget::SplitR7) {
2866 if (Reg == ARM::LR)
2867 LRSpilled = true;
2868 CS1Spilled = true;
2869 continue;
2870 }
2871
2872 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
2873 switch (Reg) {
2874 case ARM::LR:
2875 LRSpilled = true;
2876 [[fallthrough]];
2877 case ARM::R0: case ARM::R1:
2878 case ARM::R2: case ARM::R3:
2879 case ARM::R4: case ARM::R5:
2880 case ARM::R6: case ARM::R7:
2881 CS1Spilled = true;
2882 break;
2883 default:
2884 break;
2885 }
2886 } else {
2887 if (PushPopSplit != ARMSubtarget::SplitR7) {
2888 UnspilledCS1GPRs.push_back(Elt: Reg);
2889 continue;
2890 }
2891
2892 switch (Reg) {
2893 case ARM::R0: case ARM::R1:
2894 case ARM::R2: case ARM::R3:
2895 case ARM::R4: case ARM::R5:
2896 case ARM::R6: case ARM::R7:
2897 case ARM::LR:
2898 UnspilledCS1GPRs.push_back(Elt: Reg);
2899 break;
2900 default:
2901 UnspilledCS2GPRs.push_back(Elt: Reg);
2902 break;
2903 }
2904 }
2905 }
2906
2907 bool ForceLRSpill = false;
2908
2909 // If any of the stack slot references may be out of range of an immediate
2910 // offset, make sure a register (or a spill slot) is available for the
2911 // register scavenger. Note that if we're indexing off the frame pointer, the
2912 // effective stack size is 4 bytes larger since the FP points to the stack
2913 // slot of the previous FP. Also, if we have variable sized objects in the
2914 // function, stack slot references will often be negative, and some of
2915 // our instructions are positive-offset only, so conservatively consider
2916 // that case to want a spill slot (or register) as well. Similarly, if
2917 // the function adjusts the stack pointer during execution and the
2918 // adjustments aren't already part of our stack size estimate, our offset
2919 // calculations may be off, so be conservative.
2920 // FIXME: We could add logic to be more precise about negative offsets
2921 // and which instructions will need a scratch register for them. Is it
2922 // worth the effort and added fragility?
2923 unsigned EstimatedStackSize =
2924 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
2925
2926 // Determine biggest (positive) SP offset in MachineFrameInfo.
2927 int MaxFixedOffset = 0;
2928 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
2929 int MaxObjectOffset = MFI.getObjectOffset(ObjectIdx: I) + MFI.getObjectSize(ObjectIdx: I);
2930 MaxFixedOffset = std::max(a: MaxFixedOffset, b: MaxObjectOffset);
2931 }
2932
2933 bool HasFP = hasFP(MF);
2934 if (HasFP) {
2935 if (AFI->hasStackFrame())
2936 EstimatedStackSize += 4;
2937 } else {
2938 // If FP is not used, SP will be used to access arguments, so count the
2939 // size of arguments into the estimation.
2940 EstimatedStackSize += MaxFixedOffset;
2941 }
2942 EstimatedStackSize += 16; // For possible paddings.
2943
2944 unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
2945 bool HasNonSPFrameIndex = false;
2946 if (AFI->isThumb1OnlyFunction()) {
2947 // For Thumb1, don't bother to iterate over the function. The only
2948 // instruction that requires an emergency spill slot is a store to a
2949 // frame index.
2950 //
2951 // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
2952 // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
2953 // a 5-bit unsigned immediate.
2954 //
2955 // We could try to check if the function actually contains a tSTRspi
2956 // that might need the spill slot, but it's not really important.
2957 // Functions with VLAs or extremely large call frames are rare, and
2958 // if a function is allocating more than 1KB of stack, an extra 4-byte
2959 // slot probably isn't relevant.
2960 //
2961 // A special case is the scenario where r11 is used as FP, where accesses
2962 // to a frame index will require its value to be moved into a low reg.
2963 // This is handled later on, once we are able to determine if we have any
2964 // fp-relative accesses.
2965 if (RegInfo->hasBasePointer(MF))
2966 EstimatedRSStackSizeLimit = (1U << 5) * 4;
2967 else
2968 EstimatedRSStackSizeLimit = (1U << 8) * 4;
2969 EstimatedRSFixedSizeLimit = (1U << 5) * 4;
2970 } else {
2971 EstimatedRSStackSizeLimit =
2972 estimateRSStackSizeLimit(MF, TFI: this, HasNonSPFrameIndex);
2973 EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
2974 }
2975 // Final estimate of whether sp or bp-relative accesses might require
2976 // scavenging.
2977 bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
2978
2979 // If the stack pointer moves and we don't have a base pointer, the
2980 // estimate logic doesn't work. The actual offsets might be larger when
2981 // we're constructing a call frame, or we might need to use negative
2982 // offsets from fp.
2983 bool HasMovingSP = MFI.hasVarSizedObjects() ||
2984 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
2985 bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
2986
2987 // If we have a frame pointer, we assume arguments will be accessed
2988 // relative to the frame pointer. Check whether fp-relative accesses to
2989 // arguments require scavenging.
2990 //
2991 // We could do slightly better on Thumb1; in some cases, an sp-relative
2992 // offset would be legal even though an fp-relative offset is not.
2993 int MaxFPOffset = getMaxFPOffset(STI, AFI: *AFI, MF);
2994 bool HasLargeArgumentList =
2995 HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
2996
2997 bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
2998 HasLargeArgumentList || HasNonSPFrameIndex;
2999 LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
3000 << "; EstimatedStack: " << EstimatedStackSize
3001 << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
3002 << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
3003
3004 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
3005 unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII, STI, RegInfo,
3006 SavedRegs, BigFrameOffsets);
3007
3008 if (FnSize >= (1 << 11)) {
3009 // Force LR to be spilled if the Thumb function size is > 2048. This
3010 // enables use of BL to implement far jump.
3011 CanEliminateFrame = false;
3012 ForceLRSpill = true;
3013 }
3014 }
3015
3016 if (BigFrameOffsets ||
3017 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
3018 AFI->setHasStackFrame(true);
3019
3020 // Save the FP if:
3021 // 1. We currently need it (HasFP), OR
3022 // 2. We might need it later due to stack realignment from aligned DPRCS2
3023 // saves (which will make hasFP() become true in emitPrologue).
3024 if (HasFP || (isFPReserved(MF) && AFI->getNumAlignedDPRCS2Regs() > 0)) {
3025 SavedRegs.set(FramePtr);
3026 // If the frame pointer is required by the ABI, also spill LR so that we
3027 // emit a complete frame record.
3028 if ((requiresAAPCSFrameRecord(MF) || MF.disableFramePointerElim()) &&
3029 !LRSpilled) {
3030 SavedRegs.set(ARM::LR);
3031 LRSpilled = true;
3032 NumGPRSpills++;
3033 auto LRPos = llvm::find(Range&: UnspilledCS1GPRs, Val: ARM::LR);
3034 if (LRPos != UnspilledCS1GPRs.end())
3035 UnspilledCS1GPRs.erase(CI: LRPos);
3036 }
3037 auto FPPos = llvm::find(Range&: UnspilledCS1GPRs, Val: FramePtr);
3038 if (FPPos != UnspilledCS1GPRs.end())
3039 UnspilledCS1GPRs.erase(CI: FPPos);
3040 NumGPRSpills++;
3041 if (FramePtr == ARM::R7)
3042 CS1Spilled = true;
3043 }
3044
3045 // This is the number of extra spills inserted for callee-save GPRs which
3046 // would not otherwise be used by the function. When greater than zero it
3047 // guaranteees that it is possible to scavenge a register to hold the
3048 // address of a stack slot. On Thumb1, the register must be a valid operand
3049 // to tSTRi, i.e. r4-r7. For other subtargets, this is any GPR, i.e. r4-r11
3050 // or lr.
3051 //
3052 // If we don't insert a spill, we instead allocate an emergency spill
3053 // slot, which can be used by scavenging to spill an arbitrary register.
3054 //
3055 // We currently don't try to figure out whether any specific instruction
3056 // requires scavening an additional register.
3057 unsigned NumExtraCSSpill = 0;
3058
3059 if (AFI->isThumb1OnlyFunction()) {
3060 // For Thumb1-only targets, we need some low registers when we save and
3061 // restore the high registers (which aren't allocatable, but could be
3062 // used by inline assembly) because the push/pop instructions can not
3063 // access high registers. If necessary, we might need to push more low
3064 // registers to ensure that there is at least one free that can be used
3065 // for the saving & restoring, and preferably we should ensure that as
3066 // many as are needed are available so that fewer push/pop instructions
3067 // are required.
3068
3069 // Low registers which are not currently pushed, but could be (r4-r7).
3070 SmallVector<unsigned, 4> AvailableRegs;
3071
3072 // Unused argument registers (r0-r3) can be clobbered in the prologue for
3073 // free.
3074 int EntryRegDeficit = 0;
3075 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
3076 if (!MF.getRegInfo().isLiveIn(Reg)) {
3077 --EntryRegDeficit;
3078 LLVM_DEBUG(dbgs()
3079 << printReg(Reg, TRI)
3080 << " is unused argument register, EntryRegDeficit = "
3081 << EntryRegDeficit << "\n");
3082 }
3083 }
3084
3085 // Unused return registers can be clobbered in the epilogue for free.
3086 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
3087 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
3088 << " return regs used, ExitRegDeficit = "
3089 << ExitRegDeficit << "\n");
3090
3091 int RegDeficit = std::max(a: EntryRegDeficit, b: ExitRegDeficit);
3092 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
3093
3094 // r4-r6 can be used in the prologue if they are pushed by the first push
3095 // instruction.
3096 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
3097 if (SavedRegs.test(Idx: Reg)) {
3098 --RegDeficit;
3099 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
3100 << " is saved low register, RegDeficit = "
3101 << RegDeficit << "\n");
3102 } else {
3103 AvailableRegs.push_back(Elt: Reg);
3104 LLVM_DEBUG(
3105 dbgs()
3106 << printReg(Reg, TRI)
3107 << " is non-saved low register, adding to AvailableRegs\n");
3108 }
3109 }
3110
3111 // r7 can be used if it is not being used as the frame pointer.
3112 if (!HasFP || FramePtr != ARM::R7) {
3113 if (SavedRegs.test(Idx: ARM::R7)) {
3114 --RegDeficit;
3115 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
3116 << RegDeficit << "\n");
3117 } else {
3118 AvailableRegs.push_back(Elt: ARM::R7);
3119 LLVM_DEBUG(
3120 dbgs()
3121 << "%r7 is non-saved low register, adding to AvailableRegs\n");
3122 }
3123 }
3124
3125 // Each of r8-r11 needs to be copied to a low register, then pushed.
3126 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
3127 if (SavedRegs.test(Idx: Reg)) {
3128 ++RegDeficit;
3129 LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
3130 << " is saved high register, RegDeficit = "
3131 << RegDeficit << "\n");
3132 }
3133 }
3134
3135 // LR can only be used by PUSH, not POP, and can't be used at all if the
3136 // llvm.returnaddress intrinsic is used. This is only worth doing if we
3137 // are more limited at function entry than exit.
3138 if ((EntryRegDeficit > ExitRegDeficit) &&
3139 !(MF.getRegInfo().isLiveIn(Reg: ARM::LR) &&
3140 MF.getFrameInfo().isReturnAddressTaken())) {
3141 if (SavedRegs.test(Idx: ARM::LR)) {
3142 --RegDeficit;
3143 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
3144 << RegDeficit << "\n");
3145 } else {
3146 AvailableRegs.push_back(Elt: ARM::LR);
3147 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
3148 }
3149 }
3150
3151 // If there are more high registers that need pushing than low registers
3152 // available, push some more low registers so that we can use fewer push
3153 // instructions. This might not reduce RegDeficit all the way to zero,
3154 // because we can only guarantee that r4-r6 are available, but r8-r11 may
3155 // need saving.
3156 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
3157 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
3158 unsigned Reg = AvailableRegs.pop_back_val();
3159 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3160 << " to make up reg deficit\n");
3161 SavedRegs.set(Reg);
3162 NumGPRSpills++;
3163 CS1Spilled = true;
3164 assert(!MRI.isReserved(Reg) && "Should not be reserved");
3165 if (Reg != ARM::LR && !MRI.isPhysRegUsed(PhysReg: Reg))
3166 NumExtraCSSpill++;
3167 UnspilledCS1GPRs.erase(CI: llvm::find(Range&: UnspilledCS1GPRs, Val: Reg));
3168 if (Reg == ARM::LR)
3169 LRSpilled = true;
3170 }
3171 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
3172 << "\n");
3173 }
3174
3175 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
3176 // restore LR in that case.
3177 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
3178
3179 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
3180 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
3181 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
3182 SavedRegs.set(ARM::LR);
3183 NumGPRSpills++;
3184 SmallVectorImpl<unsigned>::iterator LRPos;
3185 LRPos = llvm::find(Range&: UnspilledCS1GPRs, Val: (unsigned)ARM::LR);
3186 if (LRPos != UnspilledCS1GPRs.end())
3187 UnspilledCS1GPRs.erase(CI: LRPos);
3188
3189 ForceLRSpill = false;
3190 if (!MRI.isReserved(PhysReg: ARM::LR) && !MRI.isPhysRegUsed(PhysReg: ARM::LR) &&
3191 !AFI->isThumb1OnlyFunction())
3192 NumExtraCSSpill++;
3193 }
3194
3195 // If stack and double are 8-byte aligned and we are spilling an odd number
3196 // of GPRs, spill one extra callee save GPR so we won't have to pad between
3197 // the integer and double callee save areas.
3198 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
3199 const Align TargetAlign = getStackAlign();
3200 if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
3201 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
3202 for (unsigned Reg : UnspilledCS1GPRs) {
3203 // Don't spill high register if the function is thumb. In the case of
3204 // Windows on ARM, accept R11 (frame pointer)
3205 if (!AFI->isThumbFunction() ||
3206 (STI.isTargetWindows() && Reg == ARM::R11) ||
3207 isARMLowRegister(Reg) ||
3208 (Reg == ARM::LR && !ExpensiveLRRestore)) {
3209 SavedRegs.set(Reg);
3210 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3211 << " to make up alignment\n");
3212 if (!MRI.isReserved(PhysReg: Reg) && !MRI.isPhysRegUsed(PhysReg: Reg) &&
3213 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
3214 NumExtraCSSpill++;
3215 break;
3216 }
3217 }
3218 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
3219 unsigned Reg = UnspilledCS2GPRs.front();
3220 SavedRegs.set(Reg);
3221 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
3222 << " to make up alignment\n");
3223 if (!MRI.isReserved(PhysReg: Reg) && !MRI.isPhysRegUsed(PhysReg: Reg))
3224 NumExtraCSSpill++;
3225 }
3226 }
3227
3228 // Estimate if we might need to scavenge registers at some point in order
3229 // to materialize a stack offset. If so, either spill one additional
3230 // callee-saved register or reserve a special spill slot to facilitate
3231 // register scavenging. Thumb1 needs a spill slot for stack pointer
3232 // adjustments and for frame index accesses when FP is high register,
3233 // even when the frame itself is small.
3234 unsigned RegsNeeded = 0;
3235 if (BigFrameOffsets || canSpillOnFrameIndexAccess(MF, TFI: *this)) {
3236 RegsNeeded++;
3237 // With thumb1 execute-only we may need an additional register for saving
3238 // and restoring the CPSR.
3239 if (AFI->isThumb1OnlyFunction() && STI.genExecuteOnly() && !STI.useMovt())
3240 RegsNeeded++;
3241 }
3242
3243 if (RegsNeeded > NumExtraCSSpill) {
3244 // If any non-reserved CS register isn't spilled, just spill one or two
3245 // extra. That should take care of it!
3246 unsigned NumExtras = TargetAlign.value() / 4;
3247 SmallVector<unsigned, 2> Extras;
3248 while (NumExtras && !UnspilledCS1GPRs.empty()) {
3249 unsigned Reg = UnspilledCS1GPRs.pop_back_val();
3250 if (!MRI.isReserved(PhysReg: Reg) &&
3251 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
3252 Extras.push_back(Elt: Reg);
3253 NumExtras--;
3254 }
3255 }
3256 // For non-Thumb1 functions, also check for hi-reg CS registers
3257 if (!AFI->isThumb1OnlyFunction()) {
3258 while (NumExtras && !UnspilledCS2GPRs.empty()) {
3259 unsigned Reg = UnspilledCS2GPRs.pop_back_val();
3260 if (!MRI.isReserved(PhysReg: Reg)) {
3261 Extras.push_back(Elt: Reg);
3262 NumExtras--;
3263 }
3264 }
3265 }
3266 if (NumExtras == 0) {
3267 for (unsigned Reg : Extras) {
3268 SavedRegs.set(Reg);
3269 if (!MRI.isPhysRegUsed(PhysReg: Reg))
3270 NumExtraCSSpill++;
3271 }
3272 }
3273 while ((RegsNeeded > NumExtraCSSpill) && RS) {
3274 // Reserve a slot closest to SP or frame pointer.
3275 LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
3276 const TargetRegisterClass &RC = ARM::GPRRegClass;
3277 unsigned Size = TRI->getSpillSize(RC);
3278 Align Alignment = TRI->getSpillAlign(RC);
3279 RS->addScavengingFrameIndex(
3280 FI: MFI.CreateSpillStackObject(Size, Alignment));
3281 --RegsNeeded;
3282 }
3283 }
3284 }
3285
3286 if (ForceLRSpill)
3287 SavedRegs.set(ARM::LR);
3288 AFI->setLRIsSpilled(SavedRegs.test(Idx: ARM::LR));
3289}
3290
3291void ARMFrameLowering::updateLRRestored(MachineFunction &MF) {
3292 MachineFrameInfo &MFI = MF.getFrameInfo();
3293 if (!MFI.isCalleeSavedInfoValid())
3294 return;
3295
3296 // Check if all terminators do not implicitly use LR. Then we can 'restore' LR
3297 // into PC so it is not live out of the return block: Clear the Restored bit
3298 // in that case.
3299 for (CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) {
3300 if (Info.getReg() != ARM::LR)
3301 continue;
3302 if (all_of(Range&: MF, P: [](const MachineBasicBlock &MBB) {
3303 return all_of(Range: MBB.terminators(), P: [](const MachineInstr &Term) {
3304 return !Term.isReturn() || Term.getOpcode() == ARM::LDMIA_RET ||
3305 Term.getOpcode() == ARM::t2LDMIA_RET ||
3306 Term.getOpcode() == ARM::tPOP_RET;
3307 });
3308 })) {
3309 Info.setRestored(false);
3310 break;
3311 }
3312 }
3313}
3314
3315void ARMFrameLowering::processFunctionBeforeFrameFinalized(
3316 MachineFunction &MF, RegScavenger *RS) const {
3317 TargetFrameLowering::processFunctionBeforeFrameFinalized(MF, RS);
3318 updateLRRestored(MF);
3319}
3320
3321void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
3322 BitVector &SavedRegs) const {
3323 TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
3324
3325 // If we have the "returned" parameter attribute which guarantees that we
3326 // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
3327 // record that fact for IPRA.
3328 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3329 if (AFI->getPreservesR0())
3330 SavedRegs.set(ARM::R0);
3331}
3332
3333bool ARMFrameLowering::assignCalleeSavedSpillSlots(
3334 MachineFunction &MF, const TargetRegisterInfo *TRI,
3335 std::vector<CalleeSavedInfo> &CSI) const {
3336 // For CMSE entry functions, handle floating-point context as if it was a
3337 // callee-saved register.
3338 if (STI.hasV8_1MMainlineOps() &&
3339 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) {
3340 CSI.emplace_back(args: ARM::FPCXTNS);
3341 CSI.back().setRestored(false);
3342 }
3343
3344 // For functions, which sign their return address, upon function entry, the
3345 // return address PAC is computed in R12. Treat R12 as a callee-saved register
3346 // in this case.
3347 const auto &AFI = *MF.getInfo<ARMFunctionInfo>();
3348 if (AFI.shouldSignReturnAddress()) {
3349 // The order of register must match the order we push them, because the
3350 // PEI assigns frame indices in that order. That order depends on the
3351 // PushPopSplitVariation, there are only two cases which we use with return
3352 // address signing:
3353 switch (STI.getPushPopSplitVariation(MF)) {
3354 case ARMSubtarget::SplitR7:
3355 // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8
3356 CSI.insert(position: find_if(Range&: CSI,
3357 P: [=](const auto &CS) {
3358 MCRegister Reg = CS.getReg();
3359 return Reg == ARM::R10 || Reg == ARM::R11 ||
3360 Reg == ARM::R8 || Reg == ARM::R9 ||
3361 ARM::DPRRegClass.contains(Reg);
3362 }),
3363 x: CalleeSavedInfo(ARM::R12));
3364 break;
3365 case ARMSubtarget::SplitR11AAPCSSignRA:
3366 // With SplitR11AAPCSSignRA, R12 will always be the highest-addressed CSR
3367 // on the stack.
3368 CSI.insert(position: CSI.begin(), x: CalleeSavedInfo(ARM::R12));
3369 break;
3370 case ARMSubtarget::NoSplit:
3371 assert(!MF.disableFramePointerElim() &&
3372 "ABI-required frame pointers need a CSR split when signing return "
3373 "address.");
3374 CSI.insert(position: find_if(Range&: CSI,
3375 P: [=](const auto &CS) {
3376 MCRegister Reg = CS.getReg();
3377 return Reg != ARM::LR;
3378 }),
3379 x: CalleeSavedInfo(ARM::R12));
3380 break;
3381 default:
3382 llvm_unreachable("Unexpected CSR split with return address signing");
3383 }
3384 }
3385
3386 return false;
3387}
3388
3389const TargetFrameLowering::SpillSlot *
3390ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
3391 static const SpillSlot FixedSpillOffsets[] = {{.Reg: ARM::FPCXTNS, .Offset: -4}};
3392 NumEntries = std::size(FixedSpillOffsets);
3393 return FixedSpillOffsets;
3394}
3395
3396MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
3397 MachineFunction &MF, MachineBasicBlock &MBB,
3398 MachineBasicBlock::iterator I) const {
3399 const ARMBaseInstrInfo &TII =
3400 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
3401 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3402 bool isARM = !AFI->isThumbFunction();
3403 DebugLoc dl = I->getDebugLoc();
3404 unsigned Opc = I->getOpcode();
3405 bool IsDestroy = Opc == TII.getCallFrameDestroyOpcode();
3406 unsigned CalleePopAmount = IsDestroy ? I->getOperand(i: 1).getImm() : 0;
3407
3408 assert(!AFI->isThumb1OnlyFunction() &&
3409 "This eliminateCallFramePseudoInstr does not support Thumb1!");
3410
3411 int PIdx = I->findFirstPredOperandIdx();
3412 ARMCC::CondCodes Pred = (PIdx == -1)
3413 ? ARMCC::AL
3414 : (ARMCC::CondCodes)I->getOperand(i: PIdx).getImm();
3415 unsigned PredReg = TII.getFramePred(MI: *I);
3416
3417 if (!hasReservedCallFrame(MF)) {
3418 // Bail early if the callee is expected to do the adjustment.
3419 if (IsDestroy && CalleePopAmount != -1U)
3420 return MBB.erase(I);
3421
3422 // If we have alloca, convert as follows:
3423 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
3424 // ADJCALLSTACKUP -> add, sp, sp, amount
3425 unsigned Amount = TII.getFrameSize(I: *I);
3426 if (Amount != 0) {
3427 // We need to keep the stack aligned properly. To do this, we round the
3428 // amount of space needed for the outgoing arguments up to the next
3429 // alignment boundary.
3430 Amount = alignSPAdjust(SPAdj: Amount);
3431
3432 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
3433 emitSPUpdate(isARM, MBB, MBBI&: I, dl, TII, NumBytes: -Amount, MIFlags: MachineInstr::NoFlags,
3434 Pred, PredReg);
3435 } else {
3436 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
3437 emitSPUpdate(isARM, MBB, MBBI&: I, dl, TII, NumBytes: Amount, MIFlags: MachineInstr::NoFlags,
3438 Pred, PredReg);
3439 }
3440 }
3441 } else if (CalleePopAmount != -1U) {
3442 // If the calling convention demands that the callee pops arguments from the
3443 // stack, we want to add it back if we have a reserved call frame.
3444 emitSPUpdate(isARM, MBB, MBBI&: I, dl, TII, NumBytes: -CalleePopAmount,
3445 MIFlags: MachineInstr::NoFlags, Pred, PredReg);
3446 }
3447 return MBB.erase(I);
3448}
3449
3450/// Get the minimum constant for ARM that is greater than or equal to the
3451/// argument. In ARM, constants can have any value that can be produced by
3452/// rotating an 8-bit value to the right by an even number of bits within a
3453/// 32-bit word.
3454static uint32_t alignToARMConstant(uint32_t Value) {
3455 unsigned Shifted = 0;
3456
3457 if (Value == 0)
3458 return 0;
3459
3460 while (!(Value & 0xC0000000)) {
3461 Value = Value << 2;
3462 Shifted += 2;
3463 }
3464
3465 bool Carry = (Value & 0x00FFFFFF);
3466 Value = ((Value & 0xFF000000) >> 24) + Carry;
3467
3468 if (Value & 0x0000100)
3469 Value = Value & 0x000001FC;
3470
3471 if (Shifted > 24)
3472 Value = Value >> (Shifted - 24);
3473 else
3474 Value = Value << (24 - Shifted);
3475
3476 return Value;
3477}
3478
3479// The stack limit in the TCB is set to this many bytes above the actual
3480// stack limit.
3481static const uint64_t kSplitStackAvailable = 256;
3482
3483// Adjust the function prologue to enable split stacks. This currently only
3484// supports android and linux.
3485//
3486// The ABI of the segmented stack prologue is a little arbitrarily chosen, but
3487// must be well defined in order to allow for consistent implementations of the
3488// __morestack helper function. The ABI is also not a normal ABI in that it
3489// doesn't follow the normal calling conventions because this allows the
3490// prologue of each function to be optimized further.
3491//
3492// Currently, the ABI looks like (when calling __morestack)
3493//
3494// * r4 holds the minimum stack size requested for this function call
3495// * r5 holds the stack size of the arguments to the function
3496// * the beginning of the function is 3 instructions after the call to
3497// __morestack
3498//
3499// Implementations of __morestack should use r4 to allocate a new stack, r5 to
3500// place the arguments on to the new stack, and the 3-instruction knowledge to
3501// jump directly to the body of the function when working on the new stack.
3502//
3503// An old (and possibly no longer compatible) implementation of __morestack for
3504// ARM can be found at [1].
3505//
3506// [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
3507void ARMFrameLowering::adjustForSegmentedStacks(
3508 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3509 unsigned Opcode;
3510 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
3511 bool Thumb = ST->isThumb();
3512 bool Thumb2 = ST->isThumb2();
3513
3514 // Sadly, this currently doesn't support varargs, platforms other than
3515 // android/linux. Note that thumb1/thumb2 are support for android/linux.
3516 if (MF.getFunction().isVarArg())
3517 report_fatal_error(reason: "Segmented stacks do not support vararg functions.");
3518 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
3519 report_fatal_error(reason: "Segmented stacks not supported on this platform.");
3520
3521 MachineFrameInfo &MFI = MF.getFrameInfo();
3522 const ARMBaseInstrInfo &TII =
3523 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
3524 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
3525 DebugLoc DL;
3526
3527 if (!MFI.needsSplitStackProlog())
3528 return;
3529
3530 uint64_t StackSize = MFI.getStackSize();
3531
3532 // Use R4 and R5 as scratch registers.
3533 // We save R4 and R5 before use and restore them before leaving the function.
3534 unsigned ScratchReg0 = ARM::R4;
3535 unsigned ScratchReg1 = ARM::R5;
3536 unsigned MovOp = ST->useMovt() ? ARM::t2MOVi32imm : ARM::tMOVi32imm;
3537 uint64_t AlignedStackSize;
3538
3539 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
3540 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
3541 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
3542 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
3543 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
3544
3545 // Grab everything that reaches PrologueMBB to update there liveness as well.
3546 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
3547 SmallVector<MachineBasicBlock *, 2> WalkList;
3548 WalkList.push_back(Elt: &PrologueMBB);
3549
3550 do {
3551 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
3552 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
3553 if (BeforePrologueRegion.insert(Ptr: PredBB).second)
3554 WalkList.push_back(Elt: PredBB);
3555 }
3556 } while (!WalkList.empty());
3557
3558 // The order in that list is important.
3559 // The blocks will all be inserted before PrologueMBB using that order.
3560 // Therefore the block that should appear first in the CFG should appear
3561 // first in the list.
3562 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
3563 PostStackMBB};
3564
3565 BeforePrologueRegion.insert_range(R&: AddedBlocks);
3566
3567 for (const auto &LI : PrologueMBB.liveins()) {
3568 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
3569 PredBB->addLiveIn(RegMaskPair: LI);
3570 }
3571
3572 // Remove the newly added blocks from the list, since we know
3573 // we do not have to do the following updates for them.
3574 for (MachineBasicBlock *B : AddedBlocks) {
3575 BeforePrologueRegion.erase(Ptr: B);
3576 MF.insert(MBBI: PrologueMBB.getIterator(), MBB: B);
3577 }
3578
3579 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
3580 // Make sure the LiveIns are still sorted and unique.
3581 MBB->sortUniqueLiveIns();
3582 // Replace the edges to PrologueMBB by edges to the sequences
3583 // we are about to add, but only update for immediate predecessors.
3584 if (MBB->isSuccessor(MBB: &PrologueMBB))
3585 MBB->ReplaceUsesOfBlockWith(Old: &PrologueMBB, New: AddedBlocks[0]);
3586 }
3587
3588 // The required stack size that is aligned to ARM constant criterion.
3589 AlignedStackSize = alignToARMConstant(Value: StackSize);
3590
3591 // When the frame size is less than 256 we just compare the stack
3592 // boundary directly to the value of the stack pointer, per gcc.
3593 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
3594
3595 // We will use two of the callee save registers as scratch registers so we
3596 // need to save those registers onto the stack.
3597 // We will use SR0 to hold stack limit and SR1 to hold the stack size
3598 // requested and arguments for __morestack().
3599 // SR0: Scratch Register #0
3600 // SR1: Scratch Register #1
3601 // push {SR0, SR1}
3602 if (Thumb) {
3603 BuildMI(BB: PrevStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPUSH))
3604 .add(MOs: predOps(Pred: ARMCC::AL))
3605 .addReg(RegNo: ScratchReg0)
3606 .addReg(RegNo: ScratchReg1);
3607 } else {
3608 BuildMI(BB: PrevStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::STMDB_UPD))
3609 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3610 .addReg(RegNo: ARM::SP)
3611 .add(MOs: predOps(Pred: ARMCC::AL))
3612 .addReg(RegNo: ScratchReg0)
3613 .addReg(RegNo: ScratchReg1);
3614 }
3615
3616 // Emit the relevant DWARF information about the change in stack pointer as
3617 // well as where to find both r4 and r5 (the callee-save registers)
3618 if (!MF.usesWindowsUnwindInfo()) {
3619 CFIInstBuilder CFIBuilder(PrevStackMBB, MachineInstr::NoFlags);
3620 CFIBuilder.buildDefCFAOffset(Offset: 8);
3621 CFIBuilder.buildOffset(Reg: ScratchReg1, Offset: -4);
3622 CFIBuilder.buildOffset(Reg: ScratchReg0, Offset: -8);
3623 }
3624
3625 // mov SR1, sp
3626 if (Thumb) {
3627 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ScratchReg1)
3628 .addReg(RegNo: ARM::SP)
3629 .add(MOs: predOps(Pred: ARMCC::AL));
3630 } else if (CompareStackPointer) {
3631 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVr), DestReg: ScratchReg1)
3632 .addReg(RegNo: ARM::SP)
3633 .add(MOs: predOps(Pred: ARMCC::AL))
3634 .add(MO: condCodeOp());
3635 }
3636
3637 // sub SR1, sp, #StackSize
3638 if (!CompareStackPointer && Thumb) {
3639 if (AlignedStackSize < 256) {
3640 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tSUBi8), DestReg: ScratchReg1)
3641 .add(MO: condCodeOp())
3642 .addReg(RegNo: ScratchReg1)
3643 .addImm(Val: AlignedStackSize)
3644 .add(MOs: predOps(Pred: ARMCC::AL));
3645 } else {
3646 if (Thumb2 || ST->genExecuteOnly()) {
3647 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg0)
3648 .addImm(Val: AlignedStackSize);
3649 } else {
3650 auto MBBI = McrMBB->end();
3651 auto RegInfo = STI.getRegisterInfo();
3652 RegInfo->emitLoadConstPool(MBB&: *McrMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3653 Val: AlignedStackSize);
3654 }
3655 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tSUBrr), DestReg: ScratchReg1)
3656 .add(MO: condCodeOp())
3657 .addReg(RegNo: ScratchReg1)
3658 .addReg(RegNo: ScratchReg0)
3659 .add(MOs: predOps(Pred: ARMCC::AL));
3660 }
3661 } else if (!CompareStackPointer) {
3662 if (AlignedStackSize < 256) {
3663 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::SUBri), DestReg: ScratchReg1)
3664 .addReg(RegNo: ARM::SP)
3665 .addImm(Val: AlignedStackSize)
3666 .add(MOs: predOps(Pred: ARMCC::AL))
3667 .add(MO: condCodeOp());
3668 } else {
3669 auto MBBI = McrMBB->end();
3670 auto RegInfo = STI.getRegisterInfo();
3671 RegInfo->emitLoadConstPool(MBB&: *McrMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3672 Val: AlignedStackSize);
3673 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::SUBrr), DestReg: ScratchReg1)
3674 .addReg(RegNo: ARM::SP)
3675 .addReg(RegNo: ScratchReg0)
3676 .add(MOs: predOps(Pred: ARMCC::AL))
3677 .add(MO: condCodeOp());
3678 }
3679 }
3680
3681 if (Thumb && ST->isThumb1Only()) {
3682 if (ST->genExecuteOnly()) {
3683 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg0)
3684 .addExternalSymbol(FnName: "__STACK_LIMIT");
3685 } else {
3686 unsigned PCLabelId = ARMFI->createPICLabelUId();
3687 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
3688 C&: MF.getFunction().getContext(), s: "__STACK_LIMIT", ID: PCLabelId, PCAdj: 0);
3689 MachineConstantPool *MCP = MF.getConstantPool();
3690 unsigned CPI = MCP->getConstantPoolIndex(V: NewCPV, Alignment: Align(4));
3691
3692 // ldr SR0, [pc, offset(STACK_LIMIT)]
3693 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tLDRpci), DestReg: ScratchReg0)
3694 .addConstantPoolIndex(Idx: CPI)
3695 .add(MOs: predOps(Pred: ARMCC::AL));
3696 }
3697
3698 // ldr SR0, [SR0]
3699 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tLDRi), DestReg: ScratchReg0)
3700 .addReg(RegNo: ScratchReg0)
3701 .addImm(Val: 0)
3702 .add(MOs: predOps(Pred: ARMCC::AL));
3703 } else {
3704 // Get TLS base address from the coprocessor
3705 // mrc p15, #0, SR0, c13, c0, #3
3706 BuildMI(BB: McrMBB, MIMD: DL, MCID: TII.get(Opcode: Thumb ? ARM::t2MRC : ARM::MRC),
3707 DestReg: ScratchReg0)
3708 .addImm(Val: 15)
3709 .addImm(Val: 0)
3710 .addImm(Val: 13)
3711 .addImm(Val: 0)
3712 .addImm(Val: 3)
3713 .add(MOs: predOps(Pred: ARMCC::AL));
3714
3715 // Use the last tls slot on android and a private field of the TCP on linux.
3716 assert(ST->isTargetAndroid() || ST->isTargetLinux());
3717 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
3718
3719 // Get the stack limit from the right offset
3720 // ldr SR0, [sr0, #4 * TlsOffset]
3721 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode: Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
3722 DestReg: ScratchReg0)
3723 .addReg(RegNo: ScratchReg0)
3724 .addImm(Val: 4 * TlsOffset)
3725 .add(MOs: predOps(Pred: ARMCC::AL));
3726 }
3727
3728 // Compare stack limit with stack size requested.
3729 // cmp SR0, SR1
3730 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
3731 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode))
3732 .addReg(RegNo: ScratchReg0)
3733 .addReg(RegNo: ScratchReg1)
3734 .add(MOs: predOps(Pred: ARMCC::AL));
3735
3736 // This jump is taken if StackLimit <= SP - stack required.
3737 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
3738 BuildMI(BB: GetMBB, MIMD: DL, MCID: TII.get(Opcode))
3739 .addMBB(MBB: PostStackMBB)
3740 .addImm(Val: ARMCC::LS)
3741 .addReg(RegNo: ARM::CPSR);
3742
3743 // Calling __morestack(StackSize, Size of stack arguments).
3744 // __morestack knows that the stack size requested is in SR0(r4)
3745 // and amount size of stack arguments is in SR1(r5).
3746
3747 // Pass first argument for the __morestack by Scratch Register #0.
3748 // The amount size of stack required
3749 if (Thumb) {
3750 if (AlignedStackSize < 256) {
3751 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVi8), DestReg: ScratchReg0)
3752 .add(MO: condCodeOp())
3753 .addImm(Val: AlignedStackSize)
3754 .add(MOs: predOps(Pred: ARMCC::AL));
3755 } else {
3756 if (Thumb2 || ST->genExecuteOnly()) {
3757 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg0)
3758 .addImm(Val: AlignedStackSize);
3759 } else {
3760 auto MBBI = AllocMBB->end();
3761 auto RegInfo = STI.getRegisterInfo();
3762 RegInfo->emitLoadConstPool(MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3763 Val: AlignedStackSize);
3764 }
3765 }
3766 } else {
3767 if (AlignedStackSize < 256) {
3768 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVi), DestReg: ScratchReg0)
3769 .addImm(Val: AlignedStackSize)
3770 .add(MOs: predOps(Pred: ARMCC::AL))
3771 .add(MO: condCodeOp());
3772 } else {
3773 auto MBBI = AllocMBB->end();
3774 auto RegInfo = STI.getRegisterInfo();
3775 RegInfo->emitLoadConstPool(MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg0, SubIdx: 0,
3776 Val: AlignedStackSize);
3777 }
3778 }
3779
3780 // Pass second argument for the __morestack by Scratch Register #1.
3781 // The amount size of stack consumed to save function arguments.
3782 if (Thumb) {
3783 if (ARMFI->getArgumentStackSize() < 256) {
3784 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVi8), DestReg: ScratchReg1)
3785 .add(MO: condCodeOp())
3786 .addImm(Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()))
3787 .add(MOs: predOps(Pred: ARMCC::AL));
3788 } else {
3789 if (Thumb2 || ST->genExecuteOnly()) {
3790 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: MovOp), DestReg: ScratchReg1)
3791 .addImm(Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()));
3792 } else {
3793 auto MBBI = AllocMBB->end();
3794 auto RegInfo = STI.getRegisterInfo();
3795 RegInfo->emitLoadConstPool(
3796 MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg1, SubIdx: 0,
3797 Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()));
3798 }
3799 }
3800 } else {
3801 if (alignToARMConstant(Value: ARMFI->getArgumentStackSize()) < 256) {
3802 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::MOVi), DestReg: ScratchReg1)
3803 .addImm(Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()))
3804 .add(MOs: predOps(Pred: ARMCC::AL))
3805 .add(MO: condCodeOp());
3806 } else {
3807 auto MBBI = AllocMBB->end();
3808 auto RegInfo = STI.getRegisterInfo();
3809 RegInfo->emitLoadConstPool(
3810 MBB&: *AllocMBB, MBBI, dl: DL, DestReg: ScratchReg1, SubIdx: 0,
3811 Val: alignToARMConstant(Value: ARMFI->getArgumentStackSize()));
3812 }
3813 }
3814
3815 // push {lr} - Save return address of this function.
3816 if (Thumb) {
3817 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPUSH))
3818 .add(MOs: predOps(Pred: ARMCC::AL))
3819 .addReg(RegNo: ARM::LR);
3820 } else {
3821 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::STMDB_UPD))
3822 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3823 .addReg(RegNo: ARM::SP)
3824 .add(MOs: predOps(Pred: ARMCC::AL))
3825 .addReg(RegNo: ARM::LR);
3826 }
3827
3828 // Emit the DWARF info about the change in stack as well as where to find the
3829 // previous link register
3830 if (!MF.usesWindowsUnwindInfo()) {
3831 CFIInstBuilder CFIBuilder(AllocMBB, MachineInstr::NoFlags);
3832 CFIBuilder.buildDefCFAOffset(Offset: 12);
3833 CFIBuilder.buildOffset(Reg: ARM::LR, Offset: -12);
3834 }
3835
3836 // Call __morestack().
3837 if (Thumb) {
3838 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tBL))
3839 .add(MOs: predOps(Pred: ARMCC::AL))
3840 .addExternalSymbol(FnName: "__morestack");
3841 } else {
3842 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::BL))
3843 .addExternalSymbol(FnName: "__morestack");
3844 }
3845
3846 // pop {lr} - Restore return address of this original function.
3847 if (Thumb) {
3848 if (ST->isThumb1Only()) {
3849 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPOP))
3850 .add(MOs: predOps(Pred: ARMCC::AL))
3851 .addReg(RegNo: ScratchReg0);
3852 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tMOVr), DestReg: ARM::LR)
3853 .addReg(RegNo: ScratchReg0)
3854 .add(MOs: predOps(Pred: ARMCC::AL));
3855 } else {
3856 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::t2LDR_POST))
3857 .addReg(RegNo: ARM::LR, Flags: RegState::Define)
3858 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3859 .addReg(RegNo: ARM::SP)
3860 .addImm(Val: 4)
3861 .add(MOs: predOps(Pred: ARMCC::AL));
3862 }
3863 } else {
3864 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::LDMIA_UPD))
3865 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3866 .addReg(RegNo: ARM::SP)
3867 .add(MOs: predOps(Pred: ARMCC::AL))
3868 .addReg(RegNo: ARM::LR);
3869 }
3870
3871 // Restore SR0 and SR1 in case of __morestack() was called.
3872 // __morestack() will skip PostStackMBB block so we need to restore
3873 // scratch registers from here.
3874 // pop {SR0, SR1}
3875 if (Thumb) {
3876 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPOP))
3877 .add(MOs: predOps(Pred: ARMCC::AL))
3878 .addReg(RegNo: ScratchReg0)
3879 .addReg(RegNo: ScratchReg1);
3880 } else {
3881 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::LDMIA_UPD))
3882 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3883 .addReg(RegNo: ARM::SP)
3884 .add(MOs: predOps(Pred: ARMCC::AL))
3885 .addReg(RegNo: ScratchReg0)
3886 .addReg(RegNo: ScratchReg1);
3887 }
3888
3889 // Update the CFA offset now that we've popped
3890 if (!MF.usesWindowsUnwindInfo())
3891 CFIInstBuilder(AllocMBB, MachineInstr::NoFlags).buildDefCFAOffset(Offset: 0);
3892
3893 // Return from this function.
3894 BuildMI(BB: AllocMBB, MIMD: DL, MCID: TII.get(Opcode: ST->getReturnOpcode())).add(MOs: predOps(Pred: ARMCC::AL));
3895
3896 // Restore SR0 and SR1 in case of __morestack() was not called.
3897 // pop {SR0, SR1}
3898 if (Thumb) {
3899 BuildMI(BB: PostStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::tPOP))
3900 .add(MOs: predOps(Pred: ARMCC::AL))
3901 .addReg(RegNo: ScratchReg0)
3902 .addReg(RegNo: ScratchReg1);
3903 } else {
3904 BuildMI(BB: PostStackMBB, MIMD: DL, MCID: TII.get(Opcode: ARM::LDMIA_UPD))
3905 .addReg(RegNo: ARM::SP, Flags: RegState::Define)
3906 .addReg(RegNo: ARM::SP)
3907 .add(MOs: predOps(Pred: ARMCC::AL))
3908 .addReg(RegNo: ScratchReg0)
3909 .addReg(RegNo: ScratchReg1);
3910 }
3911
3912 // Update the CFA offset now that we've popped
3913 if (!MF.usesWindowsUnwindInfo()) {
3914 CFIInstBuilder CFIBuilder(PostStackMBB, MachineInstr::NoFlags);
3915 CFIBuilder.buildDefCFAOffset(Offset: 0);
3916
3917 // Tell debuggers that r4 and r5 are now the same as they were in the
3918 // previous function, that they're the "Same Value".
3919 CFIBuilder.buildSameValue(Reg: ScratchReg0);
3920 CFIBuilder.buildSameValue(Reg: ScratchReg1);
3921 }
3922
3923 // Organizing MBB lists
3924 PostStackMBB->addSuccessor(Succ: &PrologueMBB);
3925
3926 AllocMBB->addSuccessor(Succ: PostStackMBB);
3927
3928 GetMBB->addSuccessor(Succ: PostStackMBB);
3929 GetMBB->addSuccessor(Succ: AllocMBB);
3930
3931 McrMBB->addSuccessor(Succ: GetMBB);
3932
3933 PrevStackMBB->addSuccessor(Succ: McrMBB);
3934
3935#ifdef EXPENSIVE_CHECKS
3936 MF.verify();
3937#endif
3938}
3939