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