LLVM 23.0.0git
ARMFrameLowering.cpp
Go to the documentation of this file.
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"
115#include "ARMSubtarget.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"
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"
148#include "llvm/Support/Debug.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(true),
167 cl::desc("Align ARM NEON spills in prolog and epilog"));
168
171 unsigned NumAlignedDPRCS2Regs);
172
182
183/// Get the spill area that Reg should be saved into in the prologue.
186 unsigned NumAlignedDPRCS2Regs,
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, 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 ||
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
313
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.
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.
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.
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.
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.
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
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).
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 }
402
403 int ArgumentPopSize = 0;
404 if (IsTailCallReturn) {
405 MachineOperand &StackAdjust = MBBI->getOperand(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.
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();
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("No SEH Opcode for instruction " + TII.getName(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, DL, TII.get(ARM::SEH_Nop))
455 .addImm(/*Wide=*/1)
456 .setMIFlags(Flags);
457 break;
458
459 case ARM::t2MOVi16: { // mov(w) r4, #xx
460 bool Wide = MBBI->getOperand(1).getImm() >= 256;
461 if (!Wide) {
462 MachineInstrBuilder NewInstr =
463 BuildMI(MF, DL, TII.get(ARM::tMOVi8)).setMIFlags(MBBI->getFlags());
464 NewInstr.add(MBBI->getOperand(0));
465 NewInstr.add(t1CondCodeOp(/*isDead=*/true));
466 for (MachineOperand &MO : llvm::drop_begin(MBBI->operands()))
467 NewInstr.add(MO);
468 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr);
469 MBB->erase(MBBI);
470 MBBI = NewMBBI;
471 }
472 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)).addImm(Wide).setMIFlags(Flags);
473 break;
474 }
475
476 case ARM::tBLXr: // blx r12 (__chkstk)
477 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
478 .addImm(/*Wide=*/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, DL, TII.get(ARM::SEH_Nop))
491 .addImm(/*Wide=*/1)
492 .setMIFlags(Flags);
493 MBB->insertAfter(MBBI, MIB);
494 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop))
495 .addImm(/*Wide=*/1)
496 .setMIFlags(Flags);
497 break;
498
499 case ARM::t2STR_PRE:
500 if (MBBI->getOperand(0).getReg() == ARM::SP &&
501 MBBI->getOperand(2).getReg() == ARM::SP &&
502 MBBI->getOperand(3).getImm() == -4) {
503 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
504 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveRegs))
505 .addImm(1ULL << Reg)
506 .addImm(/*Wide=*/1)
507 .setMIFlags(Flags);
508 } else {
509 report_fatal_error("No matching SEH Opcode for t2STR_PRE");
510 }
511 break;
512
513 case ARM::t2LDR_POST:
514 if (MBBI->getOperand(1).getReg() == ARM::SP &&
515 MBBI->getOperand(2).getReg() == ARM::SP &&
516 MBBI->getOperand(3).getImm() == 4) {
517 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
518 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveRegs))
519 .addImm(1ULL << Reg)
520 .addImm(/*Wide=*/1)
521 .setMIFlags(Flags);
522 } else {
523 report_fatal_error("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(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:
559 }
560 MachineInstrBuilder NewInstr =
561 BuildMI(MF, DL, TII.get(NewOpc)).setMIFlags(MBBI->getFlags());
562 for (unsigned i = 2, NumOps = MBBI->getNumOperands(); i != NumOps; ++i)
563 NewInstr.add(MBBI->getOperand(i));
564 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr);
565 MBB->erase(MBBI);
566 MBBI = NewMBBI;
567 }
568 unsigned SEHOpc =
569 (Opc == ARM::t2LDMIA_RET) ? ARM::SEH_SaveRegs_Ret : ARM::SEH_SaveRegs;
570 MIB = BuildMI(MF, DL, TII.get(SEHOpc))
571 .addImm(Mask)
572 .addImm(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(MBBI->operands(), 4)) {
580 unsigned Reg = RegInfo->getSEHRegNum(MO.getReg());
581 if (First == -1)
582 First = Reg;
583 Last = Reg;
584 }
585 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveFRegs))
586 .addImm(First)
587 .addImm(Last)
588 .setMIFlags(Flags);
589 break;
590 }
591 case ARM::tSUBspi:
592 case ARM::tADDspi:
593 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc))
594 .addImm(MBBI->getOperand(2).getImm() * 4)
595 .addImm(/*Wide=*/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, DL, TII.get(ARM::SEH_StackAlloc))
603 .addImm(MBBI->getOperand(2).getImm())
604 .addImm(/*Wide=*/1)
605 .setMIFlags(Flags);
606 break;
607
608 case ARM::tMOVr:
609 if (MBBI->getOperand(1).getReg() == ARM::SP &&
610 (Flags & MachineInstr::FrameSetup)) {
611 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
612 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP))
613 .addImm(Reg)
614 .setMIFlags(Flags);
615 } else if (MBBI->getOperand(0).getReg() == ARM::SP &&
616 (Flags & MachineInstr::FrameDestroy)) {
617 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
618 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP))
619 .addImm(Reg)
620 .setMIFlags(Flags);
621 } else {
622 report_fatal_error("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, DL, TII.get(ARM::SEH_Nop_Ret))
633 .addImm(/*Wide=*/0)
634 .setMIFlags(Flags);
635 break;
636
637 case ARM::TCRETURNdi:
638 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret))
639 .addImm(/*Wide=*/1)
640 .setMIFlags(Flags);
641 break;
642 }
643 return MBB->insertAfter(MBBI, MIB);
644}
645
648 if (MBBI == MBB.begin())
650 return std::prev(MBBI);
651}
652
656 const ARMBaseInstrInfo &TII, unsigned MIFlags) {
657 if (Start.isValid())
658 Start = std::next(Start);
659 else
660 Start = MBB.begin();
661
662 for (auto MI = Start; MI != End;) {
663 auto Next = std::next(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(*Next)) {
667 MI = std::next(Next);
668 while (MI != End && isSEHInstruction(*MI))
669 ++MI;
670 continue;
671 }
672 insertSEH(MI, TII, MIFlags);
673 MI = Next;
674 }
675}
676
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, SrcReg, NumBytes,
684 Pred, PredReg, TII, MIFlags);
685 else
686 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
687 Pred, PredReg, TII, MIFlags);
688}
689
690static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
692 const ARMBaseInstrInfo &TII, int NumBytes,
693 unsigned MIFlags = MachineInstr::NoFlags,
695 unsigned PredReg = 0) {
696 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
697 MIFlags, Pred, PredReg);
698}
699
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
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("stack-probe-size", StackProbeSize);
733 return (StackSizeInBytes >= StackProbeSize) &&
734 !F.hasFnAttribute("no-stack-arg-probe");
735}
736
737namespace {
738
739struct StackAdjustingInsts {
740 struct InstInfo {
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
755
756 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
757 bool BeforeFPSet = false) {
758 InstInfo Info = {I, SPAdjust, BeforeFPSet};
759 Insts.push_back(Info);
760 }
761
762 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
763 auto Info =
764 llvm::find_if(Insts, [&](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(Info.I));
778 CFIBuilder.buildDefCFAOffset(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.
801 const TargetInstrInfo &TII,
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(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(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
825 .addImm(~AlignMask)
827 } else if (AlignMask <= 255) {
828 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
830 .addImm(AlignMask)
832 .add(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(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
840 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
842 .add(condCodeOp());
843 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
845 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
847 .add(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(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
855 .addImm(~AlignMask)
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) {
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
890 MachineBasicBlock &MBB) const {
892 MachineFrameInfo &MFI = MF.getFrameInfo();
894 const TargetMachine &TM = MF.getTarget();
895 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
896 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
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);
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.
927 return;
928
929 StackAdjustingInsts DefCFAOffsetCandidates;
930 bool HasFP = hasFP(MF);
931
932 if (!AFI->hasStackFrame() &&
933 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
934 if (NumBytes != 0) {
935 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
937 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes, true);
938 }
939 if (!NeedsWinCFI)
940 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, HasFP);
941 if (NeedsWinCFI && MBBI != MBB.begin()) {
943 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_PrologEnd))
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, PushPopSplit,
958 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;
972 GPRCS1Size += 4;
973 break;
975 GPRCS2Size += 4;
976 break;
978 FPStatusSize += 4;
979 break;
981 DPRCS1Size += 8;
982 break;
984 GPRCS3Size += 4;
985 break;
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(LastPush, FPCXTSaveSize, BeforeFPPush);
1003 }
1004
1005 // Allocate the vararg register save area.
1006 if (ArgRegsSaveSize) {
1007 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
1009 LastPush = std::prev(MBBI);
1010 DefCFAOffsetCandidates.addInst(LastPush, ArgRegsSaveSize, BeforeFPPush);
1011 }
1012
1013 // Move past area 1.
1014 if (GPRCS1Size > 0) {
1015 GPRCS1Push = LastPush = MBBI++;
1016 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, 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(Align(8), 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(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(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) {
1054 GPRCS2Push = LastPush = MBBI++;
1055 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size, 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(LastPush, 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(STI, MF, &*LastPush, DPRGapSize))
1079 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
1080 else {
1081 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
1083 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize, 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(MBBI, sizeOfSPAdjustment(*MBBI),
1093 BeforeFPPush);
1094 DPRCS1Push = LastPush = MBBI++;
1095 }
1096 }
1097
1098 // Move past the aligned DPRCS2 area.
1099 if (DPRCS2Size > 0) {
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(D8SpillFI);
1106 } else
1107 NumBytes = DPRCS1Offset;
1108
1109 // Move GPRCS3, if using using SplitR11WindowsSEH.
1110 if (GPRCS3Size > 0) {
1112 GPRCS3Push = LastPush = MBBI++;
1113 DefCFAOffsetCandidates.addInst(LastPush, GPRCS3Size, 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, NumBytes)) {
1124 uint32_t NumWords = NumBytes >> 2;
1125
1126 if (NumWords < 65536) {
1127 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
1128 .addImm(NumWords)
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(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
1136 .addImm(NumWords & 0xffff)
1139 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVTi16), ARM::R4)
1140 .addReg(ARM::R4)
1141 .addImm(NumWords >> 16)
1144 }
1145
1146 const ARMTargetLowering *TLI = STI.getTargetLowering();
1147 RTLIB::LibcallImpl ChkStkLibcall = TLI->getLibcallImpl(RTLIB::STACK_PROBE);
1148 if (ChkStkLibcall == RTLIB::Unsupported)
1149 reportFatalUsageError("no available implementation of __chkstk");
1150 const char *ChkStk = TLI->getLibcallImplName(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(MBB, MBBI, dl, TII.get(ARM::tBL))
1160 .addExternalSymbol(ChkStk)
1161 .addReg(ARM::R4, RegState::Implicit)
1163 break;
1164 case CodeModel::Large:
1165 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
1166 .addExternalSymbol(ChkStk)
1168
1169 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
1171 .addReg(ARM::R12, RegState::Kill)
1172 .addReg(ARM::R4, RegState::Implicit)
1174 break;
1175 }
1176
1177 MachineInstrBuilder Instr, SEH;
1178 Instr = BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
1179 .addReg(ARM::SP, RegState::Kill)
1180 .addReg(ARM::R4, RegState::Kill)
1183 .add(condCodeOp());
1184 if (NeedsWinCFIStackAlloc) {
1185 SEH = BuildMI(MF, dl, TII.get(ARM::SEH_StackAlloc))
1186 .addImm(NumBytes)
1187 .addImm(/*Wide=*/1)
1189 MBB.insertAfter(Instr, 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(STI, MF, &*LastPush, NumBytes))
1198 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
1199 else {
1200 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
1202 DefCFAOffsetCandidates.addInst(std::prev(MBBI), 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.
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(FramePtrSpillFI) +
1233 ArgRegsSaveSize + FPCXTSaveSize +
1234 sizeOfSPAdjustment(*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(FramePtrSpillFI) +
1241 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1242 sizeOfSPAdjustment(*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(FramePtrSpillFI) +
1249 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size +
1250 FPStatusSize + GPRCS2Size + DPRCS1Size + DPRGapSize +
1251 sizeOfSPAdjustment(*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(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(!AFI->isThumbFunction(), MBB, AfterPush, dl, TII,
1265 FramePtr, ARM::SP, FPOffsetAfterPush,
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(FramePtr, -MFI.getObjectOffset(FramePtrSpillFI));
1274 else
1275 CFIBuilder.buildDefCFARegister(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()) {
1283 if (HasFP && PushPopSplit == ARMSubtarget::SplitR11WindowsSEH)
1284 End = AfterPush;
1286 BuildMI(MBB, End, dl, TII.get(ARM::SEH_PrologEnd))
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(CSI)) {
1296 MCRegister Reg = Entry.getReg();
1297 int FI = Entry.getFrameIdx();
1299 switch (getSpillArea(Reg, PushPopSplit, AFI->getNumAlignedDPRCS2Regs(),
1300 RegInfo)) {
1301 case SpillArea::GPRCS1:
1302 CFIPos = std::next(GPRCS1Push);
1303 break;
1304 case SpillArea::GPRCS2:
1305 CFIPos = std::next(GPRCS2Push);
1306 break;
1307 case SpillArea::DPRCS1:
1308 CFIPos = std::next(DPRCS1Push);
1309 break;
1310 case SpillArea::GPRCS3:
1311 CFIPos = std::next(GPRCS3Push);
1312 break;
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()) {
1322 .buildOffset(Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg,
1323 MFI.getObjectOffset(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))
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();
1356 if (!AFI->isThumbFunction()) {
1357 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
1358 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(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
1368 .addReg(ARM::SP, RegState::Kill)
1370 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
1371 false);
1372 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
1373 .addReg(ARM::R4, RegState::Kill)
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(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
1388 .addReg(ARM::SP)
1390 .add(condCodeOp());
1391 else
1392 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
1393 .addReg(ARM::SP)
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
1405 MachineBasicBlock &MBB) const {
1406 MachineFrameInfo &MFI = MF.getFrameInfo();
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();
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.
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(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart))
1443 RangeStart = initMBBRange(MBB, MBBI);
1444 }
1445
1446 if (NumBytes + IncomingArgStackToRestore != 0)
1447 emitSPUpdate(isARM, MBB, MBBI, dl, TII,
1448 NumBytes + IncomingArgStackToRestore,
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() &&
1457 if (!MBBI->getFlag(MachineInstr::FrameDestroy))
1458 ++MBBI;
1459 }
1460
1461 if (MF.hasWinCFI()) {
1462 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart))
1464 RangeStart = initMBBRange(MBB, MBBI);
1465 }
1466
1467 // Move SP to start of FP callee save spill area.
1468 NumBytes -=
1469 (ReservedArgStack + AFI->getFPCXTSaveAreaSize() +
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, ARM::SP, FramePtr, -NumBytes,
1481 ARMCC::AL, 0, TII,
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, ARM::R4, FramePtr, -NumBytes,
1495 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
1496 .addReg(ARM::R4)
1499 }
1500 } else {
1501 // Thumb2 or ARM.
1502 if (isARM)
1503 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
1506 .add(condCodeOp())
1508 else
1509 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
1513 }
1514 } else if (NumBytes &&
1515 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
1516 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
1518
1519 // Increment past our save areas.
1520 if (AFI->getGPRCalleeSavedArea3Size()) {
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, AFI->getDPRCalleeSavedGapSize(),
1538 }
1539
1540 if (AFI->getGPRCalleeSavedArea2Size()) {
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 ReservedArgStack + IncomingArgStackToRestore,
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(ARM::t2BXAUT_RET));
1567 else
1568 BuildMI(MBB, MBBI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2AUT));
1569 }
1570 }
1571
1572 if (MF.hasWinCFI()) {
1573 insertSEHRange(MBB, RangeStart, MBB.end(), TII, MachineInstr::FrameDestroy);
1574 BuildMI(MBB, MBB.end(), dl, TII.get(ARM::SEH_EpilogEnd))
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.
1584 int FI,
1585 Register &FrameReg) const {
1586 return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0));
1587}
1588
1591 int FI) const {
1592 const MachineFrameInfo &MFI = MF.getFrameInfo();
1593 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
1595}
1596
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(FI) + MFI.getStackSize();
1605 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
1606 bool isFixed = MFI.isFixedObjectIndex(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,
1682 unsigned StmOpc, unsigned StrOpc,
1683 bool NoGap,
1684 function_ref<bool(unsigned)> Func) const {
1685 MachineFunction &MF = *MBB.getParent();
1688
1689 DebugLoc DL;
1690
1691 using RegAndKill = std::pair<unsigned, bool>;
1692
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(Reg))
1705 MBB.addLiveIn(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(std::make_pair(Reg, /*isKill=*/!isLiveIn));
1718 }
1719
1720 if (Regs.empty())
1721 continue;
1722
1723 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
1724 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1725 });
1726
1727 if (Regs.size() > 1 || StrOpc== 0) {
1728 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1729 .addReg(ARM::SP)
1732 for (const auto &[Reg, Kill] : Regs)
1734 } else if (Regs.size() == 1) {
1735 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1736 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1737 .addReg(ARM::SP)
1739 .addImm(-4)
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,
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;
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(Reg);
1812 }
1813
1814 if (Regs.empty())
1815 continue;
1816
1817 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
1818 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1819 });
1820
1821 if (Regs.size() > 1 || LdrOpc == 0) {
1822 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1823 .addReg(ARM::SP)
1826 for (unsigned Reg : Regs)
1827 MIB.addReg(Reg, getDefRegState(true));
1828 if (DeleteRet) {
1829 if (MI != MBB.end()) {
1830 MIB.copyImplicitOps(*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(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1842 .addReg(ARM::SP, RegState::Define)
1843 .addReg(ARM::SP)
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(0);
1850 } else
1851 MIB.addImm(4);
1852 MIB.add(predOps(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,
1866 unsigned PushOpc) const {
1867 MachineFunction &MF = *MBB.getParent();
1868 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1869
1871 auto RegPresent = [&CSI](MCRegister Reg) {
1872 return llvm::any_of(CSI, [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(MBB, MI, DebugLoc(), TII.get(ARM::VMRS), ARM::R4)
1883
1884 Regs.push_back(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(MBB, MI, DebugLoc(), TII.get(ARM::VMRS_FPEXC), ARM::R5)
1893
1894 Regs.push_back(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(MBB, MI, DebugLoc(), TII.get(PushOpc), ARM::SP)
1904 .addReg(ARM::SP)
1907
1908 for (Register Reg : Regs) {
1909 MIB.addReg(Reg);
1910 }
1911}
1912
1913void ARMFrameLowering::emitFPStatusRestores(
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(CSI, [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(MBB, MI, DebugLoc(), TII.get(LdmOpc), ARM::SP)
1932 .addReg(ARM::SP)
1935
1936 // If FPSCR was saved, it will be popped into R4.
1937 if (RegPresent(ARM::FPSCR)) {
1938 MIB.addReg(ARM::R4, RegState::Define);
1939 }
1940
1941 // If FPEXC was saved, it will be popped into R5.
1942 if (RegPresent(ARM::FPEXC)) {
1943 MIB.addReg(ARM::R5, RegState::Define);
1944 }
1945
1946 // Move the FPSCR value back into the register with the VMSR instruction.
1947 if (RegPresent(ARM::FPSCR)) {
1948 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VMSR))
1949 .addReg(ARM::R4)
1952 }
1953
1954 // Move the FPEXC value back into the register with the VMSR_FPEXC
1955 // instruction.
1956 if (RegPresent(ARM::FPEXC)) {
1957 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VMSR_FPEXC))
1958 .addReg(ARM::R5)
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.
1969 unsigned NumAlignedDPRCS2Regs,
1971 const TargetRegisterInfo *TRI) {
1972 MachineFunction &MF = *MBB.getParent();
1974 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
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(FI, 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(FI, 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(MBB, MI, DL, TII.get(Opc), ARM::R4)
2015 .addReg(ARM::SP)
2016 .addImm(8 * NumAlignedDPRCS2Regs)
2018 .add(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, MI, DL, ARM::R4, MaxAlign, 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(MBB, MI, DL, TII.get(Opc), ARM::SP)
2034 .addReg(ARM::R4)
2036 if (!isThumb)
2037 MIB.add(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(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2048 MBB.addLiveIn(SupReg);
2049 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
2050 .addReg(ARM::R4, RegState::Kill)
2051 .addImm(16)
2052 .addReg(NextReg)
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(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2067 MBB.addLiveIn(SupReg);
2068 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
2069 .addReg(ARM::R4)
2070 .addImm(16)
2071 .addReg(NextReg)
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(NextReg, ARM::dsub_0, &ARM::QPRRegClass);
2082 MBB.addLiveIn(SupReg);
2083 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
2084 .addReg(ARM::R4)
2085 .addImm(16)
2086 .addReg(SupReg)
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(NextReg);
2095 // vstr.64 uses addrmode5 which has an offset scale of 4.
2096 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
2097 .addReg(NextReg)
2098 .addReg(ARM::R4)
2099 .addImm((NextReg - R4BaseReg) * 2)
2101 }
2102
2103 // The last spill instruction inserted should kill the scratch register r4.
2104 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
2105}
2106
2107/// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
2108/// iterator to the following instruction.
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.
2142 unsigned NumAlignedDPRCS2Regs,
2144 const TargetRegisterInfo *TRI) {
2145 MachineFunction &MF = *MBB.getParent();
2147 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
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(MBB, MI, DL, TII.get(Opc), ARM::R4)
2168 .addFrameIndex(D8SpillFI)
2169 .addImm(0)
2171 .add(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(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2180 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
2181 .addReg(ARM::R4, RegState::Define)
2182 .addReg(ARM::R4, RegState::Kill)
2183 .addImm(16)
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(NextReg, ARM::dsub_0, &ARM::QQPRRegClass);
2198 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
2199 .addReg(ARM::R4)
2200 .addImm(16)
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(NextReg, ARM::dsub_0, &ARM::QPRRegClass);
2211 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
2212 .addReg(ARM::R4)
2213 .addImm(16)
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(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
2222 .addReg(ARM::R4)
2223 .addImm(2 * (NextReg - R4BaseReg))
2225
2226 // Last store kills r4.
2227 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
2228}
2229
2233 if (CSI.empty())
2234 return false;
2235
2236 MachineFunction &MF = *MBB.getParent();
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(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2PAC))
2251 }
2252 // Save the non-secure floating point context.
2253 if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) {
2254 return C.getReg() == ARM::FPCXTNS;
2255 })) {
2256 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre),
2257 ARM::SP)
2258 .addReg(ARM::SP)
2259 .addImm(-4)
2261 }
2262
2263 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs,
2264 RegInfo](unsigned Reg, SpillArea TestArea) {
2265 return getSpillArea(Reg, 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, PushOpc, PushOneOpc, false, IsGPRCS1);
2282 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS2);
2283 emitFPStatusSaves(MBB, MI, CSI, PushOpc);
2284 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, IsDPRCS1);
2285 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, 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
2299 if (CSI.empty())
2300 return false;
2301
2302 MachineFunction &MF = *MBB.getParent();
2304 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
2305
2306 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
2307 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
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, 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, PopOpc, LdrOpc, isVarArg, false, IsGPRCS3);
2340 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, IsDPRCS1);
2341 emitFPStatusRestores(MBB, MI, CSI, PopOpc);
2342 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS2);
2343 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS1);
2344
2345 return true;
2346}
2347
2348// FIXME: Make generic?
2350 const ARMBaseInstrInfo &TII,
2351 const ARMSubtarget &STI,
2353 BitVector &SavedRegs,
2354 bool BigFrameOffsets) {
2355 unsigned FnSize = 0;
2356
2357 bool KCFI = MF.getFunction().getParent()->getModuleFlag("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(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 =
2515 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(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(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?
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(Limit, (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, i);
2604 if (RegClass && !RegClass->contains(ARM::SP))
2605 HasNonSPFrameIndex = true;
2606
2607 // Otherwise check the addressing mode.
2608 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
2610 case ARMII::AddrMode2:
2611 // Default 12 bit limit.
2612 break;
2613 case ARMII::AddrMode3:
2615 Limit = std::min(Limit, (1U << 8) - 1);
2616 break;
2618 Limit = std::min(Limit, ((1U << 8) - 1) * 2);
2619 break;
2620 case ARMII::AddrMode5:
2623 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
2624 break;
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(Limit, (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;
2637 Limit = std::min(Limit, ((1U << 7) - 1) * 1);
2638 break;
2640 Limit = std::min(Limit, ((1U << 7) - 1) * 2);
2641 break;
2643 Limit = std::min(Limit, ((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
2661 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
2663 return;
2664
2665 // Naked functions don't spill callee-saved registers.
2666 if (MF.getFunction().hasFnAttribute(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.
2675 return;
2676
2677 // Aligned spills require stack realignment.
2678 if (!static_cast<const ARMBaseRegisterInfo *>(
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(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
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() &&
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.
2714 true /* SpillsLR */))
2715 return false;
2716
2717 return true;
2718}
2719
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.
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, Op.getIndex(), Reg);
2744 if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::SP)
2745 return true;
2746 }
2747 return false;
2748}
2749
2751 BitVector &SavedRegs,
2752 RegScavenger *RS) const {
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)) &&
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());
2772 MachineFrameInfo &MFI = MF.getFrameInfo();
2773 MachineRegisterInfo &MRI = MF.getRegInfo();
2775 (void)TRI; // Silence unused warning in non-assert builds.
2776 Register FramePtr = STI.getFramePointerReg();
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("interrupt") && F.hasFnAttribute("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(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, 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);
2849 for (unsigned i = 0; CSRegs[i]; ++i) {
2850 unsigned Reg = CSRegs[i];
2851 bool Spilled = false;
2852 if (SavedRegs.test(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(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(Reg);
2906 break;
2907 default:
2908 UnspilledCS2GPRs.push_back(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(I) + MFI.getObjectSize(I);
2937 MaxFixedOffset = std::max(MaxFixedOffset, 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, 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, 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) ||
3037 !LRSpilled) {
3038 SavedRegs.set(ARM::LR);
3039 LRSpilled = true;
3040 NumGPRSpills++;
3041 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
3042 if (LRPos != UnspilledCS1GPRs.end())
3043 UnspilledCS1GPRs.erase(LRPos);
3044 }
3045 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
3046 if (FPPos != UnspilledCS1GPRs.end())
3047 UnspilledCS1GPRs.erase(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;
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;
3096 << " return regs used, ExitRegDeficit = "
3097 << ExitRegDeficit << "\n");
3098
3099 int RegDeficit = std::max(EntryRegDeficit, 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(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(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(ARM::R7)) {
3122 --RegDeficit;
3123 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
3124 << RegDeficit << "\n");
3125 } else {
3126 AvailableRegs.push_back(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(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(ARM::LR) &&
3149 if (SavedRegs.test(ARM::LR)) {
3150 --RegDeficit;
3151 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
3152 << RegDeficit << "\n");
3153 } else {
3154 AvailableRegs.push_back(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(Reg))
3174 NumExtraCSSpill++;
3175 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, 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++;
3193 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
3194 if (LRPos != UnspilledCS1GPRs.end())
3195 UnspilledCS1GPRs.erase(LRPos);
3196
3197 ForceLRSpill = false;
3198 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(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(Reg) && !MRI.isPhysRegUsed(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(Reg) && !MRI.isPhysRegUsed(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, *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;
3256 while (NumExtras && !UnspilledCS1GPRs.empty()) {
3257 unsigned Reg = UnspilledCS1GPRs.pop_back_val();
3258 if (!MRI.isReserved(Reg) &&
3259 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
3260 Extras.push_back(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(Reg)) {
3269 Extras.push_back(Reg);
3270 NumExtras--;
3271 }
3272 }
3273 }
3274 if (NumExtras == 0) {
3275 for (unsigned Reg : Extras) {
3276 SavedRegs.set(Reg);
3277 if (!MRI.isPhysRegUsed(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 MFI.CreateSpillStackObject(Size, Alignment));
3289 --RegsNeeded;
3290 }
3291 }
3292 }
3293
3294 if (ForceLRSpill)
3295 SavedRegs.set(ARM::LR);
3296 AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
3297}
3298
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(MF, [](const MachineBasicBlock &MBB) {
3311 return all_of(MBB.terminators(), [](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
3328
3330 BitVector &SavedRegs) const {
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
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() &&
3348 CSI.emplace_back(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)) {
3363 // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8
3364 CSI.insert(find_if(CSI,
3365 [=](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 CalleeSavedInfo(ARM::R12));
3372 break;
3374 // With SplitR11AAPCSSignRA, R12 will always be the highest-addressed CSR
3375 // on the stack.
3376 CSI.insert(CSI.begin(), CalleeSavedInfo(ARM::R12));
3377 break;
3380 "ABI-required frame pointers need a CSR split when signing return "
3381 "address.");
3382 CSI.insert(find_if(CSI,
3383 [=](const auto &CS) {
3384 MCRegister Reg = CS.getReg();
3385 return Reg != ARM::LR;
3386 }),
3387 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
3399 static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}};
3400 NumEntries = std::size(FixedSpillOffsets);
3401 return FixedSpillOffsets;
3402}
3403
3404MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
3407 const ARMBaseInstrInfo &TII =
3408 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
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(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(PIdx).getImm();
3423 unsigned PredReg = TII.getFramePred(*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);
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(Amount);
3439
3440 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
3441 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
3442 Pred, PredReg);
3443 } else {
3444 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
3445 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, 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, I, dl, TII, -CalleePopAmount,
3453 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.
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.
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
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("Segmented stacks do not support vararg functions.");
3526 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
3527 report_fatal_error("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());
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();
3552
3553 // Grab everything that reaches PrologueMBB to update there liveness as well.
3554 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
3556 WalkList.push_back(&PrologueMBB);
3557
3558 do {
3559 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
3560 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
3561 if (BeforePrologueRegion.insert(PredBB).second)
3562 WalkList.push_back(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(AddedBlocks);
3574
3575 for (const auto &LI : PrologueMBB.liveins()) {
3576 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
3577 PredBB->addLiveIn(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(B);
3584 MF.insert(PrologueMBB.getIterator(), 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(&PrologueMBB))
3593 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
3594 }
3595
3596 // The required stack size that is aligned to ARM constant criterion.
3597 AlignedStackSize = alignToARMConstant(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(PrevStackMBB, DL, TII.get(ARM::tPUSH))
3613 .addReg(ScratchReg0)
3614 .addReg(ScratchReg1);
3615 } else {
3616 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
3617 .addReg(ARM::SP, RegState::Define)
3618 .addReg(ARM::SP)
3620 .addReg(ScratchReg0)
3621 .addReg(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(8);
3629 CFIBuilder.buildOffset(ScratchReg1, -4);
3630 CFIBuilder.buildOffset(ScratchReg0, -8);
3631 }
3632
3633 // mov SR1, sp
3634 if (Thumb) {
3635 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
3636 .addReg(ARM::SP)
3638 } else if (CompareStackPointer) {
3639 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
3640 .addReg(ARM::SP)
3642 .add(condCodeOp());
3643 }
3644
3645 // sub SR1, sp, #StackSize
3646 if (!CompareStackPointer && Thumb) {
3647 if (AlignedStackSize < 256) {
3648 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
3649 .add(condCodeOp())
3650 .addReg(ScratchReg1)
3651 .addImm(AlignedStackSize)
3653 } else {
3654 if (Thumb2 || ST->genExecuteOnly()) {
3655 BuildMI(McrMBB, DL, TII.get(MovOp), ScratchReg0)
3656 .addImm(AlignedStackSize);
3657 } else {
3658 auto MBBI = McrMBB->end();
3659 auto RegInfo = STI.getRegisterInfo();
3660 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0,
3661 AlignedStackSize);
3662 }
3663 BuildMI(McrMBB, DL, TII.get(ARM::tSUBrr), ScratchReg1)
3664 .add(condCodeOp())
3665 .addReg(ScratchReg1)
3666 .addReg(ScratchReg0)
3668 }
3669 } else if (!CompareStackPointer) {
3670 if (AlignedStackSize < 256) {
3671 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
3672 .addReg(ARM::SP)
3673 .addImm(AlignedStackSize)
3675 .add(condCodeOp());
3676 } else {
3677 auto MBBI = McrMBB->end();
3678 auto RegInfo = STI.getRegisterInfo();
3679 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0,
3680 AlignedStackSize);
3681 BuildMI(McrMBB, DL, TII.get(ARM::SUBrr), ScratchReg1)
3682 .addReg(ARM::SP)
3683 .addReg(ScratchReg0)
3685 .add(condCodeOp());
3686 }
3687 }
3688
3689 if (Thumb && ST->isThumb1Only()) {
3690 if (ST->genExecuteOnly()) {
3691 BuildMI(GetMBB, DL, TII.get(MovOp), ScratchReg0)
3692 .addExternalSymbol("__STACK_LIMIT");
3693 } else {
3694 unsigned PCLabelId = ARMFI->createPICLabelUId();
3696 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
3698 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4));
3699
3700 // ldr SR0, [pc, offset(STACK_LIMIT)]
3701 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
3704 }
3705
3706 // ldr SR0, [SR0]
3707 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
3708 .addReg(ScratchReg0)
3709 .addImm(0)
3711 } else {
3712 // Get TLS base address from the coprocessor
3713 // mrc p15, #0, SR0, c13, c0, #3
3714 BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
3715 ScratchReg0)
3716 .addImm(15)
3717 .addImm(0)
3718 .addImm(13)
3719 .addImm(0)
3720 .addImm(3)
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(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
3730 ScratchReg0)
3731 .addReg(ScratchReg0)
3732 .addImm(4 * TlsOffset)
3734 }
3735
3736 // Compare stack limit with stack size requested.
3737 // cmp SR0, SR1
3738 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
3739 BuildMI(GetMBB, DL, TII.get(Opcode))
3740 .addReg(ScratchReg0)
3741 .addReg(ScratchReg1)
3743
3744 // This jump is taken if StackLimit <= SP - stack required.
3745 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
3746 BuildMI(GetMBB, DL, TII.get(Opcode))
3747 .addMBB(PostStackMBB)
3749 .addReg(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(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
3760 .add(condCodeOp())
3761 .addImm(AlignedStackSize)
3763 } else {
3764 if (Thumb2 || ST->genExecuteOnly()) {
3765 BuildMI(AllocMBB, DL, TII.get(MovOp), ScratchReg0)
3766 .addImm(AlignedStackSize);
3767 } else {
3768 auto MBBI = AllocMBB->end();
3769 auto RegInfo = STI.getRegisterInfo();
3770 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0,
3771 AlignedStackSize);
3772 }
3773 }
3774 } else {
3775 if (AlignedStackSize < 256) {
3776 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
3777 .addImm(AlignedStackSize)
3779 .add(condCodeOp());
3780 } else {
3781 auto MBBI = AllocMBB->end();
3782 auto RegInfo = STI.getRegisterInfo();
3783 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0,
3784 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(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
3793 .add(condCodeOp())
3796 } else {
3797 if (Thumb2 || ST->genExecuteOnly()) {
3798 BuildMI(AllocMBB, DL, TII.get(MovOp), ScratchReg1)
3800 } else {
3801 auto MBBI = AllocMBB->end();
3802 auto RegInfo = STI.getRegisterInfo();
3803 RegInfo->emitLoadConstPool(
3804 *AllocMBB, MBBI, DL, ScratchReg1, 0,
3806 }
3807 }
3808 } else {
3809 if (alignToARMConstant(ARMFI->getArgumentStackSize()) < 256) {
3810 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
3813 .add(condCodeOp());
3814 } else {
3815 auto MBBI = AllocMBB->end();
3816 auto RegInfo = STI.getRegisterInfo();
3817 RegInfo->emitLoadConstPool(
3818 *AllocMBB, MBBI, DL, ScratchReg1, 0,
3820 }
3821 }
3822
3823 // push {lr} - Save return address of this function.
3824 if (Thumb) {
3825 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
3827 .addReg(ARM::LR);
3828 } else {
3829 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
3830 .addReg(ARM::SP, RegState::Define)
3831 .addReg(ARM::SP)
3833 .addReg(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(12);
3841 CFIBuilder.buildOffset(ARM::LR, -12);
3842 }
3843
3844 // Call __morestack().
3845 if (Thumb) {
3846 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
3848 .addExternalSymbol("__morestack");
3849 } else {
3850 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
3851 .addExternalSymbol("__morestack");
3852 }
3853
3854 // pop {lr} - Restore return address of this original function.
3855 if (Thumb) {
3856 if (ST->isThumb1Only()) {
3857 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
3859 .addReg(ScratchReg0);
3860 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
3861 .addReg(ScratchReg0)
3863 } else {
3864 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
3865 .addReg(ARM::LR, RegState::Define)
3866 .addReg(ARM::SP, RegState::Define)
3867 .addReg(ARM::SP)
3868 .addImm(4)
3870 }
3871 } else {
3872 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
3873 .addReg(ARM::SP, RegState::Define)
3874 .addReg(ARM::SP)
3876 .addReg(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(AllocMBB, DL, TII.get(ARM::tPOP))
3886 .addReg(ScratchReg0)
3887 .addReg(ScratchReg1);
3888 } else {
3889 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
3890 .addReg(ARM::SP, RegState::Define)
3891 .addReg(ARM::SP)
3893 .addReg(ScratchReg0)
3894 .addReg(ScratchReg1);
3895 }
3896
3897 // Update the CFA offset now that we've popped
3900
3901 // Return from this function.
3902 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
3903
3904 // Restore SR0 and SR1 in case of __morestack() was not called.
3905 // pop {SR0, SR1}
3906 if (Thumb) {
3907 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
3909 .addReg(ScratchReg0)
3910 .addReg(ScratchReg1);
3911 } else {
3912 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
3913 .addReg(ARM::SP, RegState::Define)
3914 .addReg(ARM::SP)
3916 .addReg(ScratchReg0)
3917 .addReg(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(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(ScratchReg0);
3928 CFIBuilder.buildSameValue(ScratchReg1);
3929 }
3930
3931 // Organizing MBB lists
3932 PostStackMBB->addSuccessor(&PrologueMBB);
3933
3934 AllocMBB->addSuccessor(PostStackMBB);
3935
3936 GetMBB->addSuccessor(PostStackMBB);
3937 GetMBB->addSuccessor(AllocMBB);
3938
3939 McrMBB->addSuccessor(GetMBB);
3940
3941 PrevStackMBB->addSuccessor(McrMBB);
3942
3943#ifdef EXPENSIVE_CHECKS
3944 MF.verify();
3945#endif
3946}
static unsigned estimateRSStackSizeLimit(MachineFunction &MF)
Look at each instruction that references stack frames and return the stack size limit beyond which so...
static bool needsWinCFI(const MachineFunction *MF)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isThumb(const MCSubtargetInfo &STI)
static MachineBasicBlock::iterator skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, unsigned NumAlignedDPRCS2Regs)
Skip past the code inserted by emitAlignedDPRCS2Spills, and return an iterator to the following instr...
static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI, const TargetInstrInfo &TII, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const unsigned Reg, const Align Alignment, const bool MustBeSingleInstruction)
Emit an instruction sequence that will align the address in register Reg by zero-ing out the lower bi...
static uint32_t alignToARMConstant(uint32_t Value)
Get the minimum constant for ARM that is greater than or equal to the argument.
static void checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs)
static void insertSEHRange(MachineBasicBlock &MBB, MachineBasicBlock::iterator Start, const MachineBasicBlock::iterator &End, const ARMBaseInstrInfo &TII, unsigned MIFlags)
static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF, const ARMBaseInstrInfo &TII, const ARMSubtarget &STI, const ARMBaseRegisterInfo *RegInfo, BitVector &SavedRegs, bool BigFrameOffsets)
static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned NumAlignedDPRCS2Regs, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI)
Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers starting from d8.
static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned NumAlignedDPRCS2Regs, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI)
Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers starting from d8.
static int getArgumentStackToRestore(MachineFunction &MF, MachineBasicBlock &MBB)
static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, const ARMBaseInstrInfo &TII, int NumBytes, unsigned MIFlags=MachineInstr::NoFlags, ARMCC::CondCodes Pred=ARMCC::AL, unsigned PredReg=0)
static MachineBasicBlock::iterator insertSEH(MachineBasicBlock::iterator MBBI, const TargetInstrInfo &TII, unsigned Flags)
SpillArea getSpillArea(Register Reg, ARMSubtarget::PushPopSplitVariation Variation, unsigned NumAlignedDPRCS2Regs, const ARMBaseRegisterInfo *RegInfo)
Get the spill area that Reg should be saved into in the prologue.
static bool canSpillOnFrameIndexAccess(const MachineFunction &MF, const TargetFrameLowering &TFI)
static bool WindowsRequiresStackProbe(const MachineFunction &MF, size_t StackSizeInBytes)
static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI, const MachineFunction &MF)
We need the offset of the frame pointer relative to other MachineFrameInfo offsets which are encoded ...
static MachineBasicBlock::iterator initMBBRange(MachineBasicBlock &MBB, const MachineBasicBlock::iterator &MBBI)
static int sizeOfSPAdjustment(const MachineInstr &MI)
static const uint64_t kSplitStackAvailable
static cl::opt< bool > SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true), cl::desc("Align ARM NEON spills in prolog and epilog"))
static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg, unsigned SrcReg, int NumBytes, unsigned MIFlags=MachineInstr::NoFlags, ARMCC::CondCodes Pred=ARMCC::AL, unsigned PredReg=0)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file declares the machine register scavenger class.
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
static const unsigned FramePtr
bool canRealignStack(const MachineFunction &MF) const override
static ARMConstantPoolSymbol * Create(LLVMContext &C, StringRef s, unsigned ID, unsigned char PCAdj)
ARMConstantPoolValue - ARM specific constantpool value.
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
StackOffset getNonLocalFrameIndexReference(const MachineFunction &MF, int FI) const override
getNonLocalFrameIndexReference - This method returns the offset used to reference a frame index locat...
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - Provide a base+offset reference to an FI slot for debug info.
bool keepFramePointer(const MachineFunction &MF) const
static void updateLRRestored(MachineFunction &MF)
Update the IsRestored flag on LR if it is spilled, based on the return instructions.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
ARMFrameLowering(const ARMSubtarget &sti)
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
bool requiresAAPCSFrameRecord(const MachineFunction &MF) const
bool isFPReserved(const MachineFunction &MF) const
isFPReserved - Return true if the frame pointer register should be considered a reserved register on ...
bool canSimplifyCallFramePseudos(const MachineFunction &MF) const override
canSimplifyCallFramePseudos - If there is a reserved call frame, the call frame pseudos can be simpli...
void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &MBB) const override
Adjust the prologue to have the function use segmented stacks.
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const override
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool hasFPImpl(const MachineFunction &MF) const override
hasFPImpl - Return true if the specified function should have a dedicated frame pointer register.
int ResolveFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg, int SPAdj) const
void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const override
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs.
const ARMSubtarget & STI
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
bool enableCalleeSaveSkip(const MachineFunction &MF) const override
Returns true if the target can safely skip saving callee-saved registers for noreturn nounwind functi...
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
unsigned getFPCXTSaveAreaSize() const
unsigned getGPRCalleeSavedArea1Size() const
unsigned getDPRCalleeSavedGapSize() const
unsigned getDPRCalleeSavedArea1Size() const
void setDPRCalleeSavedArea1Offset(unsigned o)
void setGPRCalleeSavedArea2Size(unsigned s)
void setFramePtrSpillOffset(unsigned o)
unsigned getGPRCalleeSavedArea2Size() const
unsigned getNumAlignedDPRCS2Regs() const
void setGPRCalleeSavedArea1Size(unsigned s)
unsigned getArgumentStackToRestore() const
void setFPCXTSaveAreaSize(unsigned s)
unsigned getGPRCalleeSavedArea3Size() const
unsigned getFramePtrSpillOffset() const
unsigned getArgRegsSaveSize() const
void setGPRCalleeSavedArea2Offset(unsigned o)
void setGPRCalleeSavedArea1Offset(unsigned o)
void setDPRCalleeSavedArea1Size(unsigned s)
void setDPRCalleeSavedGapSize(unsigned s)
void setFPStatusSavesSize(unsigned s)
unsigned getArgumentStackSize() const
unsigned getReturnRegsCount() const
void setGPRCalleeSavedArea3Size(unsigned s)
unsigned getFPStatusSavesSize() const
const ARMBaseRegisterInfo * getRegisterInfo() const override
enum PushPopSplitVariation getPushPopSplitVariation(const MachineFunction &MF) const
PushPopSplitVariation
How the push and pop instructions of callee saved general-purpose registers should be split.
@ SplitR11WindowsSEH
When the stack frame size is not known (because of variable-sized objects or realignment),...
@ SplitR7
R7 and LR must be adjacent, because R7 is the frame pointer, and must point to a frame record consist...
@ SplitR11AAPCSSignRA
When generating AAPCS-compilant frame chains, R11 is the frame pointer, and must be pushed adjacent t...
@ NoSplit
All GPRs can be pushed in a single instruction.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
Helper class for creating CFI instructions and inserting them into MIR.
void buildDefCFAOffset(int64_t Offset, MCSymbol *Label=nullptr) const
void buildDefCFARegister(MCRegister Reg) const
void buildSameValue(MCRegister Reg) const
void buildOffset(MCRegister Reg, int64_t Offset) const
void buildDefCFA(MCRegister Reg, int64_t Offset) const
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition DebugLoc.h:126
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:353
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:723
Module * getParent()
Get the module that this global value is contained inside of...
bool usesWindowsCFI() const
Definition MCAsmInfo.h:674
Describe properties that are true of each instruction in the target description file.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
iterator_range< livein_iterator > liveins() const
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
LLVM_ABI unsigned getConstantPoolIndex(const Constant *C, Align Alignment)
getConstantPoolIndex - Create a new entry in the constant pool or return an existing one.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool needsSplitStackProlog() const
Return true if this function requires a split stack prolog, even if it uses no stack space.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool isReturnAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
int getStackProtectorIndex() const
Return the index for the stack protector object.
int64_t getOffsetAdjustment() const
Return the correction for frame offsets.
bool isCalleeSavedInfoValid() const
Has the callee saved info been calculated yet?
LLVM_ABI BitVector getPristineRegs(const MachineFunction &MF) const
Return a set of physical registers that are pristine.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
void setOffsetAdjustment(int64_t Adj)
Set the correction for frame offsets.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, raw_ostream *OS=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
Representation of each machine instruction.
LLVM_ABI bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
A description of a memory reference used in the backend.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
LLVM_ABI bool isLiveIn(Register Reg) const
LLVM_ABI bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest=false) const
Return true if the specified register is modified or read in this function.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Special value supplied for machine level alias analysis.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
bool erase(PtrType Ptr)
Remove pointer from the set.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
iterator erase(const_iterator CI)
typename SuperClass::iterator iterator
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
virtual void getCalleeSaves(const MachineFunction &MF, BitVector &SavedRegs) const
Returns the callee-saved registers as computed by determineCalleeSaves in the BitVector SavedRegs.
TargetFrameLowering(StackDirection D, Align StackAl, int LAO, Align TransAl=Align(1), bool StackReal=true)
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Get the libcall impl routine name for the specified libcall.
static StringRef getLibcallImplName(RTLIB::LibcallImpl Call)
Get the libcall routine name for the specified libcall implementation.
Primary interface to the complete machine description for the target machine.
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
TargetOptions Options
LLVM_ABI bool FramePointerIsReserved(const MachineFunction &MF) const
FramePointerIsReserved - This returns true if the frame pointer must always either point to a new fra...
LLVM_ABI bool DisableFramePointerElim(const MachineFunction &MF) const
DisableFramePointerElim - This returns true if frame pointer elimination optimization should be disab...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM Value Representation.
Definition Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned getAM2Opc(AddrOpc Opc, unsigned Imm12, ShiftOpc SO, unsigned IdxMode=0)
unsigned getSORegOpc(ShiftOpc ShOp, unsigned Imm)
@ D16
Only 16 D registers.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:395
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:573
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Kill
The last use of a register.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
static bool isARMLowRegister(MCRegister Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
static bool isSEHInstruction(const MachineInstr &MI)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
bool tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget, MachineFunction &MF, MachineInstr *MI, unsigned NumBytes)
Tries to add registers to the reglist of a given base-updating push/pop instruction to adjust the sta...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr RegState getDefRegState(bool B)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
DWARFExpression::Operation Op
static MachineOperand t1CondCodeOp(bool isDead=false)
Get the operand corresponding to the conditional code result for Thumb1.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1772
static MachineOperand condCodeOp(unsigned CCReg=0)
Get the operand corresponding to the conditional code result.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
void emitARMRegPlusImmediate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, Register DestReg, Register BaseReg, int NumBytes, ARMCC::CondCodes Pred, Register PredReg, const ARMBaseInstrInfo &TII, unsigned MIFlags=0)
emitARMRegPlusImmediate / emitT2RegPlusImmediate - Emits a series of instructions to materializea des...
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
void emitT2RegPlusImmediate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, Register DestReg, Register BaseReg, int NumBytes, ARMCC::CondCodes Pred, Register PredReg, const ARMBaseInstrInfo &TII, unsigned MIFlags=0)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77