LLVM 24.0.0git
HexagonFrameLowering.cpp
Go to the documentation of this file.
1//===- HexagonFrameLowering.cpp - Define frame lowering -------------------===//
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
11#include "HexagonBlockRanges.h"
12#include "HexagonISelLowering.h"
13#include "HexagonInstrInfo.h"
15#include "HexagonRegisterInfo.h"
16#include "HexagonSubtarget.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/Function.h"
48#include "llvm/MC/MCDwarf.h"
50#include "llvm/Pass.h"
53#include "llvm/Support/Debug.h"
55#include "llvm/Support/LEB128.h"
59#include <algorithm>
60#include <cassert>
61#include <cstdint>
62#include <iterator>
63#include <limits>
64#include <map>
65#include <optional>
66#include <utility>
67#include <vector>
68
69#define DEBUG_TYPE "hexagon-pei"
70
72 llvm::Type *Ty) {
73 if (Ty->isVectorTy())
74 return HST.isTypeForHLX(Ty);
75 if (auto *ArrayTy = llvm::dyn_cast<llvm::ArrayType>(Ty))
76 return containsHLXObject(HST, ArrayTy->getElementType());
77 if (auto *StructTy = llvm::dyn_cast<llvm::StructType>(Ty))
78 return llvm::any_of(StructTy->elements(), [&](llvm::Type *EltTy) {
79 return containsHLXObject(HST, EltTy);
80 });
81 return false;
82}
83
84// Hexagon stack frame layout as defined by the ABI:
85//
86// Incoming arguments
87// passed via stack
88// |
89// |
90// SP during function's FP during function's |
91// +-- runtime (top of stack) runtime (bottom) --+ |
92// | | |
93// --++---------------------+------------------+-----------------++-+-------
94// | parameter area for | variable-size | fixed-size |LR| arg
95// | called functions | local objects | local objects |FP|
96// --+----------------------+------------------+-----------------+--+-------
97// <- size known -> <- size unknown -> <- size known ->
98//
99// Low address High address
100//
101// <--- stack growth
102//
103//
104// - In any circumstances, the outgoing function arguments are always accessi-
105// ble using the SP, and the incoming arguments are accessible using the FP.
106// - If the local objects are not aligned, they can always be accessed using
107// the FP.
108// - If there are no variable-sized objects, the local objects can always be
109// accessed using the SP, regardless whether they are aligned or not. (The
110// alignment padding will be at the bottom of the stack (highest address),
111// and so the offset with respect to the SP will be known at the compile-
112// -time.)
113//
114// The only complication occurs if there are both, local aligned objects, and
115// dynamically allocated (variable-sized) objects. The alignment pad will be
116// placed between the FP and the local objects, thus preventing the use of the
117// FP to access the local objects. At the same time, the variable-sized objects
118// will be between the SP and the local objects, thus introducing an unknown
119// distance from the SP to the locals.
120//
121// To avoid this problem, a new register is created that holds the aligned
122// address of the bottom of the stack, referred in the sources as AP (aligned
123// pointer). The AP will be equal to "FP-p", where "p" is the smallest pad
124// that aligns AP to the required boundary (a maximum of the alignments of
125// all stack objects, fixed- and variable-sized). All local objects[1] will
126// then use AP as the base pointer.
127// [1] The exception is with "fixed" stack objects. "Fixed" stack objects get
128// their name from being allocated at fixed locations on the stack, relative
129// to the FP. In the presence of dynamic allocation and local alignment, such
130// objects can only be accessed through the FP.
131//
132// Illustration of the AP:
133// FP --+
134// |
135// ---------------+---------------------+-----+-----------------------++-+--
136// Rest of the | Local stack objects | Pad | Fixed stack objects |LR|
137// stack frame | (aligned) | | (CSR, spills, etc.) |FP|
138// ---------------+---------------------+-----+-----------------+-----+--+--
139// |<-- Multiple of the -->|
140// stack alignment +-- AP
141//
142// The AP is set up at the beginning of the function. Since it is not a dedi-
143// cated (reserved) register, it needs to be kept live throughout the function
144// to be available as the base register for local object accesses.
145// Normally, an address of a stack objects is obtained by a pseudo-instruction
146// PS_fi. To access local objects with the AP register present, a different
147// pseudo-instruction needs to be used: PS_fia. The PS_fia takes one extra
148// argument compared to PS_fi: the first input register is the AP register.
149// This keeps the register live between its definition and its uses.
150
151// The AP register is originally set up using pseudo-instruction PS_aligna:
152// AP = PS_aligna A
153// where
154// A - required stack alignment
155// The alignment value must be the maximum of all alignments required by
156// any stack object.
157
158// The dynamic allocation uses a pseudo-instruction PS_alloca:
159// Rd = PS_alloca Rs, A
160// where
161// Rd - address of the allocated space
162// Rs - minimum size (the actual allocated can be larger to accommodate
163// alignment)
164// A - required alignment
165
166using namespace llvm;
167
170 const DebugLoc &DL) {
171 if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
172 return;
173
174 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
175 // Hexagon saves LR (R31) via allocframe. If there is no frame, LR is
176 // not on the regular stack and does not need shadow-stack protection.
177 if (!HST.getFrameLowering()->hasFP(MF))
178 return;
179
180 // The shadow call stack pointer has to survive arbitrary calls, so it is
181 // always one of the callee-saved registers R16-R27 (Hexagon ABI, "Register
182 // usage across calls"). It must also be reserved: besides keeping the
183 // register allocator away from it, reserving it keeps it out of the
184 // callee-saved set, so it is never spilled and restored as an ordinary
185 // callee-saved register - which would leave the epilogue below reading the
186 // *caller's* shadow-stack slot. The spill stubs are handled separately in
187 // useSpillFunction()/useRestoreFunction().
188 Register SCSPReg = HST.getSCSPReg();
189 const auto &HRI = *HST.getRegisterInfo();
190 if (!HST.isRegisterReservedByUser(SCSPReg))
191 // Lower-cased to match the spelling of the -ffixed-<reg> flag the user
192 // needs to pass; TRI names the register "R18".
193 report_fatal_error(Twine("Must reserve ") +
194 StringRef(HRI.getName(SCSPReg)).lower() +
195 " to use shadow call stack on Hexagon");
196
197 const auto &HII = *HST.getInstrInfo();
198
199 // SCSPReg = add(SCSPReg, #4)
200 BuildMI(MBB, MI, DL, HII.get(Hexagon::A2_addi), SCSPReg)
201 .addReg(SCSPReg)
202 .addImm(4)
204 // memw(SCSPReg + #-4) = r31
205 BuildMI(MBB, MI, DL, HII.get(Hexagon::S2_storeri_io))
206 .addReg(SCSPReg)
207 .addImm(-4)
208 .addReg(Hexagon::R31)
210
211 MBB.addLiveIn(SCSPReg);
212
213 if (!MF.needsFrameMoves())
214 return;
215
216 // CFI: DW_CFA_val_expression for the SCS register, DW_OP_bregN -4
217 // Tells the unwinder that the SCS register at entry = current value - 4.
218 unsigned DwarfSCSReg = HRI.getDwarfRegNum(SCSPReg, /*IsEH=*/true);
219 // DW_OP_breg0..DW_OP_breg31 (0x70..0x8f) are 32 opcodes indexed by
220 // register number, so the register number must fit in [0, 31].
221 assert(DwarfSCSReg < 32 && "SCS register should be < 32");
222 const char CFIInst[] = {
223 (char)dwarf::DW_CFA_val_expression,
224 (char)DwarfSCSReg,
225 2, // expression length
226 (char)(unsigned)(dwarf::DW_OP_breg0 + DwarfSCSReg),
227 (char)(-4 & 0x7f), // SLEB128 -4
228 };
230 .buildEscape(StringRef(CFIInst, sizeof(CFIInst)));
231}
232
235 const DebugLoc &DL) {
236 if (!MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
237 return;
238
239 // hasFP() is true at both call sites: the non-vararg path in
240 // insertEpilogueInBlock returns early when !hasFP(), and the vararg+musl
241 // path is inside the hasFP() branch. Check defensively.
243 report_fatal_error("SCS epilogue requires a frame");
244
245 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
246 Register SCSPReg = HST.getSCSPReg();
247 const auto &HII = *HST.getInstrInfo();
248
249 // r31 = memw(SCSPReg + #-4)
250 BuildMI(MBB, MI, DL, HII.get(Hexagon::L2_loadri_io), Hexagon::R31)
251 .addReg(SCSPReg)
252 .addImm(-4)
254 // SCSPReg = add(SCSPReg, #-4)
255 BuildMI(MBB, MI, DL, HII.get(Hexagon::A2_addi), SCSPReg)
256 .addReg(SCSPReg)
257 .addImm(-4)
259
260 if (MF.needsFrameMoves())
262}
263
264#ifndef NDEBUG
265static unsigned SpillOptCount = 0;
266#endif
267
268namespace {
269
270 class HexagonCallFrameInformation : public MachineFunctionPass {
271 public:
272 static char ID;
273
274 HexagonCallFrameInformation() : MachineFunctionPass(ID) {}
275
276 bool runOnMachineFunction(MachineFunction &MF) override;
277
278 MachineFunctionProperties getRequiredProperties() const override {
279 return MachineFunctionProperties().setNoVRegs();
280 }
281 };
282
283 char HexagonCallFrameInformation::ID = 0;
284
285} // end anonymous namespace
286
287bool HexagonCallFrameInformation::runOnMachineFunction(MachineFunction &MF) {
288 auto &HFI = *MF.getSubtarget<HexagonSubtarget>().getFrameLowering();
289 bool NeedCFI = MF.needsFrameMoves();
290
291 if (!NeedCFI)
292 return false;
293 HFI.insertCFIInstructions(MF);
294 return true;
295}
296
297INITIALIZE_PASS(HexagonCallFrameInformation, "hexagon-cfi",
298 "Hexagon call frame information", false, false)
299
301 return new HexagonCallFrameInformation();
302}
303
304/// Map a register pair Reg to the subregister that has the greater "number",
305/// i.e. D3 (aka R7:6) will be mapped to R7, etc.
307 const TargetRegisterInfo &TRI,
308 bool hireg = true) {
309 if (Reg < Hexagon::D0 || Reg > Hexagon::D15)
310 return Reg;
311
312 Register RegNo = 0;
313 for (MCPhysReg SubReg : TRI.subregs(Reg)) {
314 if (hireg) {
315 if (SubReg > RegNo)
316 RegNo = SubReg;
317 } else {
318 if (!RegNo || SubReg < RegNo)
319 RegNo = SubReg;
320 }
321 }
322 return RegNo;
323}
324
325/// Returns the callee saved register with the largest id in the vector.
327 const TargetRegisterInfo &TRI) {
328 static_assert(Hexagon::R1 > 0,
329 "Assume physical registers are encoded as positive integers");
330 if (CSI.empty())
331 return 0;
332
333 Register Max = getMax32BitSubRegister(CSI[0].getReg(), TRI);
334 for (unsigned I = 1, E = CSI.size(); I < E; ++I) {
336 if (Reg > Max)
337 Max = Reg;
338 }
339 return Max;
340}
341
342/// Checks if the basic block contains any instruction that needs a stack
343/// frame to be already in place.
344static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR,
345 const HexagonRegisterInfo &HRI) {
346 const MachineFunction *MF = MBB.getParent();
347 if (&MBB == &MF->front() && MF->getInfo<HexagonMachineFunctionInfo>()
349 .isValid())
350 return true;
351
352 for (const MachineInstr &MI : MBB) {
353 if (MI.isCall())
354 return true;
355 unsigned Opc = MI.getOpcode();
356 switch (Opc) {
357 case Hexagon::PS_alloca:
358 return true;
359 default:
360 break;
361 }
362 // Check individual operands.
363 for (const MachineOperand &MO : MI.operands()) {
364 // While the presence of a frame index does not prove that a stack
365 // frame will be required, all frame indexes should be within alloc-
366 // frame/deallocframe. Otherwise, the code that translates a frame
367 // index into an offset would have to be aware of the placement of
368 // the frame creation/destruction instructions.
369 if (MO.isFI())
370 return true;
371 if (MO.isReg()) {
372 Register R = MO.getReg();
373 // Debug instructions may refer to $noreg.
374 if (!R)
375 continue;
376 // Virtual registers will need scavenging, which then may require
377 // a stack slot.
378 if (R.isVirtual())
379 return true;
380 for (MCPhysReg S : HRI.subregs_inclusive(R))
381 if (CSR[S])
382 return true;
383 continue;
384 }
385 if (MO.isRegMask()) {
386 // A regmask would normally have all callee-saved registers marked
387 // as preserved, so this check would not be needed, but in case of
388 // ever having other regmasks (for other calling conventions),
389 // make sure they would be processed correctly.
390 const uint32_t *BM = MO.getRegMask();
391 for (int x = CSR.find_first(); x >= 0; x = CSR.find_next(x)) {
392 unsigned R = x;
393 // If this regmask does not preserve a CSR, a frame will be needed.
394 if (!(BM[R / 32] & (1u << (R % 32))))
395 return true;
396 }
397 }
398 }
399 }
400 return false;
401}
402
403/// Returns true if MBB has a machine instructions that indicates a tail call
404/// in the block.
405static bool hasTailCall(const MachineBasicBlock &MBB) {
406 MachineBasicBlock::const_iterator I = MBB.getLastNonDebugInstr();
407 if (I == MBB.end())
408 return false;
409 unsigned RetOpc = I->getOpcode();
410 return RetOpc == Hexagon::PS_tailcall_i || RetOpc == Hexagon::PS_tailcall_r;
411}
412
413/// Returns true if MBB contains an instruction that returns.
414static bool hasReturn(const MachineBasicBlock &MBB) {
415 for (const MachineInstr &MI : MBB.terminators())
416 if (MI.isReturn())
417 return true;
418 return false;
419}
420
421/// Returns the "return" instruction from this block, or nullptr if there
422/// isn't any.
424 for (auto &I : MBB)
425 if (I.isReturn())
426 return &I;
427 return nullptr;
428}
429
430static bool isRestoreCall(unsigned Opc) {
431 switch (Opc) {
432 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
433 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
434 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT:
435 case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC:
436 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT:
437 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC:
438 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4:
439 case Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC:
440 return true;
441 }
442 return false;
443}
444
445static inline bool isOptNone(const MachineFunction &MF) {
446 return MF.getFunction().hasOptNone() ||
448}
449
450static inline bool isOptSize(const MachineFunction &MF) {
451 const Function &F = MF.getFunction();
452 return F.hasOptSize() && !F.hasMinSize();
453}
454
455static inline bool isMinSize(const MachineFunction &MF) {
456 return MF.getFunction().hasMinSize();
457}
458
459/// Implements shrink-wrapping of the stack frame. By default, stack frame
460/// is created in the function entry block, and is cleaned up in every block
461/// that returns. This function finds alternate blocks: one for the frame
462/// setup (prolog) and one for the cleanup (epilog).
463void HexagonFrameLowering::findShrunkPrologEpilog(MachineFunction &MF,
464 MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const {
465 static unsigned ShrinkCounter = 0;
466
467 if (MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl() &&
468 MF.getFunction().isVarArg())
469 return;
470 // The caller's VSP is saved through R7, which is only known to be free
471 // in the entry block.
472 if (MF.getSubtarget<HexagonSubtarget>().useHLXOps())
473 return;
474 const auto &CLOpts = MF.getSubtarget<HexagonSubtarget>().getCLOpts();
475 if (CLOpts.shrink_frame_limit) {
476 if (ShrinkCounter >= *CLOpts.shrink_frame_limit)
477 return;
478 ShrinkCounter++;
479 }
480
481 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
482
483 MachineDominatorTree MDT;
484 MDT.recalculate(MF);
485 MachinePostDominatorTree MPT;
486 MPT.recalculate(MF);
487
488 using UnsignedMap = DenseMap<unsigned, unsigned>;
489 using RPOTType = ReversePostOrderTraversal<const MachineFunction *>;
490
491 UnsignedMap RPO;
492 RPOTType RPOT(&MF);
493 unsigned RPON = 0;
494 for (auto &I : RPOT)
495 RPO[I->getNumber()] = RPON++;
496
497 // Don't process functions that have loops, at least for now. Placement
498 // of prolog and epilog must take loop structure into account. For simpli-
499 // city don't do it right now.
500 for (auto &I : MF) {
501 unsigned BN = RPO[I.getNumber()];
502 for (MachineBasicBlock *Succ : I.successors())
503 // If found a back-edge, return.
504 if (RPO[Succ->getNumber()] <= BN)
505 return;
506 }
507
508 // Collect the set of blocks that need a stack frame to execute. Scan
509 // each block for uses/defs of callee-saved registers, calls, etc.
511 BitVector CSR(Hexagon::NUM_TARGET_REGS);
512 for (const MCPhysReg *P = HRI.getCalleeSavedRegs(&MF); *P; ++P)
513 for (MCPhysReg S : HRI.subregs_inclusive(*P))
514 CSR[S] = true;
515
516 for (auto &I : MF)
517 if (needsStackFrame(I, CSR, HRI))
518 SFBlocks.push_back(&I);
519
520 LLVM_DEBUG({
521 dbgs() << "Blocks needing SF: {";
522 for (auto &B : SFBlocks)
523 dbgs() << " " << printMBBReference(*B);
524 dbgs() << " }\n";
525 });
526 // No frame needed?
527 if (SFBlocks.empty())
528 return;
529
530 // Pick a common dominator and a common post-dominator.
531 MachineBasicBlock *DomB = SFBlocks[0];
532 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
533 DomB = MDT.findNearestCommonDominator(DomB, SFBlocks[i]);
534 if (!DomB)
535 break;
536 }
537 MachineBasicBlock *PDomB = SFBlocks[0];
538 for (unsigned i = 1, n = SFBlocks.size(); i < n; ++i) {
539 PDomB = MPT.findNearestCommonDominator(PDomB, SFBlocks[i]);
540 if (!PDomB)
541 break;
542 }
543 LLVM_DEBUG({
544 dbgs() << "Computed dom block: ";
545 if (DomB)
546 dbgs() << printMBBReference(*DomB);
547 else
548 dbgs() << "<null>";
549 dbgs() << ", computed pdom block: ";
550 if (PDomB)
551 dbgs() << printMBBReference(*PDomB);
552 else
553 dbgs() << "<null>";
554 dbgs() << "\n";
555 });
556 if (!DomB || !PDomB)
557 return;
558
559 // Make sure that DomB dominates PDomB and PDomB post-dominates DomB.
560 if (!MDT.dominates(DomB, PDomB)) {
561 LLVM_DEBUG(dbgs() << "Dom block does not dominate pdom block\n");
562 return;
563 }
564 if (!MPT.dominates(PDomB, DomB)) {
565 LLVM_DEBUG(dbgs() << "PDom block does not post-dominate dom block\n");
566 return;
567 }
568
569 // Finally, everything seems right.
570 PrologB = DomB;
571 EpilogB = PDomB;
572}
573
574/// Perform most of the PEI work here:
575/// - saving/restoring of the callee-saved registers,
576/// - stack frame creation and destruction.
577/// Normally, this work is distributed among various functions, but doing it
578/// in one place allows shrink-wrapping of the stack frame.
580 MachineBasicBlock &MBB) const {
581 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
582
583 MachineFrameInfo &MFI = MF.getFrameInfo();
584 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
585
586 MachineBasicBlock *PrologB = &MF.front(), *EpilogB = nullptr;
587 if (MF.getSubtarget<HexagonSubtarget>().getCLOpts().shrink_frame)
588 findShrunkPrologEpilog(MF, PrologB, EpilogB);
589
590 bool PrologueStubs = false;
592 insertCSRSpillsInBlock(*PrologB, CSI, HRI, PrologueStubs);
593 // Insert PS_aligna after all CSR spills.
594 // PS_aligna initializes the AP register with an aligned
595 // value derived from FP. Since AP is a callee-saved register, its original
596 // value must be saved before it is overwritten, and it must be defined
597 // before any AP-relative stack accesses.
598 insertAlignaInBlock(*PrologB, AfterCSR);
599 insertPrologueInBlock(*PrologB, PrologueStubs);
600 // Insert the SCS prologue after all FrameSetup instructions so that it
601 // follows allocframe and any CSR spills in the instruction stream. The
602 // packetizer may still fuse the SCS store with the first call in the
603 // function, but because Hexagon packets use old-value reads the original
604 // R31 is always what is stored.
605 {
606 MachineBasicBlock::iterator AfterProlog = PrologB->begin();
607 while (AfterProlog != PrologB->end() &&
608 AfterProlog->getFlag(MachineInstr::FrameSetup))
609 ++AfterProlog;
610 DebugLoc PrologDL = PrologB->findDebugLoc(AfterProlog);
611 emitSCSPrologue(MF, *PrologB, AfterProlog, PrologDL);
612 }
613 updateEntryPaths(MF, *PrologB);
614
615 if (EpilogB) {
616 insertCSRRestoresInBlock(*EpilogB, CSI, HRI);
617 insertEpilogueInBlock(*EpilogB);
618 } else {
619 for (auto &B : MF)
620 if (B.isReturnBlock())
621 insertCSRRestoresInBlock(B, CSI, HRI);
622
623 for (auto &B : MF)
624 if (B.isReturnBlock())
625 insertEpilogueInBlock(B);
626
627 for (auto &B : MF) {
628 if (B.empty())
629 continue;
630 MachineInstr *RetI = getReturn(B);
631 if (!RetI || isRestoreCall(RetI->getOpcode()))
632 continue;
633 for (auto &R : CSI)
634 RetI->addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
635 }
636 }
637
638 if (EpilogB) {
639 // If there is an epilog block, it may not have a return instruction.
640 // In such case, we need to add the callee-saved registers as live-ins
641 // in all blocks on all paths from the epilog to any return block.
642 unsigned MaxBN = MF.getNumBlockIDs();
643 BitVector DoneT(MaxBN+1), DoneF(MaxBN+1), Path(MaxBN+1);
644 updateExitPaths(*EpilogB, *EpilogB, DoneT, DoneF, Path);
645 }
646}
647
648/// Returns true if the target can safely skip saving callee-saved registers
649/// for noreturn nounwind functions.
651 const MachineFunction &MF) const {
652 const auto &F = MF.getFunction();
653 assert(F.hasFnAttribute(Attribute::NoReturn) &&
654 F.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
655 !F.getFunction().hasFnAttribute(Attribute::UWTable));
656 (void)F;
657
658 // No need to save callee saved registers if the function does not return.
659 return MF.getSubtarget<HexagonSubtarget>().noreturnStackElim();
660}
661
662// Helper function used to determine when to eliminate the stack frame for
663// functions marked as noreturn and when the noreturn-stack-elim options are
664// specified. When both these conditions are true, then a FP may not be needed
665// if the function makes a call. It is very similar to enableCalleeSaveSkip,
666// but it used to check if the allocframe can be eliminated as well.
667static bool enableAllocFrameElim(const MachineFunction &MF) {
668 const auto &F = MF.getFunction();
669 const auto &MFI = MF.getFrameInfo();
670 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
671 assert(!MFI.hasVarSizedObjects() &&
672 !HST.getRegisterInfo()->hasStackRealignment(MF));
673 return F.hasFnAttribute(Attribute::NoReturn) &&
674 F.hasFnAttribute(Attribute::NoUnwind) &&
675 !F.hasFnAttribute(Attribute::UWTable) && HST.noreturnStackElim() &&
676 MFI.getStackSize() == 0;
677}
678
679void HexagonFrameLowering::insertPrologueInBlock(MachineBasicBlock &MBB,
680 bool PrologueStubs) const {
682 MachineFrameInfo &MFI = MF.getFrameInfo();
683 auto &HST = MF.getSubtarget<HexagonSubtarget>();
684 auto &HII = *HST.getInstrInfo();
685 auto &HRI = *HST.getRegisterInfo();
686 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
687
688 Align MaxAlign = std::max(getMaxStackAlign(MF), getStackAlign());
689 uint64_t VTCMFrameSize = HMFI.getVTCMFrameInfo().getStackSize();
690
691 // Calculate the total stack frame size.
692 // Get the number of bytes to allocate from the FrameInfo.
693 unsigned FrameSize = MFI.getStackSize();
694 // Round up the max call frame size to the max alignment on the stack.
695 unsigned MaxCFA = alignTo(MFI.getMaxCallFrameSize(), MaxAlign);
696 MFI.setMaxCallFrameSize(MaxCFA);
697
698 FrameSize = MaxCFA + alignTo(FrameSize, MaxAlign);
699 MFI.setStackSize(FrameSize);
700
701 bool AlignStack = (MaxAlign > getStackAlign());
702
703 // Get the number of bytes to allocate from the FrameInfo.
704 unsigned NumBytes = MFI.getStackSize();
705 Register SP = HRI.getStackRegister();
706 unsigned MaxCF = MFI.getMaxCallFrameSize();
708
709 SmallVector<MachineInstr *, 4> AdjustRegs;
710 for (auto &MBB : MF)
711 for (auto &MI : MBB)
712 if (MI.getOpcode() == Hexagon::PS_alloca)
713 AdjustRegs.push_back(&MI);
714
715 for (auto *MI : AdjustRegs) {
716 assert((MI->getOpcode() == Hexagon::PS_alloca) && "Expected alloca");
717 expandAlloca(MI, MF, HII, SP, MaxCF);
718 MI->eraseFromParent();
719 }
720
722
723 if (MF.getFunction().isVarArg() &&
724 MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl()) {
725 // Calculate the size of register saved area.
726 int NumVarArgRegs = 6 - FirstVarArgSavedReg;
727 int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0)
728 ? NumVarArgRegs * 4
729 : NumVarArgRegs * 4 + 4;
730 if (RegisterSavedAreaSizePlusPadding > 0) {
731 // Decrement the stack pointer by size of register saved area plus
732 // padding if any.
733 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
734 .addReg(SP)
735 .addImm(-RegisterSavedAreaSizePlusPadding)
737
738 int NumBytes = 0;
739 // Copy all the named arguments below register saved area.
740 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
741 for (int i = HMFI.getFirstNamedArgFrameIndex(),
742 e = HMFI.getLastNamedArgFrameIndex(); i >= e; --i) {
743 // HLX arguments are on the VTCM stack.
745 continue;
746 uint64_t ObjSize = MFI.getObjectSize(i);
747 Align ObjAlign = MFI.getObjectAlign(i);
748
749 // Determine the kind of load/store that should be used.
750 unsigned LDOpc, STOpc;
751 uint64_t OpcodeChecker = ObjAlign.value();
752
753 // Handle cases where alignment of an object is > its size.
754 if (ObjAlign > ObjSize) {
755 if (ObjSize <= 1)
756 OpcodeChecker = 1;
757 else if (ObjSize <= 2)
758 OpcodeChecker = 2;
759 else if (ObjSize <= 4)
760 OpcodeChecker = 4;
761 else if (ObjSize > 4)
762 OpcodeChecker = 8;
763 }
764
765 switch (OpcodeChecker) {
766 case 1:
767 LDOpc = Hexagon::L2_loadrb_io;
768 STOpc = Hexagon::S2_storerb_io;
769 break;
770 case 2:
771 LDOpc = Hexagon::L2_loadrh_io;
772 STOpc = Hexagon::S2_storerh_io;
773 break;
774 case 4:
775 LDOpc = Hexagon::L2_loadri_io;
776 STOpc = Hexagon::S2_storeri_io;
777 break;
778 case 8:
779 default:
780 LDOpc = Hexagon::L2_loadrd_io;
781 STOpc = Hexagon::S2_storerd_io;
782 break;
783 }
784
785 Register RegUsed = LDOpc == Hexagon::L2_loadrd_io ? Hexagon::D3
786 : Hexagon::R6;
787 int LoadStoreCount = ObjSize / OpcodeChecker;
788
789 if (ObjSize % OpcodeChecker)
790 ++LoadStoreCount;
791
792 // Get the start location of the load. NumBytes is basically the
793 // offset from the stack pointer of previous function, which would be
794 // the caller in this case, as this function has variable argument
795 // list.
796 if (NumBytes != 0)
797 NumBytes = alignTo(NumBytes, ObjAlign);
798
799 int Count = 0;
800 while (Count < LoadStoreCount) {
801 // Load the value of the named argument on stack.
802 BuildMI(MBB, InsertPt, dl, HII.get(LDOpc), RegUsed)
803 .addReg(SP)
804 .addImm(RegisterSavedAreaSizePlusPadding +
805 ObjAlign.value() * Count + NumBytes)
807
808 // Store it below the register saved area plus padding.
809 BuildMI(MBB, InsertPt, dl, HII.get(STOpc))
810 .addReg(SP)
811 .addImm(ObjAlign.value() * Count + NumBytes)
812 .addReg(RegUsed)
814
815 Count++;
816 }
817 NumBytes += MFI.getObjectSize(i);
818 }
819
820 // Make NumBytes 8 byte aligned
821 NumBytes = alignTo(NumBytes, 8);
822
823 // If the number of registers having variable arguments is odd,
824 // leave 4 bytes of padding to get to the location where first
825 // variable argument which was passed through register was copied.
826 NumBytes = (NumVarArgRegs % 2 == 0) ? NumBytes : NumBytes + 4;
827
828 for (int j = FirstVarArgSavedReg, i = 0; j < 6; ++j, ++i) {
829 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_storeri_io))
830 .addReg(SP)
831 .addImm(NumBytes + 4 * i)
832 .addReg(Hexagon::R0 + j)
834 }
835 }
836 }
837
838 if (hasFP(MF)) {
839 insertAllocframe(MBB, InsertPt, NumBytes);
840 if (AlignStack) {
841 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_andir), SP)
842 .addReg(SP)
843 .addImm(-int64_t(MaxAlign.value()));
844 }
845 // If the stack-checking is enabled, and we spilled the callee-saved
846 // registers inline (i.e. did not use a spill function), then call
847 // the stack checker directly.
848 if (HST.getCLOpts().stackovf_sanitizer && !PrologueStubs)
849 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_call_stk))
850 .addExternalSymbol("__runtime_stack_check");
851 } else if (NumBytes > 0) {
852 assert(alignTo(NumBytes, 8) == NumBytes);
853 auto *TLI = HST.getTargetLowering();
854 bool NeedsProbing = TLI->hasInlineStackProbe(MF);
855 unsigned ProbeSize = 0;
856 if (NeedsProbing) {
857 Align StackAlign = getStackAlign();
858 ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
859 }
860 if (NeedsProbing && NumBytes > ProbeSize) {
861 // Compute target SP in R28 (caller-saved scratch).
862 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), Hexagon::R28)
863 .addReg(SP)
864 .addImm(-int(NumBytes))
866 // Emit pseudo to be expanded by inlineStackProbe().
867 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_probed_stackalloc))
868 .addReg(Hexagon::R28)
870 } else {
871 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
872 .addReg(SP)
873 .addImm(-int(NumBytes))
875 }
876 }
877 if (!VTCMFrameSize)
878 return;
879 if (int VSPFI = HMFI.getVSPFrameIndex(); VSPFI >= 0) {
880 // Save the caller's VSP before allocating the vector frame. R7 is not
881 // an argument register, and the prologue is in the entry block (see
882 // findShrunkPrologEpilog).
883 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_tfrcrr), Hexagon::R7)
884 .addReg(Hexagon::VSP)
886 HII.storeRegToStackSlot(MBB, InsertPt, Hexagon::R7, /*isKill=*/true, VSPFI,
887 &Hexagon::IntRegsRegClass, Register());
888 std::prev(InsertPt)->setFlag(MachineInstr::FrameSetup);
889 }
890 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::V2_vallocframe_imm))
891 .addImm(VTCMFrameSize / 2048)
893}
894
895void HexagonFrameLowering::insertEpilogueInBlock(MachineBasicBlock &MBB) const {
897 auto &HST = MF.getSubtarget<HexagonSubtarget>();
898 auto &HII = *HST.getInstrInfo();
899 auto &HRI = *HST.getRegisterInfo();
900 Register SP = HRI.getStackRegister();
901
904
905 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
906 uint64_t VTCMFrameSize = HMFI.getVTCMFrameInfo().getStackSize();
907 if (VTCMFrameSize)
908 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::V2_vdeallocframe_imm))
909 .addImm(VTCMFrameSize / 2048);
910
911 if (!hasFP(MF)) {
912 MachineFrameInfo &MFI = MF.getFrameInfo();
913 unsigned NumBytes = MFI.getStackSize();
914 if (MF.getFunction().isVarArg() &&
915 MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl()) {
916 // On Hexagon Linux, deallocate the stack for the register saved area.
917 int NumVarArgRegs = 6 - FirstVarArgSavedReg;
918 int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0) ?
919 (NumVarArgRegs * 4) : (NumVarArgRegs * 4 + 4);
920 NumBytes += RegisterSavedAreaSizePlusPadding;
921 }
922 if (NumBytes) {
923 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
924 .addReg(SP)
925 .addImm(NumBytes);
926 }
927 return;
928 }
929
930 MachineInstr *RetI = getReturn(MBB);
931 unsigned RetOpc = RetI ? RetI->getOpcode() : 0;
932
933 // Handle EH_RETURN.
934 if (RetOpc == Hexagon::EH_RETURN_JMPR) {
935 // EH paths overwrite R31 with a handler address; the shadow stack is
936 // not read on this path, so no SCS epilogue is needed.
937 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
938 .addDef(Hexagon::D15)
939 .addReg(Hexagon::R30);
940 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_add), SP)
941 .addReg(SP)
942 .addReg(Hexagon::R28);
943 return;
944 }
945
946 // Check for RESTORE_DEALLOC_RET* tail call. Don't emit an extra dealloc-
947 // frame instruction if we encounter it.
948 // These are restore stubs, which useRestoreFunction() never selects when SCS
949 // is active (they do deallocframe+jumpr, bypassing the SCS epilogue), so no
950 // SCS epilogue is needed here.
951 if (RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4 ||
952 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC ||
953 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT ||
954 RetOpc == Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC) {
956 ++It;
957 // Delete all instructions after the RESTORE (except labels).
958 while (It != MBB.end()) {
959 if (!It->isLabel())
960 It = MBB.erase(It);
961 else
962 ++It;
963 }
964 return;
965 }
966
967 // It is possible that the restoring code is a call to a library function.
968 // All of the restore* functions include "deallocframe", so we need to make
969 // sure that we don't add an extra one.
970 bool NeedsSCS = MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack);
971 bool NeedsDeallocframe = true;
972 unsigned PrevOpc = 0;
973 if (!MBB.empty() && InsertPt != MBB.begin()) {
974 MachineBasicBlock::iterator PrevIt = std::prev(InsertPt);
975 PrevOpc = PrevIt->getOpcode();
976 if (PrevOpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
977 PrevOpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC ||
978 PrevOpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
979 PrevOpc == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
980 PrevOpc == Hexagon::PS_call_nr || PrevOpc == Hexagon::PS_callr_nr)
981 NeedsDeallocframe = false;
982 }
983
984 if (!MF.getSubtarget<HexagonSubtarget>().isEnvironmentMusl() ||
985 !MF.getFunction().isVarArg()) {
986 if (!NeedsDeallocframe) {
987 // RESTORE_DEALLOC_BEFORE_TAILCALL is a restore stub, which
988 // useRestoreFunction() never selects when SCS is active.
989 // PS_call_nr/PS_callr_nr are noreturn calls so the shadow stack entry
990 // is never read - no SCS epilogue is needed on either path.
991 if (NeedsSCS && PrevOpc != Hexagon::PS_call_nr &&
992 PrevOpc != Hexagon::PS_callr_nr)
993 report_fatal_error("SCS with RESTORE_DEALLOC stub: "
994 "useRestoreFunction() should have prevented this");
995 return;
996 }
997 // If the returning instruction is PS_jmpret, replace it with
998 // dealloc_return, otherwise just add deallocframe. The function
999 // could be returning via a tail call.
1000 if (RetOpc != Hexagon::PS_jmpret || !HST.getCLOpts().dealloc_ret ||
1001 NeedsSCS) {
1002 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
1003 .addDef(Hexagon::D15)
1004 .addReg(Hexagon::R30);
1005 // When shadow call stack is active, overwrite R31 restored by
1006 // deallocframe with the shadow-stack copy, then retract the pointer.
1007 if (NeedsSCS)
1008 emitSCSEpilogue(MF, MBB, InsertPt, dl);
1009 return;
1010 }
1011 unsigned NewOpc = Hexagon::L4_return;
1012 MachineInstrBuilder NewI = BuildMI(MBB, RetI, dl, HII.get(NewOpc))
1013 .addDef(Hexagon::D15)
1014 .addReg(Hexagon::R30);
1015 // Avoid duplicating the pc implicit-def.
1016 for (const MachineOperand &MO : drop_begin(RetI->implicit_operands()))
1017 NewI.add(MO);
1018 MBB.erase(RetI);
1019 } else {
1020 // L2_deallocframe instruction after it.
1021 // Calculate the size of register saved area.
1022 int NumVarArgRegs = 6 - FirstVarArgSavedReg;
1023 int RegisterSavedAreaSizePlusPadding = (NumVarArgRegs % 2 == 0) ?
1024 (NumVarArgRegs * 4) : (NumVarArgRegs * 4 + 4);
1025
1028 : std::prev(Term);
1029 bool HasRestoreStub =
1030 I != MBB.end() &&
1031 (I->getOpcode() == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT ||
1032 I->getOpcode() ==
1033 Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC ||
1034 I->getOpcode() == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4 ||
1035 I->getOpcode() == Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC);
1036 if (!HasRestoreStub)
1037 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::L2_deallocframe))
1038 .addDef(Hexagon::D15)
1039 .addReg(Hexagon::R30);
1040 if (RegisterSavedAreaSizePlusPadding != 0)
1041 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
1042 .addReg(SP)
1043 .addImm(RegisterSavedAreaSizePlusPadding);
1044 // RESTORE_DEALLOC stubs are never selected when SCS is active (see
1045 // useRestoreFunction()), so only emit the SCS epilogue when we emitted
1046 // our own deallocframe above.
1047 if (NeedsSCS && !HasRestoreStub)
1048 emitSCSEpilogue(MF, MBB, InsertPt, dl);
1049 }
1050}
1051
1052void HexagonFrameLowering::insertAllocframe(MachineBasicBlock &MBB,
1053 MachineBasicBlock::iterator InsertPt, unsigned NumBytes) const {
1054 MachineFunction &MF = *MBB.getParent();
1055 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1056 auto &HII = *HST.getInstrInfo();
1057 auto &HRI = *HST.getRegisterInfo();
1058
1059 // Check for overflow.
1060 // Hexagon_TODO: Ugh! hardcoding. Is there an API that can be used?
1061 const unsigned int ALLOCFRAME_MAX = 16384;
1062
1063 // Create a dummy memory operand to avoid allocframe from being treated as
1064 // a volatile memory reference.
1067
1069 Register SP = HRI.getStackRegister();
1070
1071 auto *TLI = HST.getTargetLowering();
1072 bool NeedsProbing = TLI->hasInlineStackProbe(MF) && NumBytes > 0;
1073 unsigned ProbeSize = 0;
1074 if (NeedsProbing) {
1075 Align StackAlign = getStackAlign();
1076 ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
1077 }
1078
1079 if (NeedsProbing && NumBytes > ProbeSize) {
1080 // Emit allocframe(#0) to save FP/LR only.
1081 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
1082 .addDef(SP)
1083 .addReg(SP)
1084 .addImm(0)
1085 .addMemOperand(MMO)
1087
1088 // Compute target SP in R28 (caller-saved scratch).
1089 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), Hexagon::R28)
1090 .addReg(SP)
1091 .addImm(-int(NumBytes))
1093
1094 // Emit pseudo to be expanded by inlineStackProbe().
1095 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::PS_probed_stackalloc))
1096 .addReg(Hexagon::R28)
1098 } else if (NumBytes >= ALLOCFRAME_MAX) {
1099 // Emit allocframe(#0).
1100 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
1101 .addDef(SP)
1102 .addReg(SP)
1103 .addImm(0)
1104 .addMemOperand(MMO)
1106
1107 // Subtract the size from the stack pointer.
1108 Register SP = HRI.getStackRegister();
1109 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::A2_addi), SP)
1110 .addReg(SP)
1111 .addImm(-int(NumBytes))
1113 } else {
1114 BuildMI(MBB, InsertPt, dl, HII.get(Hexagon::S2_allocframe))
1115 .addDef(SP)
1116 .addReg(SP)
1117 .addImm(NumBytes)
1118 .addMemOperand(MMO)
1120 }
1121}
1122
1124 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1125 // Collect PS_probed_stackalloc pseudos to expand. Collecting first avoids
1126 // issues with modifying the block while iterating.
1128 for (MachineInstr &MI : PrologueMBB)
1129 if (MI.getOpcode() == Hexagon::PS_probed_stackalloc)
1130 ToReplace.push_back(&MI);
1131
1132 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1133 auto &HII = *HST.getInstrInfo();
1134 auto *TLI = HST.getTargetLowering();
1135 Align StackAlign = getStackAlign();
1136 unsigned ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
1138
1139 for (MachineInstr *MI : ToReplace) {
1140 MachineBasicBlock::iterator MBBI = MI->getIterator();
1141 DebugLoc DL = PrologueMBB.findDebugLoc(MBBI);
1142 Register TargetReg = MI->getOperand(0).getReg();
1143
1144 // Split the block: everything after the pseudo goes into ExitMBB.
1145 MachineBasicBlock *MBB = MI->getParent();
1146 MachineFunction::iterator InsertPt = std::next(MBB->getIterator());
1147 MachineBasicBlock *LoopMBB =
1148 MF.CreateMachineBasicBlock(MBB->getBasicBlock());
1149 MF.insert(InsertPt, LoopMBB);
1150 MachineBasicBlock *ExitMBB =
1151 MF.CreateMachineBasicBlock(MBB->getBasicBlock());
1152 MF.insert(InsertPt, ExitMBB);
1153
1154 // Move everything after the pseudo into ExitMBB.
1155 ExitMBB->splice(ExitMBB->end(), MBB, std::next(MBBI), MBB->end());
1157
1158 // LoopMBB: probe each page by decrementing SP and storing zero.
1159 // When NumBytes is not an exact multiple of ProbeSize the loop
1160 // will overshoot by up to ProbeSize-1 bytes; the final r29 = r28
1161 // in ExitMBB corrects SP to the true target.
1162 //
1163 // The store is placed before the compare+branch so that the
1164 // packetizer can bundle them into a single VLIW packet. All
1165 // non-predicated instructions in a packet commit unconditionally,
1166 // so the probe store executes on every iteration including the
1167 // last (when the branch falls through).
1168 //
1169 // r29 = add(r29, #-ProbeSize)
1170 // memw(r29+#0) = #0
1171 // p0 = cmp.gtu(r29, r28)
1172 // if (p0) jump LoopMBB
1173 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::A2_addi),
1174 Hexagon::R29)
1175 .addReg(Hexagon::R29)
1176 .addImm(-int(ProbeSize))
1177 .setMIFlags(Flags);
1178
1179 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::S4_storeiri_io))
1180 .addReg(Hexagon::R29)
1181 .addImm(0)
1182 .addImm(0)
1183 .setMIFlags(Flags);
1184
1185 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::C2_cmpgtu),
1186 Hexagon::P0)
1187 .addReg(Hexagon::R29)
1188 .addReg(TargetReg)
1189 .setMIFlags(Flags);
1190
1191 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::J2_jumpt))
1192 .addReg(Hexagon::P0)
1193 .addMBB(LoopMBB)
1194 .setMIFlags(Flags);
1195
1196 // ExitMBB: set final SP.
1197 BuildMI(*ExitMBB, ExitMBB->begin(), DL, HII.get(Hexagon::A2_tfr),
1198 Hexagon::R29)
1199 .addReg(TargetReg)
1200 .setMIFlags(Flags);
1201
1202 // Set up CFG edges.
1203 MBB->addSuccessor(LoopMBB);
1204 LoopMBB->addSuccessor(LoopMBB);
1205 LoopMBB->addSuccessor(ExitMBB);
1206
1207 // Remove the pseudo.
1208 MI->eraseFromParent();
1209
1210 // Recompute live-ins for the new blocks.
1211 fullyRecomputeLiveIns({ExitMBB, LoopMBB});
1212 }
1213}
1214
1215void HexagonFrameLowering::insertAlignaInBlock(
1217 MachineFunction &MF = *MBB.getParent();
1218 Register AP =
1219 MF.getInfo<HexagonMachineFunctionInfo>()->getStackAlignBaseReg();
1220 if (!AP.isValid())
1221 return;
1222
1223 assert(needsAligna(MF) && "Unexpected stack align base register");
1224
1225 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
1226 Align MaxAlign = std::max(MF.getFrameInfo().getMaxAlign(), getStackAlign());
1227 DebugLoc DL = MBB.findDebugLoc(InsertPt);
1228 BuildMI(MBB, InsertPt, DL, HII.get(Hexagon::PS_aligna), AP)
1229 .addImm(MaxAlign.value());
1230}
1231
1232void HexagonFrameLowering::updateEntryPaths(MachineFunction &MF,
1233 MachineBasicBlock &SaveB) const {
1234 SetVector<unsigned> Worklist;
1235
1236 MachineBasicBlock &EntryB = MF.front();
1237 Worklist.insert(EntryB.getNumber());
1238
1239 unsigned SaveN = SaveB.getNumber();
1240 auto &CSI = MF.getFrameInfo().getCalleeSavedInfo();
1241
1242 for (unsigned i = 0; i < Worklist.size(); ++i) {
1243 unsigned BN = Worklist[i];
1245 for (auto &R : CSI)
1246 if (!MBB.isLiveIn(R.getReg()))
1247 MBB.addLiveIn(R.getReg());
1248 if (BN != SaveN)
1249 for (auto &SB : MBB.successors())
1250 Worklist.insert(SB->getNumber());
1251 }
1252}
1253
1254bool HexagonFrameLowering::updateExitPaths(MachineBasicBlock &MBB,
1255 MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF,
1256 BitVector &Path) const {
1257 assert(MBB.getNumber() >= 0);
1258 unsigned BN = MBB.getNumber();
1259 if (Path[BN] || DoneF[BN])
1260 return false;
1261 if (DoneT[BN])
1262 return true;
1263
1264 auto &CSI = MBB.getParent()->getFrameInfo().getCalleeSavedInfo();
1265
1266 Path[BN] = true;
1267 bool ReachedExit = false;
1268 for (auto &SB : MBB.successors())
1269 ReachedExit |= updateExitPaths(*SB, RestoreB, DoneT, DoneF, Path);
1270
1271 if (!MBB.empty() && MBB.back().isReturn()) {
1272 // Add implicit uses of all callee-saved registers to the reached
1273 // return instructions. This is to prevent the anti-dependency breaker
1274 // from renaming these registers.
1275 MachineInstr &RetI = MBB.back();
1276 if (!isRestoreCall(RetI.getOpcode()))
1277 for (auto &R : CSI)
1278 RetI.addOperand(MachineOperand::CreateReg(R.getReg(), false, true));
1279 ReachedExit = true;
1280 }
1281
1282 // We don't want to add unnecessary live-ins to the restore block: since
1283 // the callee-saved registers are being defined in it, the entry of the
1284 // restore block cannot be on the path from the definitions to any exit.
1285 if (ReachedExit && &MBB != &RestoreB) {
1286 for (auto &R : CSI)
1287 if (!MBB.isLiveIn(R.getReg()))
1288 MBB.addLiveIn(R.getReg());
1289 DoneT[BN] = true;
1290 }
1291 if (!ReachedExit)
1292 DoneF[BN] = true;
1293
1294 Path[BN] = false;
1295 return ReachedExit;
1296}
1297
1298static std::optional<MachineBasicBlock::iterator>
1300 // The CFI instructions need to be inserted right after allocframe.
1301 // An exception to this is a situation where allocframe is bundled
1302 // with a call: then the CFI instructions need to be inserted before
1303 // the packet with the allocframe+call (in case the call throws an
1304 // exception).
1305 auto End = B.instr_end();
1306
1307 for (MachineInstr &I : B) {
1308 MachineBasicBlock::iterator It = I.getIterator();
1309 if (!I.isBundle()) {
1310 if (I.getOpcode() == Hexagon::S2_allocframe)
1311 return std::next(It);
1312 continue;
1313 }
1314 // I is a bundle.
1315 bool HasCall = false, HasAllocFrame = false;
1316 auto T = It.getInstrIterator();
1317 while (++T != End && T->isBundled()) {
1318 if (T->getOpcode() == Hexagon::S2_allocframe)
1319 HasAllocFrame = true;
1320 else if (T->isCall())
1321 HasCall = true;
1322 }
1323 if (HasAllocFrame)
1324 return HasCall ? It : std::next(It);
1325 }
1326 return std::nullopt;
1327}
1328
1330 for (auto &B : MF)
1331 if (auto At = findCFILocation(B))
1332 insertCFIInstructionsAt(B, *At);
1333}
1334
1335void HexagonFrameLowering::insertCFIInstructionsAt(MachineBasicBlock &MBB,
1336 MachineBasicBlock::iterator At) const {
1337 MachineFunction &MF = *MBB.getParent();
1338 MachineFrameInfo &MFI = MF.getFrameInfo();
1339 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1340 auto &HII = *HST.getInstrInfo();
1341 auto &HRI = *HST.getRegisterInfo();
1342
1343 // If CFI instructions have debug information attached, something goes
1344 // wrong with the final assembly generation: the prolog_end is placed
1345 // in a wrong location.
1346 DebugLoc DL;
1347 const MCInstrDesc &CFID = HII.get(TargetOpcode::CFI_INSTRUCTION);
1348
1349 MCSymbol *FrameLabel = MF.getContext().createTempSymbol();
1350 bool HasFP = hasFP(MF);
1351
1352 if (HasFP) {
1353 unsigned DwFPReg = HRI.getDwarfRegNum(HRI.getFrameRegister(), true);
1354 unsigned DwRAReg = HRI.getDwarfRegNum(HRI.getRARegister(), true);
1355
1356 // Define CFA via an offset from the value of FP.
1357 //
1358 // -8 -4 0 (SP)
1359 // --+----+----+---------------------
1360 // | FP | LR | increasing addresses -->
1361 // --+----+----+---------------------
1362 // | +-- Old SP (before allocframe)
1363 // +-- New FP (after allocframe)
1364 //
1365 // MCCFIInstruction::cfiDefCfa adds the offset from the register.
1366 // MCCFIInstruction::createOffset takes the offset without sign change.
1367 auto DefCfa = MCCFIInstruction::cfiDefCfa(FrameLabel, DwFPReg, 8);
1368 BuildMI(MBB, At, DL, CFID)
1369 .addCFIIndex(MF.addFrameInst(DefCfa));
1370 // R31 (return addr) = CFA - 4
1371 auto OffR31 = MCCFIInstruction::createOffset(FrameLabel, DwRAReg, -4);
1372 BuildMI(MBB, At, DL, CFID)
1373 .addCFIIndex(MF.addFrameInst(OffR31));
1374 // R30 (frame ptr) = CFA - 8
1375 auto OffR30 = MCCFIInstruction::createOffset(FrameLabel, DwFPReg, -8);
1376 BuildMI(MBB, At, DL, CFID)
1377 .addCFIIndex(MF.addFrameInst(OffR30));
1378 }
1379
1380 static const MCPhysReg RegsToMove[] = {
1381 Hexagon::R1, Hexagon::R0, Hexagon::R3, Hexagon::R2,
1382 Hexagon::R17, Hexagon::R16, Hexagon::R19, Hexagon::R18,
1383 Hexagon::R21, Hexagon::R20, Hexagon::R23, Hexagon::R22,
1384 Hexagon::R25, Hexagon::R24, Hexagon::R27, Hexagon::R26,
1385 Hexagon::D0, Hexagon::D1, Hexagon::D8, Hexagon::D9,
1386 Hexagon::D10, Hexagon::D11, Hexagon::D12, Hexagon::D13
1387 };
1388
1389 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
1390
1391 for (MCPhysReg Reg : RegsToMove) {
1392 auto IfR = [Reg] (const CalleeSavedInfo &C) -> bool {
1393 return C.getReg() == Reg;
1394 };
1395 auto F = find_if(CSI, IfR);
1396 if (F == CSI.end())
1397 continue;
1398
1399 int64_t Offset;
1400 if (HasFP) {
1401 // If the function has a frame pointer (i.e. has an allocframe),
1402 // then the CFA has been defined in terms of FP. Any offsets in
1403 // the following CFI instructions have to be defined relative
1404 // to FP, which points to the bottom of the stack frame.
1405 // The function getFrameIndexReference can still choose to use SP
1406 // for the offset calculation, so we cannot simply call it here.
1407 // Instead, get the offset (relative to the FP) directly.
1408 Offset = MFI.getObjectOffset(F->getFrameIdx());
1409 } else {
1410 Register FrameReg;
1411 Offset =
1412 getFrameIndexReference(MF, F->getFrameIdx(), FrameReg).getFixed();
1413 }
1414 // Subtract 8 to make room for R30 and R31, which are added above.
1415 Offset -= 8;
1416
1417 if (Reg < Hexagon::D0 || Reg > Hexagon::D15) {
1418 unsigned DwarfReg = HRI.getDwarfRegNum(Reg, true);
1419 auto OffReg = MCCFIInstruction::createOffset(FrameLabel, DwarfReg,
1420 Offset);
1421 BuildMI(MBB, At, DL, CFID)
1422 .addCFIIndex(MF.addFrameInst(OffReg));
1423 } else {
1424 // Split the double regs into subregs, and generate appropriate
1425 // cfi_offsets.
1426 // The only reason, we are split double regs is, llvm-mc does not
1427 // understand paired registers for cfi_offset.
1428 // Eg .cfi_offset r1:0, -64
1429
1430 Register HiReg = HRI.getSubReg(Reg, Hexagon::isub_hi);
1431 Register LoReg = HRI.getSubReg(Reg, Hexagon::isub_lo);
1432 unsigned HiDwarfReg = HRI.getDwarfRegNum(HiReg, true);
1433 unsigned LoDwarfReg = HRI.getDwarfRegNum(LoReg, true);
1434 auto OffHi = MCCFIInstruction::createOffset(FrameLabel, HiDwarfReg,
1435 Offset+4);
1436 BuildMI(MBB, At, DL, CFID)
1437 .addCFIIndex(MF.addFrameInst(OffHi));
1438 auto OffLo = MCCFIInstruction::createOffset(FrameLabel, LoDwarfReg,
1439 Offset);
1440 BuildMI(MBB, At, DL, CFID)
1441 .addCFIIndex(MF.addFrameInst(OffLo));
1442 }
1443 }
1444
1445 // HLX callee-saved registers are spilled to the VTCM stack, which is
1446 // addressed by VSP, not by the CFA. Describe them as
1447 // DW_CFA_expression <reg>, DW_OP_bregx <vsp>, <offset>
1448 // where the offset is relative to the VSP after vallocframe, which stays
1449 // the same in the function body. Preserved registers that are not spilled
1450 // keep their value.
1451 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1452 unsigned DwVSPReg = HRI.getDwarfRegNum(Hexagon::VSP, true);
1453 int64_t VTCMFrameSize = HMFI.getVTCMFrameInfo().getStackSize();
1454 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R) {
1455 if (!Hexagon::HlxLRRegClass.contains(*R))
1456 continue;
1457 unsigned DwarfReg = HRI.getDwarfRegNum(*R, true);
1458 auto F = find_if(
1459 CSI, [R](const CalleeSavedInfo &C) { return C.getReg() == *R; });
1460 if (F == CSI.end()) {
1461 auto Same = MCCFIInstruction::createSameValue(FrameLabel, DwarfReg);
1462 BuildMI(MBB, At, DL, CFID).addCFIIndex(MF.addFrameInst(Same));
1463 continue;
1464 }
1465 assert(HMFI.isVTCMStackIndex(F->getFrameIdx()) &&
1466 "HLX register not spilled to the VTCM stack");
1467 int64_t Offset =
1468 VTCMFrameSize + HMFI.getMappedVTCMObjectOffset(F->getFrameIdx());
1469 uint8_t Buf[16];
1470 SmallString<16> Expr, Vals;
1471 Expr.push_back(dwarf::DW_OP_bregx);
1472 Expr.append(Buf, Buf + encodeULEB128(DwVSPReg, Buf));
1473 Expr.append(Buf, Buf + encodeSLEB128(Offset, Buf));
1474 Vals.push_back(dwarf::DW_CFA_expression);
1475 Vals.append(Buf, Buf + encodeULEB128(DwarfReg, Buf));
1476 Vals.append(Buf, Buf + encodeULEB128(Expr.size(), Buf));
1477 Vals.append(Expr);
1478 std::string Comment =
1479 (Twine(HRI.getRegAsmName(*R)) + " at vsp + " + Twine(Offset)).str();
1480 auto Esc =
1481 MCCFIInstruction::createEscape(FrameLabel, Vals, SMLoc(), Comment);
1482 BuildMI(MBB, At, DL, CFID).addCFIIndex(MF.addFrameInst(Esc));
1483 }
1484
1485 // The caller's VSP, saved by insertPrologueInBlock.
1486 if (int VSPFI = HMFI.getVSPFrameIndex(); VSPFI >= 0) {
1487 assert(HasFP && "A VTCM frame requires a frame pointer");
1488 auto OffVSP = MCCFIInstruction::createOffset(
1489 FrameLabel, DwVSPReg, MFI.getObjectOffset(VSPFI) - 8);
1490 BuildMI(MBB, At, DL, CFID).addCFIIndex(MF.addFrameInst(OffVSP));
1491 }
1492}
1493
1495 const auto &CLOpts = MF.getSubtarget<HexagonSubtarget>().getCLOpts();
1496 auto &MFI = MF.getFrameInfo();
1497 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1498 bool HasExtraAlign = HRI.hasStackRealignment(MF);
1499 bool HasAlloca = MFI.hasVarSizedObjects();
1500
1501 // Insert ALLOCFRAME if we need to or at -O0 for the debugger. Think
1502 // that this shouldn't be required, but doing so now because gcc does and
1503 // gdb can't break at the start of the function without it. Will remove if
1504 // this turns out to be a gdb bug.
1505 //
1507 return true;
1508
1509 // By default we want to use SP (since it's always there). FP requires
1510 // some setup (i.e. ALLOCFRAME).
1511 // Both, alloca and stack alignment modify the stack pointer by an
1512 // undetermined value, so we need to save it at the entry to the function
1513 // (i.e. use allocframe).
1514 if (HasAlloca || HasExtraAlign)
1515 return true;
1516
1517 // If FP-elimination is disabled, we have to use FP. This must not be
1518 // gated on stack size: the user/ABI-requested frame pointer is needed
1519 // regardless of whether the function currently has a stack frame.
1520 // Every other target checks DisableFramePointerElim unconditionally.
1521 if (MF.disableFramePointerElim() || !CLOpts.fp_elim)
1522 return true;
1523
1524 if (MFI.getStackSize() > 0) {
1525 if (CLOpts.stackovf_sanitizer)
1526 return true;
1527 }
1528
1529 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1530 if (HMFI.getVTCMFrameInfo().getStackSize())
1531 return true;
1532 if ((MFI.hasCalls() && !enableAllocFrameElim(MF)) || HMFI.hasClobberLR())
1533 return true;
1534
1535 return false;
1536}
1537
1543
1544static const char *getSpillFunctionFor(Register MaxReg, SpillKind SpillType,
1545 bool Stkchk = false) {
1546 const char * V4SpillToMemoryFunctions[] = {
1547 "__save_r16_through_r17",
1548 "__save_r16_through_r19",
1549 "__save_r16_through_r21",
1550 "__save_r16_through_r23",
1551 "__save_r16_through_r25",
1552 "__save_r16_through_r27" };
1553
1554 const char * V4SpillToMemoryStkchkFunctions[] = {
1555 "__save_r16_through_r17_stkchk",
1556 "__save_r16_through_r19_stkchk",
1557 "__save_r16_through_r21_stkchk",
1558 "__save_r16_through_r23_stkchk",
1559 "__save_r16_through_r25_stkchk",
1560 "__save_r16_through_r27_stkchk" };
1561
1562 const char * V4SpillFromMemoryFunctions[] = {
1563 "__restore_r16_through_r17_and_deallocframe",
1564 "__restore_r16_through_r19_and_deallocframe",
1565 "__restore_r16_through_r21_and_deallocframe",
1566 "__restore_r16_through_r23_and_deallocframe",
1567 "__restore_r16_through_r25_and_deallocframe",
1568 "__restore_r16_through_r27_and_deallocframe" };
1569
1570 const char * V4SpillFromMemoryTailcallFunctions[] = {
1571 "__restore_r16_through_r17_and_deallocframe_before_tailcall",
1572 "__restore_r16_through_r19_and_deallocframe_before_tailcall",
1573 "__restore_r16_through_r21_and_deallocframe_before_tailcall",
1574 "__restore_r16_through_r23_and_deallocframe_before_tailcall",
1575 "__restore_r16_through_r25_and_deallocframe_before_tailcall",
1576 "__restore_r16_through_r27_and_deallocframe_before_tailcall"
1577 };
1578
1579 const char **SpillFunc = nullptr;
1580
1581 switch(SpillType) {
1582 case SK_ToMem:
1583 SpillFunc = Stkchk ? V4SpillToMemoryStkchkFunctions
1584 : V4SpillToMemoryFunctions;
1585 break;
1586 case SK_FromMem:
1587 SpillFunc = V4SpillFromMemoryFunctions;
1588 break;
1589 case SK_FromMemTailcall:
1590 SpillFunc = V4SpillFromMemoryTailcallFunctions;
1591 break;
1592 }
1593 assert(SpillFunc && "Unknown spill kind");
1594
1595 // Spill all callee-saved registers up to the highest register used.
1596 switch (MaxReg) {
1597 case Hexagon::R17:
1598 return SpillFunc[0];
1599 case Hexagon::R19:
1600 return SpillFunc[1];
1601 case Hexagon::R21:
1602 return SpillFunc[2];
1603 case Hexagon::R23:
1604 return SpillFunc[3];
1605 case Hexagon::R25:
1606 return SpillFunc[4];
1607 case Hexagon::R27:
1608 return SpillFunc[5];
1609 default:
1610 llvm_unreachable("Unhandled maximum callee save register");
1611 }
1612 return nullptr;
1613}
1614
1615StackOffset
1617 Register &FrameReg) const {
1618 auto &MFI = MF.getFrameInfo();
1619 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
1620
1621 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1622 if (HMFI.isVTCMStackIndex(FI)) {
1623 const MachineFrameInfo &VTCMFrameInfo = HMFI.getVTCMFrameInfo();
1624 FrameReg = HRI.getVTCMStackRegister();
1625 return StackOffset::getFixed(VTCMFrameInfo.getStackSize() +
1626 HMFI.getMappedVTCMObjectOffset(FI));
1627 }
1628
1629 int Offset = MFI.getObjectOffset(FI);
1630 bool HasAlloca = MFI.hasVarSizedObjects();
1631 bool HasExtraAlign = HRI.hasStackRealignment(MF);
1632 bool NoOpt = MF.getTarget().getOptLevel() == CodeGenOptLevel::None;
1633
1634 unsigned FrameSize = MFI.getStackSize();
1635 Register SP = HRI.getStackRegister();
1636 Register FP = HRI.getFrameRegister();
1637 Register AP = HMFI.getStackAlignBaseReg();
1638 // It may happen that AP will be absent even HasAlloca && HasExtraAlign
1639 // is true. HasExtraAlign may be set because of vector spills, without
1640 // aligned locals or aligned outgoing function arguments. Since vector
1641 // spills will ultimately be "unaligned", it is safe to use FP as the
1642 // base register.
1643 // In fact, in such a scenario the stack is actually not required to be
1644 // aligned, although it may end up being aligned anyway, since this
1645 // particular case is not easily detectable. The alignment will be
1646 // unnecessary, but not incorrect.
1647 // Unfortunately there is no quick way to verify that the above is
1648 // indeed the case (and that it's not a result of an error), so just
1649 // assume that missing AP will be replaced by FP.
1650 // (A better fix would be to rematerialize AP from FP and always align
1651 // vector spills.)
1652 bool UseFP = false, UseAP = false; // Default: use SP (except at -O0).
1653 // Use FP at -O0, except when there are objects with extra alignment.
1654 // That additional alignment requirement may cause a pad to be inserted,
1655 // which will make it impossible to use FP to access objects located
1656 // past the pad.
1657 if (NoOpt && !HasExtraAlign)
1658 UseFP = true;
1659 if (MFI.isFixedObjectIndex(FI) || MFI.isObjectPreAllocated(FI)) {
1660 // Fixed and preallocated objects will be located before any padding
1661 // so FP must be used to access them.
1662 UseFP |= (HasAlloca || HasExtraAlign);
1663 } else {
1664 if (HasAlloca) {
1665 if (HasExtraAlign)
1666 UseAP = true;
1667 else
1668 UseFP = true;
1669 }
1670 }
1671
1672 // If FP was picked, then there had better be FP.
1673 bool HasFP = hasFP(MF);
1674 assert((HasFP || !UseFP) && "This function must have frame pointer");
1675
1676 // Having FP implies allocframe. Allocframe will store extra 8 bytes:
1677 // FP/LR. If the base register is used to access an object across these
1678 // 8 bytes, then the offset will need to be adjusted by 8.
1679 //
1680 // After allocframe:
1681 // HexagonISelLowering adds 8 to ---+
1682 // the offsets of all stack-based |
1683 // arguments (*) |
1684 // |
1685 // getObjectOffset < 0 0 8 getObjectOffset >= 8
1686 // ------------------------+-----+------------------------> increasing
1687 // <local objects> |FP/LR| <input arguments> addresses
1688 // -----------------+------+-----+------------------------>
1689 // | |
1690 // SP/AP point --+ +-- FP points here (**)
1691 // somewhere on
1692 // this side of FP/LR
1693 //
1694 // (*) See LowerFormalArguments. The FP/LR is assumed to be present.
1695 // (**) *FP == old-FP. FP+0..7 are the bytes of FP/LR.
1696
1697 // The lowering assumes that FP/LR is present, and so the offsets of
1698 // the formal arguments start at 8. If FP/LR is not there we need to
1699 // reduce the offset by 8.
1700 if (Offset > 0 && !HasFP)
1701 Offset -= 8;
1702
1703 if (UseFP)
1704 FrameReg = FP;
1705 else if (UseAP)
1706 FrameReg = AP;
1707 else
1708 FrameReg = SP;
1709
1710 // Calculate the actual offset in the instruction. If there is no FP
1711 // (in other words, no allocframe), then SP will not be adjusted (i.e.
1712 // there will be no SP -= FrameSize), so the frame size should not be
1713 // added to the calculated offset.
1714 int RealOffset = Offset;
1715 if (!UseFP && !UseAP)
1716 RealOffset = FrameSize+Offset;
1717 return StackOffset::getFixed(RealOffset);
1718}
1719
1720MachineBasicBlock::iterator HexagonFrameLowering::insertCSRSpillsInBlock(
1721 MachineBasicBlock &MBB, const CSIVect &CSI, const HexagonRegisterInfo &HRI,
1722 bool &PrologueStubs) const {
1724 if (CSI.empty())
1725 return MI;
1726
1727 PrologueStubs = false;
1728 MachineFunction &MF = *MBB.getParent();
1729 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1730 auto &HII = *HST.getInstrInfo();
1731
1732 if (useSpillFunction(MF, CSI)) {
1733 PrologueStubs = true;
1734 Register MaxReg = getMaxCalleeSavedReg(CSI, HRI);
1735 bool StkOvrFlowEnabled = HST.getCLOpts().stackovf_sanitizer;
1736 const char *SpillFun = getSpillFunctionFor(MaxReg, SK_ToMem,
1737 StkOvrFlowEnabled);
1738 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1739 bool IsPIC = HTM.isPositionIndependent();
1740 bool LongCalls = HST.useLongCalls() || HST.getCLOpts().save_restore_long;
1741
1742 // Call spill function.
1743 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1744 unsigned SpillOpc;
1745 if (StkOvrFlowEnabled) {
1746 if (LongCalls)
1747 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT_PIC
1748 : Hexagon::SAVE_REGISTERS_CALL_V4STK_EXT;
1749 else
1750 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4STK_PIC
1751 : Hexagon::SAVE_REGISTERS_CALL_V4STK;
1752 } else {
1753 if (LongCalls)
1754 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC
1755 : Hexagon::SAVE_REGISTERS_CALL_V4_EXT;
1756 else
1757 SpillOpc = IsPIC ? Hexagon::SAVE_REGISTERS_CALL_V4_PIC
1758 : Hexagon::SAVE_REGISTERS_CALL_V4;
1759 }
1760
1761 MachineInstr *SaveRegsCall =
1762 BuildMI(MBB, MI, DL, HII.get(SpillOpc))
1763 .addExternalSymbol(SpillFun);
1764
1765 // Add callee-saved registers as use.
1766 addCalleeSaveRegistersAsImpOperand(SaveRegsCall, CSI, false, true);
1767 // Add live in registers.
1768 for (const CalleeSavedInfo &I : CSI)
1769 MBB.addLiveIn(I.getReg());
1770 } else {
1771 for (const CalleeSavedInfo &I : CSI) {
1772 MCRegister Reg = I.getReg();
1773 // Add live in registers. We treat eh_return callee saved register r0 - r3
1774 // specially. They are not really callee saved registers as they are not
1775 // supposed to be killed.
1776 bool IsKill = !HRI.isEHReturnCalleeSaveReg(Reg);
1777 int FI = I.getFrameIdx();
1778 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1779 HII.storeRegToStackSlot(MBB, MI, Reg, IsKill, FI, RC, Register());
1780 if (IsKill)
1781 MBB.addLiveIn(Reg);
1782 }
1783 }
1784
1785 return MI;
1786}
1787
1788bool HexagonFrameLowering::insertCSRRestoresInBlock(MachineBasicBlock &MBB,
1789 const CSIVect &CSI, const HexagonRegisterInfo &HRI) const {
1790 if (CSI.empty())
1791 return false;
1792
1794 MachineFunction &MF = *MBB.getParent();
1795 auto &HST = MF.getSubtarget<HexagonSubtarget>();
1796 auto &HII = *HST.getInstrInfo();
1797
1798 if (useRestoreFunction(MF, CSI)) {
1799 bool HasTC = hasTailCall(MBB) || !hasReturn(MBB);
1800 Register MaxR = getMaxCalleeSavedReg(CSI, HRI);
1802 const char *RestoreFn = getSpillFunctionFor(MaxR, Kind);
1803 auto &HTM = static_cast<const HexagonTargetMachine&>(MF.getTarget());
1804 bool IsPIC = HTM.isPositionIndependent();
1805 bool LongCalls = HST.useLongCalls() || HST.getCLOpts().save_restore_long;
1806
1807 // Call spill function.
1808 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc()
1809 : MBB.findDebugLoc(MBB.end());
1810 MachineInstr *DeallocCall = nullptr;
1811
1812 if (HasTC) {
1813 unsigned RetOpc;
1814 if (LongCalls)
1815 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT_PIC
1816 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_EXT;
1817 else
1818 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4_PIC
1819 : Hexagon::RESTORE_DEALLOC_BEFORE_TAILCALL_V4;
1820 DeallocCall = BuildMI(MBB, MI, DL, HII.get(RetOpc))
1821 .addExternalSymbol(RestoreFn);
1822 } else {
1823 // The block has a return.
1825 assert(It->isReturn() && std::next(It) == MBB.end());
1826 unsigned RetOpc;
1827 if (LongCalls)
1828 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT_PIC
1829 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4_EXT;
1830 else
1831 RetOpc = IsPIC ? Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC
1832 : Hexagon::RESTORE_DEALLOC_RET_JMP_V4;
1833 MachineInstrBuilder MIB =
1834 BuildMI(MBB, It, DL, HII.get(RetOpc)).addExternalSymbol(RestoreFn);
1835 // Transfer the function live-out registers, avoiding duplicating the pc
1836 // implicit-def.
1837 for (const MachineOperand &MO : drop_begin(It->implicit_operands()))
1838 MIB.add(MO);
1839 DeallocCall = MIB;
1840 }
1841 addCalleeSaveRegistersAsImpOperand(DeallocCall, CSI, true, false);
1842 return true;
1843 }
1844
1845 for (const CalleeSavedInfo &I : CSI) {
1846 MCRegister Reg = I.getReg();
1847 const TargetRegisterClass *RC = HRI.getMinimalPhysRegClass(Reg);
1848 int FI = I.getFrameIdx();
1849 HII.loadRegFromStackSlot(MBB, MI, Reg, FI, RC, Register());
1850 }
1851
1852 return true;
1853}
1854
1858 MachineInstr &MI = *I;
1859 unsigned Opc = MI.getOpcode();
1860 (void)Opc; // Silence compiler warning.
1861 assert((Opc == Hexagon::ADJCALLSTACKDOWN || Opc == Hexagon::ADJCALLSTACKUP) &&
1862 "Cannot handle this call frame pseudo instruction");
1863 return MBB.erase(I);
1864}
1865
1866void HexagonFrameLowering::computeVTCMStackOffsets(MachineFunction &MF) const {
1867 MachineFrameInfo &MFI = MF.getFrameInfo();
1868 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
1869 const auto &HRI = *HST.getRegisterInfo();
1870 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1871 MachineFrameInfo &VTCMFrameInfo = HMFI.getVTCMFrameInfo();
1872 const int64_t HlxLRSize = HRI.getSpillSize(Hexagon::HlxLRRegClass);
1873 const int64_t HlxLLRSize = HRI.getSpillSize(Hexagon::HlxLLRRegClass);
1874
1875 // Incoming HLX stack arguments are just above the VTCM frame. NoAlloc
1876 // fixed objects are incoming HLX stack arguments (see LowerFormalArguments).
1877 for (int I = MFI.getObjectIndexBegin(); I != 0; ++I) {
1879 continue;
1880 HMFI.moveToVTCMStack(I, VTCMFrameInfo.CreateFixedObject(
1881 MFI.getObjectSize(I), MFI.getObjectOffset(I),
1882 /*IsImmutable=*/true));
1883 }
1884
1885 int64_t Offset = 0;
1886 for (int I = 0, E = MFI.getObjectIndexEnd(); I != E; ++I) {
1887 bool IsHlxSpill =
1888 MFI.isSpillSlotObjectIndex(I) && (MFI.getObjectSize(I) == HlxLRSize ||
1889 MFI.getObjectSize(I) == HlxLLRSize);
1890 if (MFI.isDeadObjectIndex(I) || MFI.isFixedObjectIndex(I) ||
1891 (!IsHlxSpill && MFI.isSpillSlotObjectIndex(I)) ||
1893 continue;
1894 const AllocaInst *AI = MFI.getObjectAllocation(I);
1895 if (!IsHlxSpill && (!AI || !containsHLXObject(HST, AI->getAllocatedType())))
1896 continue;
1897
1898 int64_t Size = MFI.getObjectSize(I);
1899 Align Alignment = MFI.getObjectAlign(I);
1900 int VTCMIndex =
1901 IsHlxSpill ? VTCMFrameInfo.CreateSpillStackObject(Size, Alignment)
1902 : VTCMFrameInfo.CreateStackObject(
1903 Size, Alignment, false, MFI.getObjectAllocation(I));
1904 Offset += Size;
1905 VTCMFrameInfo.setObjectOffset(VTCMIndex, -Offset);
1906 HMFI.moveToVTCMStack(I, VTCMIndex);
1907 MFI.RemoveStackObject(I);
1908 }
1909 // Outgoing HLX stack arguments are stored at VSP+0 and up, below the
1910 // objects above.
1911 uint64_t StackSize = Offset + HMFI.getMaxVTCMCallFrameSize();
1912 VTCMFrameInfo.setStackSize(StackSize);
1913
1914 // The "hlx-vector-stack-limit" function attribute overrides the option.
1915 const Function &F = MF.getFunction();
1916 uint64_t Limit = F.getFnAttributeAsParsedInteger(
1917 "hlx-vector-stack-limit",
1918 MF.getSubtarget<HexagonSubtarget>().getCLOpts().hlx_vector_stack_limit);
1919 if (StackSize > Limit)
1920 F.getContext().diagnose(DiagnosticInfoResourceLimit(
1921 F, "HLX vector stack size", StackSize, Limit, DS_Error));
1922}
1923
1925 MachineFunction &MF, RegScavenger *RS) const {
1926 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
1927 if (!HST.hasV85OpsOnly() || !HST.useHLXOps())
1928 return;
1929 computeVTCMStackOffsets(MF);
1930 auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1931 if (HST.getCLOpts().save_parent_vsp && HMFI.getVTCMFrameInfo().getStackSize())
1932 HMFI.setVSPFrameIndex(
1934}
1935
1936Align HexagonFrameLowering::getMaxStackAlign(const MachineFunction &MF) const {
1937 const MachineFrameInfo &MFI = MF.getFrameInfo();
1938 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
1939 if (!HST.hasV85OpsOnly() || !HST.useHLXOps())
1940 return MFI.getMaxAlign();
1941
1942 // MFI's max alignment includes the 2048-byte alignment of the HLX objects
1943 // moved to the VTCM stack, so recompute it from the scalar frame objects.
1944 // Add the requests not tied to an object: outgoing stack arguments (byval
1945 // and HVX vectors, see HexagonTargetLowering::LowerCall) and the function's
1946 // alignstack. Incoming stack arguments are aligned by the caller and need no
1947 // realignment here.
1948 const auto &HMFI = *MF.getInfo<HexagonMachineFunctionInfo>();
1949 Align MaxAlign = std::max(HMFI.getOutgoingArgAlign(),
1951 for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd(); I != E;
1952 ++I) {
1953 if (MFI.isDeadObjectIndex(I))
1954 continue;
1955 MaxAlign = std::max(MaxAlign, MFI.getObjectAlign(I));
1956 }
1957 return MaxAlign;
1958}
1959
1960/// Returns true if there are no caller-saved registers available in class RC.
1962 const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC) {
1964
1965 auto IsUsed = [&HRI,&MRI] (Register Reg) -> bool {
1966 for (MCRegAliasIterator AI(Reg, &HRI, true); AI.isValid(); ++AI)
1967 if (MRI.isPhysRegUsed(*AI))
1968 return true;
1969 return false;
1970 };
1971
1972 // Check for an unused caller-saved register. Callee-saved registers
1973 // have become pristine by now.
1974 for (const MCPhysReg *P = HRI.getCallerSavedRegs(&MF, RC); *P; ++P)
1975 if (!IsUsed(*P))
1976 return false;
1977
1978 // All caller-saved registers are used.
1979 return true;
1980}
1981
1982#ifndef NDEBUG
1984 dbgs() << '{';
1985 for (int x = Regs.find_first(); x >= 0; x = Regs.find_next(x)) {
1986 Register R = x;
1987 dbgs() << ' ' << printReg(R, &TRI);
1988 }
1989 dbgs() << " }";
1990}
1991#endif
1992
1994 const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const {
1995 LLVM_DEBUG(dbgs() << __func__ << " on " << MF.getName() << '\n');
1996 MachineFrameInfo &MFI = MF.getFrameInfo();
1997 BitVector SRegs(Hexagon::NUM_TARGET_REGS);
1998
1999 // Generate a set of unique, callee-saved registers (SRegs), where each
2000 // register in the set is maximal in terms of sub-/super-register relation,
2001 // i.e. for each R in SRegs, no proper super-register of R is also in SRegs.
2002
2003 // (1) For each callee-saved register, add that register and all of its
2004 // sub-registers to SRegs.
2005 LLVM_DEBUG(dbgs() << "Initial CS registers: {");
2006 for (const CalleeSavedInfo &I : CSI) {
2007 Register R = I.getReg();
2008 LLVM_DEBUG(dbgs() << ' ' << printReg(R, TRI));
2009 for (MCPhysReg SR : TRI->subregs_inclusive(R))
2010 SRegs[SR] = true;
2011 }
2012 LLVM_DEBUG(dbgs() << " }\n");
2013 LLVM_DEBUG(dbgs() << "SRegs.1: "; dump_registers(SRegs, *TRI);
2014 dbgs() << "\n");
2015
2016 // (2) For each reserved register, remove that register and all of its
2017 // sub- and super-registers from SRegs.
2018 BitVector Reserved = TRI->getReservedRegs(MF);
2019 // Unreserve the stack align register: it is reserved for this function
2020 // only, it still needs to be saved/restored.
2021 Register AP =
2022 MF.getInfo<HexagonMachineFunctionInfo>()->getStackAlignBaseReg();
2023 assert((!needsAligna(MF) || AP.isValid()) &&
2024 "AP must be assigned before register allocation");
2025 if (AP.isValid()) {
2026 Reserved[AP] = false;
2027 // Unreserve super-regs if no other subregisters are reserved.
2028 for (MCPhysReg SP : TRI->superregs(AP)) {
2029 bool HasResSub = false;
2030 for (MCPhysReg SB : TRI->subregs(SP)) {
2031 if (!Reserved[SB])
2032 continue;
2033 HasResSub = true;
2034 break;
2035 }
2036 if (!HasResSub)
2037 Reserved[SP] = false;
2038 }
2039 }
2040
2041 for (int x = Reserved.find_first(); x >= 0; x = Reserved.find_next(x)) {
2042 Register R = x;
2043 for (MCPhysReg SR : TRI->superregs_inclusive(R))
2044 SRegs[SR] = false;
2045 }
2046 LLVM_DEBUG(dbgs() << "Res: "; dump_registers(Reserved, *TRI);
2047 dbgs() << "\n");
2048 LLVM_DEBUG(dbgs() << "SRegs.2: "; dump_registers(SRegs, *TRI);
2049 dbgs() << "\n");
2050
2051 // (3) Collect all registers that have at least one sub-register in SRegs,
2052 // and also have no sub-registers that are reserved. These will be the can-
2053 // didates for saving as a whole instead of their individual sub-registers.
2054 // (Saving R17:16 instead of R16 is fine, but only if R17 was not reserved.)
2055 // HLX registers are saved individually: there is no HLX pair spill.
2056 BitVector TmpSup(Hexagon::NUM_TARGET_REGS);
2057 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
2058 Register R = x;
2059 if (Hexagon::HlxLRRegClass.contains(R))
2060 continue;
2061 for (MCPhysReg SR : TRI->superregs(R))
2062 TmpSup[SR] = true;
2063 }
2064 for (int x = TmpSup.find_first(); x >= 0; x = TmpSup.find_next(x)) {
2065 Register R = x;
2066 for (MCPhysReg SR : TRI->subregs_inclusive(R)) {
2067 if (!Reserved[SR])
2068 continue;
2069 TmpSup[R] = false;
2070 break;
2071 }
2072 }
2073 LLVM_DEBUG(dbgs() << "TmpSup: "; dump_registers(TmpSup, *TRI);
2074 dbgs() << "\n");
2075
2076 // (4) Include all super-registers found in (3) into SRegs.
2077 SRegs |= TmpSup;
2078 LLVM_DEBUG(dbgs() << "SRegs.4: "; dump_registers(SRegs, *TRI);
2079 dbgs() << "\n");
2080
2081 // (5) For each register R in SRegs, if any super-register of R is in SRegs,
2082 // remove R from SRegs.
2083 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
2084 Register R = x;
2085 for (MCPhysReg SR : TRI->superregs(R)) {
2086 if (!SRegs[SR])
2087 continue;
2088 SRegs[R] = false;
2089 break;
2090 }
2091 }
2092 LLVM_DEBUG(dbgs() << "SRegs.5: "; dump_registers(SRegs, *TRI);
2093 dbgs() << "\n");
2094
2095 // Now, for each register that has a fixed stack slot, create the stack
2096 // object for it.
2097 CSI.clear();
2098
2100
2101 unsigned NumFixed;
2102 int64_t MinOffset = 0; // CS offsets are negative.
2103 const SpillSlot *FixedSlots = getCalleeSavedSpillSlots(NumFixed);
2104 for (const SpillSlot *S = FixedSlots; S != FixedSlots+NumFixed; ++S) {
2105 if (!SRegs[S->Reg])
2106 continue;
2107 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(S->Reg);
2108 int FI = MFI.CreateFixedSpillStackObject(TRI->getSpillSize(*RC), S->Offset);
2109 MinOffset = std::min(MinOffset, S->Offset);
2110 CSI.push_back(CalleeSavedInfo(S->Reg, FI));
2111 SRegs[S->Reg] = false;
2112 }
2113
2114 // There can be some registers that don't have fixed slots. For example,
2115 // we need to store R0-R3 in functions with exception handling. For each
2116 // such register, create a non-fixed stack object.
2117 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
2118 Register R = x;
2119 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(R);
2120 unsigned Size = TRI->getSpillSize(*RC);
2121 // HLX registers are saved in spill slots on the VTCM stack.
2122 if (Hexagon::HlxLRRegClass.contains(R)) {
2123 int FI = MFI.CreateSpillStackObject(Size, TRI->getSpillAlign(*RC));
2124 CSI.push_back(CalleeSavedInfo(R, FI));
2125 SRegs[R] = false;
2126 continue;
2127 }
2128 int64_t Off = MinOffset - Size;
2129 Align Alignment = std::min(TRI->getSpillAlign(*RC), getStackAlign());
2130 Off &= -Alignment.value();
2131 int FI = MFI.CreateFixedSpillStackObject(Size, Off);
2132 MinOffset = std::min(MinOffset, Off);
2133 CSI.push_back(CalleeSavedInfo(R, FI));
2134 SRegs[R] = false;
2135 }
2136
2137 LLVM_DEBUG({
2138 dbgs() << "CS information: {";
2139 for (const CalleeSavedInfo &I : CSI) {
2140 int FI = I.getFrameIdx();
2141 int Off = MFI.getObjectOffset(FI);
2142 dbgs() << ' ' << printReg(I.getReg(), TRI) << ":fi#" << FI << ":sp";
2143 if (Off >= 0)
2144 dbgs() << '+';
2145 dbgs() << Off;
2146 }
2147 dbgs() << " }\n";
2148 });
2149
2150#ifndef NDEBUG
2151 // Verify that all registers were handled.
2152 bool MissedReg = false;
2153 for (int x = SRegs.find_first(); x >= 0; x = SRegs.find_next(x)) {
2154 Register R = x;
2155 dbgs() << printReg(R, TRI) << ' ';
2156 MissedReg = true;
2157 }
2158 if (MissedReg)
2159 llvm_unreachable("...there are unhandled callee-saved registers!");
2160#endif
2161
2162 return true;
2163}
2164
2165bool HexagonFrameLowering::expandCopy(MachineBasicBlock &B,
2167 const HexagonInstrInfo &HII, SmallVectorImpl<Register> &NewRegs) const {
2168 MachineInstr *MI = &*It;
2169 DebugLoc DL = MI->getDebugLoc();
2170 Register DstR = MI->getOperand(0).getReg();
2171 Register SrcR = MI->getOperand(1).getReg();
2172 if (!Hexagon::ModRegsRegClass.contains(DstR) ||
2173 !Hexagon::ModRegsRegClass.contains(SrcR))
2174 return false;
2175
2176 Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2177 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), TmpR).add(MI->getOperand(1));
2178 BuildMI(B, It, DL, HII.get(TargetOpcode::COPY), DstR)
2179 .addReg(TmpR, RegState::Kill);
2180
2181 NewRegs.push_back(TmpR);
2182 B.erase(It);
2183 return true;
2184}
2185
2186bool HexagonFrameLowering::expandStoreInt(MachineBasicBlock &B,
2188 const HexagonInstrInfo &HII, SmallVectorImpl<Register> &NewRegs) const {
2189 MachineInstr *MI = &*It;
2190 if (!MI->getOperand(0).isFI())
2191 return false;
2192
2193 DebugLoc DL = MI->getDebugLoc();
2194 unsigned Opc = MI->getOpcode();
2195 Register SrcR = MI->getOperand(2).getReg();
2196 bool IsKill = MI->getOperand(2).isKill();
2197 int FI = MI->getOperand(0).getIndex();
2198
2199 // TmpR = C2_tfrpr SrcR if SrcR is a predicate register
2200 // TmpR = A2_tfrcrr SrcR if SrcR is a modifier register
2201 Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2202 unsigned TfrOpc = (Opc == Hexagon::STriw_pred) ? Hexagon::C2_tfrpr
2203 : Hexagon::A2_tfrcrr;
2204 BuildMI(B, It, DL, HII.get(TfrOpc), TmpR)
2205 .addReg(SrcR, getKillRegState(IsKill));
2206
2207 // S2_storeri_io FI, 0, TmpR
2208 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
2209 .addFrameIndex(FI)
2210 .addImm(0)
2211 .addReg(TmpR, RegState::Kill)
2212 .cloneMemRefs(*MI);
2213
2214 NewRegs.push_back(TmpR);
2215 B.erase(It);
2216 return true;
2217}
2218
2219bool HexagonFrameLowering::expandStoreCirc(
2220 MachineBasicBlock &B, MachineBasicBlock::iterator It,
2221 MachineRegisterInfo &MRI, const HexagonInstrInfo &HII,
2222 SmallVectorImpl<Register> &NewRegs) const {
2223 MachineFunction &MF = *B.getParent();
2224 const auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2225 MachineInstr *MI = &*It;
2226 if (!MI->getOperand(0).isFI())
2227 return false;
2228
2229 DebugLoc DL = MI->getDebugLoc();
2230 Register SrcR = MI->getOperand(1).getReg();
2231 bool IsKill = MI->getOperand(1).isKill();
2232 int FI = MI->getOperand(0).getIndex();
2233
2234 unsigned Offset = 0;
2235 for (auto SubReg : {Hexagon::isub_lo, Hexagon::isub_hi}) {
2236 Register SrcSubReg = HRI.getSubReg(SrcR, SubReg);
2237
2238 // TmpR = A2_tfrcrr SrcSubReg.
2239 Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2240 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrcrr), TmpR)
2241 .addReg(SrcSubReg, getKillRegState(IsKill))
2242 ->copyImplicitOps(MF, *It);
2243
2244 // S2_storeri_io FI/FI+offset, TmpR.
2245 BuildMI(B, It, DL, HII.get(Hexagon::S2_storeri_io))
2246 .addFrameIndex(FI)
2247 .addImm(Offset)
2248 .addReg(TmpR, RegState::Kill)
2249 .cloneMemRefs(*MI);
2250 NewRegs.push_back(TmpR);
2251 Offset += HRI.getSpillSize(Hexagon::IntRegsRegClass);
2252 }
2253
2254 B.erase(It);
2255 return true;
2256}
2257
2258bool HexagonFrameLowering::expandLoadCirc(
2259 MachineBasicBlock &B, MachineBasicBlock::iterator It,
2260 MachineRegisterInfo &MRI, const HexagonInstrInfo &HII,
2261 SmallVectorImpl<Register> &NewRegs) const {
2262 MachineFunction &MF = *B.getParent();
2263 const auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2264 MachineInstr *MI = &*It;
2265 if (!MI->getOperand(1).isFI())
2266 return false;
2267
2268 DebugLoc DL = MI->getDebugLoc();
2269 Register DstR = MI->getOperand(0).getReg();
2270 int FI = MI->getOperand(1).getIndex();
2271
2272 unsigned Offset = 0;
2273 for (auto SubReg : {Hexagon::isub_lo, Hexagon::isub_hi}) {
2274 Register DstSubReg = HRI.getSubReg(DstR, SubReg);
2275
2276 // TmpR = L2_loadri_io FI, Offset.
2277 Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2278 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
2279 .addFrameIndex(FI)
2280 .addImm(Offset)
2281 .cloneMemRefs(*MI);
2282
2283 // DstR = A2_tfrrcr TmpR.
2284 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrrcr), DstSubReg)
2285 .addReg(TmpR, RegState::Kill)
2286 ->copyImplicitOps(MF, *It);
2287
2288 NewRegs.push_back(TmpR);
2289 Offset += HRI.getSpillSize(Hexagon::IntRegsRegClass);
2290 }
2291
2292 B.erase(It);
2293 return true;
2294}
2295
2296bool HexagonFrameLowering::expandLoadInt(
2297 MachineBasicBlock &B, MachineBasicBlock::iterator It,
2298 MachineRegisterInfo &MRI, const HexagonInstrInfo &HII,
2299 SmallVectorImpl<Register> &NewRegs) const {
2300 MachineInstr *MI = &*It;
2301 if (!MI->getOperand(1).isFI())
2302 return false;
2303
2304 DebugLoc DL = MI->getDebugLoc();
2305 unsigned Opc = MI->getOpcode();
2306 Register DstR = MI->getOperand(0).getReg();
2307 int FI = MI->getOperand(1).getIndex();
2308
2309 // TmpR = L2_loadri_io FI, 0
2310 Register TmpR = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2311 BuildMI(B, It, DL, HII.get(Hexagon::L2_loadri_io), TmpR)
2312 .addFrameIndex(FI)
2313 .addImm(0)
2314 .cloneMemRefs(*MI);
2315
2316 // DstR = C2_tfrrp TmpR if DstR is a predicate register
2317 // DstR = A2_tfrrcr TmpR if DstR is a modifier register
2318 unsigned TfrOpc = (Opc == Hexagon::LDriw_pred) ? Hexagon::C2_tfrrp
2319 : Hexagon::A2_tfrrcr;
2320 BuildMI(B, It, DL, HII.get(TfrOpc), DstR)
2321 .addReg(TmpR, RegState::Kill);
2322
2323 NewRegs.push_back(TmpR);
2324 B.erase(It);
2325 return true;
2326}
2327
2328bool HexagonFrameLowering::expandStoreVecPred(MachineBasicBlock &B,
2329 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
2330 const HexagonInstrInfo &HII, SmallVectorImpl<Register> &NewRegs) const {
2331 MachineInstr *MI = &*It;
2332 if (!MI->getOperand(0).isFI())
2333 return false;
2334
2335 DebugLoc DL = MI->getDebugLoc();
2336 Register SrcR = MI->getOperand(2).getReg();
2337 bool IsKill = MI->getOperand(2).isKill();
2338 int FI = MI->getOperand(0).getIndex();
2339 auto *RC = &Hexagon::HvxVRRegClass;
2340
2341 // Insert transfer to general vector register.
2342 // TmpR0 = A2_tfrsi 0x01010101
2343 // TmpR1 = V6_vandqrt Qx, TmpR0
2344 // store FI, 0, TmpR1
2345 Register TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2347
2348 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
2349 .addImm(0x01010101);
2350
2351 BuildMI(B, It, DL, HII.get(Hexagon::V6_vandqrt), TmpR1)
2352 .addReg(SrcR, getKillRegState(IsKill))
2353 .addReg(TmpR0, RegState::Kill);
2354
2355 HII.storeRegToStackSlot(B, It, TmpR1, true, FI, RC, Register());
2356 expandStoreVec(B, std::prev(It), MRI, HII, NewRegs);
2357
2358 NewRegs.push_back(TmpR0);
2359 NewRegs.push_back(TmpR1);
2360 B.erase(It);
2361 return true;
2362}
2363
2364bool HexagonFrameLowering::expandLoadVecPred(MachineBasicBlock &B,
2365 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
2366 const HexagonInstrInfo &HII, SmallVectorImpl<Register> &NewRegs) const {
2367 MachineInstr *MI = &*It;
2368 if (!MI->getOperand(1).isFI())
2369 return false;
2370
2371 DebugLoc DL = MI->getDebugLoc();
2372 Register DstR = MI->getOperand(0).getReg();
2373 int FI = MI->getOperand(1).getIndex();
2374 auto *RC = &Hexagon::HvxVRRegClass;
2375
2376 // TmpR0 = A2_tfrsi 0x01010101
2377 // TmpR1 = load FI, 0
2378 // DstR = V6_vandvrt TmpR1, TmpR0
2379 Register TmpR0 = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2381
2382 BuildMI(B, It, DL, HII.get(Hexagon::A2_tfrsi), TmpR0)
2383 .addImm(0x01010101);
2384 HII.loadRegFromStackSlot(B, It, TmpR1, FI, RC, Register());
2385 expandLoadVec(B, std::prev(It), MRI, HII, NewRegs);
2386
2387 BuildMI(B, It, DL, HII.get(Hexagon::V6_vandvrt), DstR)
2388 .addReg(TmpR1, RegState::Kill)
2389 .addReg(TmpR0, RegState::Kill);
2390
2391 NewRegs.push_back(TmpR0);
2392 NewRegs.push_back(TmpR1);
2393 B.erase(It);
2394 return true;
2395}
2396
2397bool HexagonFrameLowering::expandStoreVec2(MachineBasicBlock &B,
2399 MachineRegisterInfo &MRI,
2400 const HexagonInstrInfo &HII,
2401 SmallVectorImpl<Register> &NewRegs,
2402 bool IsHLX) const {
2403 MachineFunction &MF = *B.getParent();
2404 auto &MFI = MF.getFrameInfo();
2405 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2406 MachineInstr *MI = &*It;
2407 if (!MI->getOperand(0).isFI())
2408 return false;
2409
2410 // It is possible that the double vector being stored is only partially
2411 // defined. From the point of view of the liveness tracking, it is ok to
2412 // store it as a whole, but if we break it up we may end up storing a
2413 // register that is entirely undefined.
2414 LivePhysRegs LPR(HRI);
2415 LPR.addLiveIns(B);
2417 for (auto R = B.begin(); R != It; ++R) {
2418 Clobbers.clear();
2419 LPR.stepForward(*R, Clobbers);
2420 }
2421
2422 DebugLoc DL = MI->getDebugLoc();
2423 Register SrcR = MI->getOperand(2).getReg();
2424 Register SrcLo = HRI.getSubReg(SrcR, Hexagon::vsub_lo);
2425 Register SrcHi = HRI.getSubReg(SrcR, Hexagon::vsub_hi);
2426 bool IsKill = MI->getOperand(2).isKill();
2427 int FI = MI->getOperand(0).getIndex();
2428
2429 if (IsHLX) {
2430 const MachineOperand &SrcOp = MI->getOperand(2);
2431 unsigned Size = HRI.getSpillSize(Hexagon::HlxLRRegClass);
2432 assert(MI->hasOneMemOperand() && "HLX pair spill must have one MMO");
2433 const MachineMemOperand *PairMMO = *MI->memoperands_begin();
2434 MachineMemOperand *LoMMO = MF.getMachineMemOperand(PairMMO, 0, Size);
2435 MachineMemOperand *HiMMO = MF.getMachineMemOperand(PairMMO, Size, Size);
2436
2437 if (LPR.contains(SrcLo)) {
2438 BuildMI(B, It, DL, HII.get(Hexagon::LX_S16b_pseudo))
2439 .addFrameIndex(FI)
2440 .addReg(SrcLo, getRegState(SrcOp))
2441 .addReg(Hexagon::VSP, RegState::Implicit)
2442 .addMemOperand(LoMMO);
2443 }
2444
2445 if (LPR.contains(SrcHi)) {
2446 Register StackReg = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2447 BuildMI(B, It, DL, HII.get(Hexagon::A2_addi), StackReg)
2448 .addFrameIndex(FI)
2449 .addImm(Size);
2450 BuildMI(B, It, DL, HII.get(Hexagon::LX_S16b_pseudo))
2451 .addReg(StackReg, RegState::Kill)
2452 .addReg(SrcHi, getRegState(SrcOp))
2453 .addReg(Hexagon::VSP, RegState::Implicit)
2454 .addMemOperand(HiMMO);
2455 }
2456
2457 B.erase(It);
2458 return true;
2459 }
2460
2461 unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
2462 Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
2463 Align HasAlign = MFI.getObjectAlign(FI);
2464 unsigned StoreOpc;
2465
2466 // Store low part.
2467 if (LPR.contains(SrcLo)) {
2468 StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
2469 : Hexagon::V6_vS32Ub_ai;
2470 BuildMI(B, It, DL, HII.get(StoreOpc))
2471 .addFrameIndex(FI)
2472 .addImm(0)
2473 .addReg(SrcLo, getKillRegState(IsKill))
2474 .cloneMemRefs(*MI);
2475 }
2476
2477 // Store high part.
2478 if (LPR.contains(SrcHi)) {
2479 StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
2480 : Hexagon::V6_vS32Ub_ai;
2481 BuildMI(B, It, DL, HII.get(StoreOpc))
2482 .addFrameIndex(FI)
2483 .addImm(Size)
2484 .addReg(SrcHi, getKillRegState(IsKill))
2485 .cloneMemRefs(*MI);
2486 }
2487
2488 B.erase(It);
2489 return true;
2490}
2491
2492bool HexagonFrameLowering::expandLoadVec2(MachineBasicBlock &B,
2494 MachineRegisterInfo &MRI,
2495 const HexagonInstrInfo &HII,
2496 SmallVectorImpl<Register> &NewRegs,
2497 bool IsHLX) const {
2498 MachineFunction &MF = *B.getParent();
2499 auto &MFI = MF.getFrameInfo();
2500 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2501 MachineInstr *MI = &*It;
2502 if (!MI->getOperand(1).isFI())
2503 return false;
2504
2505 DebugLoc DL = MI->getDebugLoc();
2506 Register DstR = MI->getOperand(0).getReg();
2507 Register DstHi = HRI.getSubReg(DstR, Hexagon::vsub_hi);
2508 Register DstLo = HRI.getSubReg(DstR, Hexagon::vsub_lo);
2509 int FI = MI->getOperand(1).getIndex();
2510
2511 if (IsHLX) {
2512 const MachineOperand &DstOp = MI->getOperand(0);
2513 unsigned Size = HRI.getSpillSize(Hexagon::HlxLRRegClass);
2514 assert(MI->hasOneMemOperand() && "HLX pair reload must have one MMO");
2515 const MachineMemOperand *PairMMO = *MI->memoperands_begin();
2516 MachineMemOperand *LoMMO = MF.getMachineMemOperand(PairMMO, 0, Size);
2517 MachineMemOperand *HiMMO = MF.getMachineMemOperand(PairMMO, Size, Size);
2518
2519 BuildMI(B, It, DL, HII.get(Hexagon::LX_L16b_pseudo))
2520 .addReg(DstLo, getRegState(DstOp))
2521 .addFrameIndex(FI)
2522 .addReg(Hexagon::VSP, RegState::Implicit)
2523 .addMemOperand(LoMMO);
2524
2525 Register StackReg = MRI.createVirtualRegister(&Hexagon::IntRegsRegClass);
2526 BuildMI(B, It, DL, HII.get(Hexagon::A2_addi), StackReg)
2527 .addFrameIndex(FI)
2528 .addImm(Size);
2529 BuildMI(B, It, DL, HII.get(Hexagon::LX_L16b_pseudo))
2530 .addReg(DstHi, getRegState(DstOp))
2531 .addReg(StackReg, RegState::Kill)
2532 .addReg(Hexagon::VSP, RegState::Implicit)
2533 .addMemOperand(HiMMO);
2534
2535 B.erase(It);
2536 return true;
2537 }
2538
2539 unsigned Size = HRI.getSpillSize(Hexagon::HvxVRRegClass);
2540 Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
2541 Align HasAlign = MFI.getObjectAlign(FI);
2542 unsigned LoadOpc;
2543
2544 // Load low part.
2545 LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
2546 : Hexagon::V6_vL32Ub_ai;
2547 BuildMI(B, It, DL, HII.get(LoadOpc), DstLo)
2548 .addFrameIndex(FI)
2549 .addImm(0)
2550 .cloneMemRefs(*MI);
2551
2552 // Load high part.
2553 LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
2554 : Hexagon::V6_vL32Ub_ai;
2555 BuildMI(B, It, DL, HII.get(LoadOpc), DstHi)
2556 .addFrameIndex(FI)
2557 .addImm(Size)
2558 .cloneMemRefs(*MI);
2559
2560 B.erase(It);
2561 return true;
2562}
2563
2564bool HexagonFrameLowering::expandStoreVec(MachineBasicBlock &B,
2565 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
2566 const HexagonInstrInfo &HII, SmallVectorImpl<Register> &NewRegs) const {
2567 MachineFunction &MF = *B.getParent();
2568 auto &MFI = MF.getFrameInfo();
2569 MachineInstr *MI = &*It;
2570 if (!MI->getOperand(0).isFI())
2571 return false;
2572
2573 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2574 DebugLoc DL = MI->getDebugLoc();
2575 Register SrcR = MI->getOperand(2).getReg();
2576 bool IsKill = MI->getOperand(2).isKill();
2577 int FI = MI->getOperand(0).getIndex();
2578
2579 Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
2580 Align HasAlign = MFI.getObjectAlign(FI);
2581 unsigned StoreOpc = NeedAlign <= HasAlign ? Hexagon::V6_vS32b_ai
2582 : Hexagon::V6_vS32Ub_ai;
2583 BuildMI(B, It, DL, HII.get(StoreOpc))
2584 .addFrameIndex(FI)
2585 .addImm(0)
2586 .addReg(SrcR, getKillRegState(IsKill))
2587 .cloneMemRefs(*MI);
2588
2589 B.erase(It);
2590 return true;
2591}
2592
2593bool HexagonFrameLowering::expandLoadVec(MachineBasicBlock &B,
2594 MachineBasicBlock::iterator It, MachineRegisterInfo &MRI,
2595 const HexagonInstrInfo &HII, SmallVectorImpl<Register> &NewRegs) const {
2596 MachineFunction &MF = *B.getParent();
2597 auto &MFI = MF.getFrameInfo();
2598 MachineInstr *MI = &*It;
2599 if (!MI->getOperand(1).isFI())
2600 return false;
2601
2602 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2603 DebugLoc DL = MI->getDebugLoc();
2604 Register DstR = MI->getOperand(0).getReg();
2605 int FI = MI->getOperand(1).getIndex();
2606
2607 Align NeedAlign = HRI.getSpillAlign(Hexagon::HvxVRRegClass);
2608 Align HasAlign = MFI.getObjectAlign(FI);
2609 unsigned LoadOpc = NeedAlign <= HasAlign ? Hexagon::V6_vL32b_ai
2610 : Hexagon::V6_vL32Ub_ai;
2611 BuildMI(B, It, DL, HII.get(LoadOpc), DstR)
2612 .addFrameIndex(FI)
2613 .addImm(0)
2614 .cloneMemRefs(*MI);
2615
2616 B.erase(It);
2617 return true;
2618}
2619
2620bool HexagonFrameLowering::expandSpillMacros(MachineFunction &MF,
2621 SmallVectorImpl<Register> &NewRegs) const {
2622 auto &HII = *MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
2623 MachineRegisterInfo &MRI = MF.getRegInfo();
2624 bool Changed = false;
2625
2626 for (auto &B : MF) {
2627 // Traverse the basic block.
2629 for (auto I = B.begin(), E = B.end(); I != E; I = NextI) {
2630 MachineInstr *MI = &*I;
2631 NextI = std::next(I);
2632 unsigned Opc = MI->getOpcode();
2633
2634 switch (Opc) {
2635 case TargetOpcode::COPY:
2636 Changed |= expandCopy(B, I, MRI, HII, NewRegs);
2637 break;
2638 case Hexagon::STriw_pred:
2639 case Hexagon::STriw_ctr:
2640 Changed |= expandStoreInt(B, I, MRI, HII, NewRegs);
2641 break;
2642 case Hexagon::STriw_circ:
2643 Changed |= expandStoreCirc(B, I, MRI, HII, NewRegs);
2644 break;
2645 case Hexagon::LDriw_pred:
2646 case Hexagon::LDriw_ctr:
2647 Changed |= expandLoadInt(B, I, MRI, HII, NewRegs);
2648 break;
2649 case Hexagon::LDriw_circ:
2650 Changed |= expandLoadCirc(B, I, MRI, HII, NewRegs);
2651 break;
2652 case Hexagon::PS_vstorerq_ai:
2653 Changed |= expandStoreVecPred(B, I, MRI, HII, NewRegs);
2654 break;
2655 case Hexagon::PS_vloadrq_ai:
2656 Changed |= expandLoadVecPred(B, I, MRI, HII, NewRegs);
2657 break;
2658 case Hexagon::PS_vloadrw_ai:
2659 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs);
2660 break;
2661 case Hexagon::PS_vstorerw_ai:
2662 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs);
2663 break;
2664 case Hexagon::PS_loadrll:
2665 Changed |= expandLoadVec2(B, I, MRI, HII, NewRegs, /*IsHLX=*/true);
2666 break;
2667 case Hexagon::PS_storerll:
2668 Changed |= expandStoreVec2(B, I, MRI, HII, NewRegs, /*IsHLX=*/true);
2669 break;
2670 }
2671 }
2672 }
2673
2674 return Changed;
2675}
2676
2678 BitVector &SavedRegs,
2679 RegScavenger *RS) const {
2680 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2681 const auto &CLOpts = MF.getSubtarget<HexagonSubtarget>().getCLOpts();
2682
2683 SavedRegs.resize(HRI.getNumRegs());
2684
2685 // If we have a function containing __builtin_eh_return we want to spill and
2686 // restore all callee saved registers. Pretend that they are used.
2688 for (const MCPhysReg *R = HRI.getCalleeSavedRegs(&MF); *R; ++R)
2689 SavedRegs.set(*R);
2690
2691 // If the function needs dynamic stack realignment, AP is a callee-saved
2692 // register that gets overwritten by the PS_aligna emitted in the prologue
2693 // but PS_aligna is created during emitPrologue, which runs after this hook.
2694 if (needsAligna(MF)) {
2695 Register AP =
2696 MF.getInfo<HexagonMachineFunctionInfo>()->getStackAlignBaseReg();
2697 assert(AP.isValid() && "AP must be assigned before register allocation");
2698 SavedRegs.set(AP);
2699 }
2700
2701 // Replace predicate register pseudo spill code.
2703 expandSpillMacros(MF, NewRegs);
2704 if (CLOpts.opt_spill && !isOptNone(MF))
2705 optimizeSpillSlots(MF, NewRegs);
2706
2707 // We need to reserve a spill slot if scavenging could potentially require
2708 // spilling a scavenged register.
2709 if (!NewRegs.empty() || mayOverflowFrameOffset(MF)) {
2710 MachineFrameInfo &MFI = MF.getFrameInfo();
2713 // Reserve an int register in any case, because it could be used to hold
2714 // the stack offset in case it does not fit into a spill instruction.
2715 SpillRCs.insert(&Hexagon::IntRegsRegClass);
2716
2717 for (Register VR : NewRegs)
2718 SpillRCs.insert(MRI.getRegClass(VR));
2719
2720 for (const auto *RC : SpillRCs) {
2721 if (!needToReserveScavengingSpillSlots(MF, HRI, RC))
2722 continue;
2723 unsigned Num = 1;
2724 switch (RC->getID()) {
2725 case Hexagon::IntRegsRegClassID:
2726 Num = CLOpts.number_scavenger_slots;
2727 break;
2728 case Hexagon::HvxQRRegClassID:
2729 Num = 2; // Vector predicate spills also need a vector register.
2730 break;
2731 }
2732 unsigned S = HRI.getSpillSize(*RC);
2733 Align A = HRI.getSpillAlign(*RC);
2734 for (unsigned i = 0; i < Num; i++) {
2735 int NewFI = MFI.CreateSpillStackObject(S, A);
2736 RS->addScavengingFrameIndex(NewFI);
2737 }
2738 }
2739 }
2740
2742}
2743
2744Register HexagonFrameLowering::findPhysReg(MachineFunction &MF,
2748 const TargetRegisterClass *RC) const {
2749 auto &HRI = *MF.getSubtarget<HexagonSubtarget>().getRegisterInfo();
2750 auto &MRI = MF.getRegInfo();
2751
2752 auto isDead = [&FIR,&DeadMap] (Register Reg) -> bool {
2753 auto F = DeadMap.find({Reg,0});
2754 if (F == DeadMap.end())
2755 return false;
2756 for (auto &DR : F->second)
2757 if (DR.contains(FIR))
2758 return true;
2759 return false;
2760 };
2761
2762 for (Register Reg : HRI.getRawAllocationOrder(*RC, MF)) {
2763 bool Dead = true;
2764 for (auto R : HexagonBlockRanges::expandToSubRegs({Reg,0}, MRI, HRI)) {
2765 if (isDead(R.Reg))
2766 continue;
2767 Dead = false;
2768 break;
2769 }
2770 if (Dead)
2771 return Reg;
2772 }
2773 return 0;
2774}
2775
2776void HexagonFrameLowering::optimizeSpillSlots(MachineFunction &MF,
2777 SmallVectorImpl<Register> &VRegs) const {
2778 auto &HST = MF.getSubtarget<HexagonSubtarget>();
2779 auto &HII = *HST.getInstrInfo();
2780 auto &HRI = *HST.getRegisterInfo();
2781 auto &MRI = MF.getRegInfo();
2782 HexagonBlockRanges HBR(MF);
2783
2784 using BlockIndexMap =
2785 std::map<MachineBasicBlock *, HexagonBlockRanges::InstrIndexMap>;
2786 using BlockRangeMap =
2787 std::map<MachineBasicBlock *, HexagonBlockRanges::RangeList>;
2788 using IndexType = HexagonBlockRanges::IndexType;
2789
2790 struct SlotInfo {
2791 BlockRangeMap Map;
2792 unsigned Size = 0;
2793 const TargetRegisterClass *RC = nullptr;
2794
2795 SlotInfo() = default;
2796 };
2797
2798 BlockIndexMap BlockIndexes;
2799 SmallSet<int,4> BadFIs;
2800 std::map<int,SlotInfo> FIRangeMap;
2801
2802 // Accumulate register classes: get a common class for a pre-existing
2803 // class HaveRC and a new class NewRC. Return nullptr if a common class
2804 // cannot be found, otherwise return the resulting class. If HaveRC is
2805 // nullptr, assume that it is still unset.
2806 auto getCommonRC =
2807 [](const TargetRegisterClass *HaveRC,
2808 const TargetRegisterClass *NewRC) -> const TargetRegisterClass * {
2809 if (HaveRC == nullptr || HaveRC == NewRC)
2810 return NewRC;
2811 // Different classes, both non-null. Pick the more general one.
2812 if (HaveRC->hasSubClassEq(NewRC))
2813 return HaveRC;
2814 if (NewRC->hasSubClassEq(HaveRC))
2815 return NewRC;
2816 return nullptr;
2817 };
2818
2819 // Scan all blocks in the function. Check all occurrences of frame indexes,
2820 // and collect relevant information.
2821 for (auto &B : MF) {
2822 std::map<int,IndexType> LastStore, LastLoad;
2823 auto P = BlockIndexes.emplace(&B, HexagonBlockRanges::InstrIndexMap(B));
2824 auto &IndexMap = P.first->second;
2825 LLVM_DEBUG(dbgs() << "Index map for " << printMBBReference(B) << "\n"
2826 << IndexMap << '\n');
2827
2828 for (auto &In : B) {
2829 // Debug instructions do not generate any code, and their operands
2830 // (including frame index operands) must not affect the decisions made
2831 // by this optimization.
2832 if (In.isDebugInstr())
2833 continue;
2834 int LFI, SFI;
2835 bool Load = HII.isLoadFromStackSlot(In, LFI) && !HII.isPredicated(In);
2836 bool Store = HII.isStoreToStackSlot(In, SFI) && !HII.isPredicated(In);
2837 if (Load && Store) {
2838 // If it's both a load and a store, then we won't handle it.
2839 BadFIs.insert(LFI);
2840 BadFIs.insert(SFI);
2841 continue;
2842 }
2843 // Check for register classes of the register used as the source for
2844 // the store, and the register used as the destination for the load.
2845 // Also, only accept base+imm_offset addressing modes. Other addressing
2846 // modes can have side-effects (post-increments, etc.). For stack
2847 // slots they are very unlikely, so there is not much loss due to
2848 // this restriction.
2849 if (Load || Store) {
2850 int TFI = Load ? LFI : SFI;
2851 unsigned AM = HII.getAddrMode(In);
2852 SlotInfo &SI = FIRangeMap[TFI];
2853 bool Bad = (AM != HexagonII::BaseImmOffset);
2854 if (!Bad) {
2855 // If the addressing mode is ok, check the register class.
2856 unsigned OpNum = Load ? 0 : 2;
2857 auto *RC = HII.getRegClass(In.getDesc(), OpNum);
2858 RC = getCommonRC(SI.RC, RC);
2859 if (RC == nullptr)
2860 Bad = true;
2861 else
2862 SI.RC = RC;
2863 }
2864 if (!Bad) {
2865 // Check sizes.
2866 unsigned S = HII.getMemAccessSize(In);
2867 if (SI.Size != 0 && SI.Size != S)
2868 Bad = true;
2869 else
2870 SI.Size = S;
2871 }
2872 if (!Bad) {
2873 for (auto *Mo : In.memoperands()) {
2874 if (!Mo->isVolatile() && !Mo->isAtomic())
2875 continue;
2876 Bad = true;
2877 break;
2878 }
2879 }
2880 if (Bad)
2881 BadFIs.insert(TFI);
2882 }
2883
2884 // Locate uses of frame indices.
2885 for (unsigned i = 0, n = In.getNumOperands(); i < n; ++i) {
2886 const MachineOperand &Op = In.getOperand(i);
2887 if (!Op.isFI())
2888 continue;
2889 int FI = Op.getIndex();
2890 // Make sure that the following operand is an immediate and that
2891 // it is 0. This is the offset in the stack object.
2892 if (i+1 >= n || !In.getOperand(i+1).isImm() ||
2893 In.getOperand(i+1).getImm() != 0)
2894 BadFIs.insert(FI);
2895 if (BadFIs.count(FI))
2896 continue;
2897
2898 IndexType Index = IndexMap.getIndex(&In);
2899 auto &LS = LastStore[FI];
2900 auto &LL = LastLoad[FI];
2901 if (Load) {
2902 if (LS == IndexType::None)
2903 LS = IndexType::Entry;
2904 LL = Index;
2905 } else if (Store) {
2906 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
2907 if (LS != IndexType::None)
2908 RL.add(LS, LL, false, false);
2909 else if (LL != IndexType::None)
2910 RL.add(IndexType::Entry, LL, false, false);
2911 LL = IndexType::None;
2912 LS = Index;
2913 } else {
2914 BadFIs.insert(FI);
2915 }
2916 }
2917 }
2918
2919 for (auto &I : LastLoad) {
2920 IndexType LL = I.second;
2921 if (LL == IndexType::None)
2922 continue;
2923 auto &RL = FIRangeMap[I.first].Map[&B];
2924 IndexType &LS = LastStore[I.first];
2925 if (LS != IndexType::None)
2926 RL.add(LS, LL, false, false);
2927 else
2928 RL.add(IndexType::Entry, LL, false, false);
2929 LS = IndexType::None;
2930 }
2931 for (auto &I : LastStore) {
2932 IndexType LS = I.second;
2933 if (LS == IndexType::None)
2934 continue;
2935 auto &RL = FIRangeMap[I.first].Map[&B];
2936 RL.add(LS, IndexType::None, false, false);
2937 }
2938 }
2939
2940 LLVM_DEBUG({
2941 for (auto &P : FIRangeMap) {
2942 dbgs() << "fi#" << P.first;
2943 if (BadFIs.count(P.first))
2944 dbgs() << " (bad)";
2945 dbgs() << " RC: ";
2946 if (P.second.RC != nullptr)
2947 dbgs() << HRI.getRegClassName(P.second.RC) << '\n';
2948 else
2949 dbgs() << "<null>\n";
2950 for (auto &R : P.second.Map)
2951 dbgs() << " " << printMBBReference(*R.first) << " { " << R.second
2952 << "}\n";
2953 }
2954 });
2955
2956 // When a slot is loaded from in a block without being stored to in the
2957 // same block, it is live-on-entry to this block. To avoid CFG analysis,
2958 // consider this slot to be live-on-exit from all blocks.
2959 SmallSet<int,4> LoxFIs;
2960
2961 std::map<MachineBasicBlock*,std::vector<int>> BlockFIMap;
2962
2963 for (auto &P : FIRangeMap) {
2964 // P = pair(FI, map: BB->RangeList)
2965 if (BadFIs.count(P.first))
2966 continue;
2967 for (auto &B : MF) {
2968 auto F = P.second.Map.find(&B);
2969 // F = pair(BB, RangeList)
2970 if (F == P.second.Map.end() || F->second.empty())
2971 continue;
2972 HexagonBlockRanges::IndexRange &IR = F->second.front();
2973 if (IR.start() == IndexType::Entry)
2974 LoxFIs.insert(P.first);
2975 BlockFIMap[&B].push_back(P.first);
2976 }
2977 }
2978
2979 LLVM_DEBUG({
2980 dbgs() << "Block-to-FI map (* -- live-on-exit):\n";
2981 for (auto &P : BlockFIMap) {
2982 auto &FIs = P.second;
2983 if (FIs.empty())
2984 continue;
2985 dbgs() << " " << printMBBReference(*P.first) << ": {";
2986 for (auto I : FIs) {
2987 dbgs() << " fi#" << I;
2988 if (LoxFIs.count(I))
2989 dbgs() << '*';
2990 }
2991 dbgs() << " }\n";
2992 }
2993 });
2994
2995#ifndef NDEBUG
2996 bool HasOptLimit = HST.getCLOpts().spill_opt_max.has_value();
2997#endif
2998
2999 // eliminate loads, when all loads eliminated, eliminate all stores.
3000 for (auto &B : MF) {
3001 auto F = BlockIndexes.find(&B);
3002 assert(F != BlockIndexes.end());
3003 HexagonBlockRanges::InstrIndexMap &IM = F->second;
3004 HexagonBlockRanges::RegToRangeMap LM = HBR.computeLiveMap(IM);
3005 HexagonBlockRanges::RegToRangeMap DM = HBR.computeDeadMap(IM, LM);
3006 LLVM_DEBUG(dbgs() << printMBBReference(B) << " dead map\n"
3007 << HexagonBlockRanges::PrintRangeMap(DM, HRI));
3008
3009 for (auto FI : BlockFIMap[&B]) {
3010 if (BadFIs.count(FI))
3011 continue;
3012 LLVM_DEBUG(dbgs() << "Working on fi#" << FI << '\n');
3013 HexagonBlockRanges::RangeList &RL = FIRangeMap[FI].Map[&B];
3014 for (auto &Range : RL) {
3015 LLVM_DEBUG(dbgs() << "--Examining range:" << RL << '\n');
3016 if (!IndexType::isInstr(Range.start()) ||
3017 !IndexType::isInstr(Range.end()))
3018 continue;
3019 MachineInstr &SI = *IM.getInstr(Range.start());
3020 MachineInstr &EI = *IM.getInstr(Range.end());
3021 assert(SI.mayStore() && "Unexpected start instruction");
3022 assert(EI.mayLoad() && "Unexpected end instruction");
3023 MachineOperand &SrcOp = SI.getOperand(2);
3024
3025 HexagonBlockRanges::RegisterRef SrcRR = { SrcOp.getReg(),
3026 SrcOp.getSubReg() };
3027 auto *RC = HII.getRegClass(SI.getDesc(), 2);
3028 // The this-> is needed to unconfuse MSVC.
3029 Register FoundR = this->findPhysReg(MF, Range, IM, DM, RC);
3030 LLVM_DEBUG(dbgs() << "Replacement reg:" << printReg(FoundR, &HRI)
3031 << '\n');
3032 if (FoundR == 0)
3033 continue;
3034#ifndef NDEBUG
3035 if (HasOptLimit) {
3036 if (SpillOptCount >= *HST.getCLOpts().spill_opt_max)
3037 return;
3038 SpillOptCount++;
3039 }
3040#endif
3041
3042 // Generate the copy-in: "FoundR = COPY SrcR" at the store location.
3043 MachineBasicBlock::iterator StartIt = SI.getIterator(), NextIt;
3044 MachineInstr *CopyIn = nullptr;
3045 if (SrcRR.Reg != FoundR || SrcRR.Sub != 0) {
3046 const DebugLoc &DL = SI.getDebugLoc();
3047 CopyIn = BuildMI(B, StartIt, DL, HII.get(TargetOpcode::COPY), FoundR)
3048 .add(SrcOp);
3049 }
3050
3051 ++StartIt;
3052 // Check if this is a last store and the FI is live-on-exit.
3053 if (LoxFIs.count(FI) && (&Range == &RL.back())) {
3054 // Update store's source register.
3055 if (unsigned SR = SrcOp.getSubReg())
3056 SrcOp.setReg(HRI.getSubReg(FoundR, SR));
3057 else
3058 SrcOp.setReg(FoundR);
3059 SrcOp.setSubReg(0);
3060 // We are keeping this register live.
3061 SrcOp.setIsKill(false);
3062 } else {
3063 B.erase(&SI);
3064 IM.replaceInstr(&SI, CopyIn);
3065 }
3066
3067 auto EndIt = std::next(EI.getIterator());
3068 for (auto It = StartIt; It != EndIt; It = NextIt) {
3069 MachineInstr &MI = *It;
3070 NextIt = std::next(It);
3071 int TFI;
3072 if (!HII.isLoadFromStackSlot(MI, TFI) || TFI != FI)
3073 continue;
3074 Register DstR = MI.getOperand(0).getReg();
3075 assert(MI.getOperand(0).getSubReg() == 0);
3076 MachineInstr *CopyOut = nullptr;
3077 if (DstR != FoundR) {
3078 DebugLoc DL = MI.getDebugLoc();
3079 unsigned MemSize = HII.getMemAccessSize(MI);
3080 assert(HII.getAddrMode(MI) == HexagonII::BaseImmOffset);
3081 unsigned CopyOpc = TargetOpcode::COPY;
3082 if (HII.isSignExtendingLoad(MI))
3083 CopyOpc = (MemSize == 1) ? Hexagon::A2_sxtb : Hexagon::A2_sxth;
3084 else if (HII.isZeroExtendingLoad(MI))
3085 CopyOpc = (MemSize == 1) ? Hexagon::A2_zxtb : Hexagon::A2_zxth;
3086 CopyOut = BuildMI(B, It, DL, HII.get(CopyOpc), DstR)
3087 .addReg(FoundR, getKillRegState(&MI == &EI));
3088 }
3089 IM.replaceInstr(&MI, CopyOut);
3090 B.erase(It);
3091 }
3092
3093 // Update the dead map.
3094 HexagonBlockRanges::RegisterRef FoundRR = { FoundR, 0 };
3095 for (auto RR : HexagonBlockRanges::expandToSubRegs(FoundRR, MRI, HRI))
3096 DM[RR].subtract(Range);
3097 } // for Range in range list
3098 }
3099 }
3100}
3101
3102void HexagonFrameLowering::expandAlloca(MachineInstr *AI, MachineFunction &MF,
3103 const HexagonInstrInfo &HII,
3104 Register SP, unsigned CF) const {
3105 MachineBasicBlock &MB = *AI->getParent();
3106 DebugLoc DL = AI->getDebugLoc();
3107 unsigned A = AI->getOperand(2).getImm();
3108
3109 MachineOperand &RdOp = AI->getOperand(0);
3110 MachineOperand &RsOp = AI->getOperand(1);
3111 Register Rd = RdOp.getReg(), Rs = RsOp.getReg();
3112
3113 auto &HST = MF.getSubtarget<HexagonSubtarget>();
3114 auto *TLI = HST.getTargetLowering();
3115 bool NeedsProbing = TLI->hasInlineStackProbe(MF);
3116
3117 if (!NeedsProbing) {
3118 // Have
3119 // Rd = alloca Rs, #A
3120 //
3121 // If Rs and Rd are different registers, use this sequence:
3122 // Rd = sub(r29, Rs)
3123 // r29 = sub(r29, Rs)
3124 // Rd = and(Rd, #-A) ; if necessary
3125 // r29 = and(r29, #-A) ; if necessary
3126 // Rd = add(Rd, #CF) ; CF size aligned to at most A
3127 // otherwise, do
3128 // Rd = sub(r29, Rs)
3129 // Rd = and(Rd, #-A) ; if necessary
3130 // r29 = Rd
3131 // Rd = add(Rd, #CF) ; CF size aligned to at most A
3132
3133 // Rd = sub(r29, Rs)
3134 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd).addReg(SP).addReg(Rs);
3135 if (Rs != Rd) {
3136 // r29 = sub(r29, Rs)
3137 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), SP).addReg(SP).addReg(Rs);
3138 }
3139 if (A > 8) {
3140 // Rd = and(Rd, #-A)
3141 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
3142 .addReg(Rd)
3143 .addImm(-int64_t(A));
3144 if (Rs != Rd)
3145 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), SP)
3146 .addReg(SP)
3147 .addImm(-int64_t(A));
3148 }
3149 if (Rs == Rd) {
3150 // r29 = Rd
3151 BuildMI(MB, AI, DL, HII.get(TargetOpcode::COPY), SP).addReg(Rd);
3152 }
3153 if (CF > 0) {
3154 // Rd = add(Rd, #CF)
3155 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_addi), Rd).addReg(Rd).addImm(CF);
3156 }
3157 return;
3158 }
3159
3160 // Stack probing for dynamic allocation. The size Rs is a runtime value
3161 // so the probe loop is always emitted; it is a no-op when Rs is small.
3162 //
3163 // Compute the target SP into Rd (with optional alignment), then probe
3164 // each page on the way down:
3165 //
3166 // Rd = sub(r29, Rs)
3167 // [Rd = and(Rd, #-A)] ; if alignment > 8
3168 // LoopMBB:
3169 // r29 = add(r29, #-ProbeSize)
3170 // memw(r29+#0) = #0
3171 // p0 = cmp.gtu(r29, Rd)
3172 // if (p0.new) jump:t LoopMBB
3173 // ExitMBB:
3174 // r29 = Rd
3175 // [Rd = add(Rd, #CF)] ; if CF > 0
3176 // <rest of original block>
3177 //
3178 // Rd holds the exact (aligned) target SP throughout the loop, so the
3179 // final "r29 = Rd" snaps SP to the correct value even when Rs is not
3180 // a multiple of ProbeSize.
3181
3182 Align StackAlign = getStackAlign();
3183 unsigned ProbeSize = TLI->getStackProbeSize(MF, StackAlign);
3185
3186 // Emit target-SP computation into Rd before splitting the block.
3187 // Rd = sub(r29, Rs)
3188 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_sub), Rd)
3189 .addReg(SP)
3190 .addReg(Rs)
3191 .setMIFlags(Flags);
3192 if (A > 8) {
3193 // Rd = and(Rd, #-A)
3194 BuildMI(MB, AI, DL, HII.get(Hexagon::A2_andir), Rd)
3195 .addReg(Rd)
3196 .addImm(-int64_t(A))
3197 .setMIFlags(Flags);
3198 }
3199
3200 // Split the block: everything after AI goes into ExitMBB.
3202 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(MB.getBasicBlock());
3203 MF.insert(InsertPt, LoopMBB);
3204 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MB.getBasicBlock());
3205 MF.insert(InsertPt, ExitMBB);
3206
3207 // Move instructions after AI (exclusive) into ExitMBB.
3208 ExitMBB->splice(ExitMBB->end(), &MB, std::next(AI->getIterator()), MB.end());
3209 ExitMBB->transferSuccessorsAndUpdatePHIs(&MB);
3210
3211 // LoopMBB: probe each page.
3212 // r29 = add(r29, #-ProbeSize)
3213 // memw(r29+#0) = #0
3214 // p0 = cmp.gtu(r29, Rd)
3215 // if (p0.new) jump:t LoopMBB
3216 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::A2_addi), Hexagon::R29)
3217 .addReg(Hexagon::R29)
3218 .addImm(-int(ProbeSize))
3219 .setMIFlags(Flags);
3220
3221 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::S4_storeiri_io))
3222 .addReg(Hexagon::R29)
3223 .addImm(0)
3224 .addImm(0)
3225 .setMIFlags(Flags);
3226
3227 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::C2_cmpgtu),
3228 Hexagon::P0)
3229 .addReg(Hexagon::R29)
3230 .addReg(Rd)
3231 .setMIFlags(Flags);
3232
3233 BuildMI(*LoopMBB, LoopMBB->end(), DL, HII.get(Hexagon::J2_jumpt))
3234 .addReg(Hexagon::P0)
3235 .addMBB(LoopMBB)
3236 .setMIFlags(Flags);
3237
3238 // ExitMBB: snap SP to exact target, then apply CF offset to Rd.
3239 // r29 = Rd
3240 // [Rd = add(Rd, #CF)]
3241 MachineBasicBlock::iterator ExitIt = ExitMBB->begin();
3242 BuildMI(*ExitMBB, ExitIt, DL, HII.get(Hexagon::A2_tfr), Hexagon::R29)
3243 .addReg(Rd)
3244 .setMIFlags(Flags);
3245 if (CF > 0) {
3246 BuildMI(*ExitMBB, ExitIt, DL, HII.get(Hexagon::A2_addi), Rd)
3247 .addReg(Rd)
3248 .addImm(CF)
3249 .setMIFlags(Flags);
3250 }
3251
3252 // Wire up CFG edges.
3253 MB.addSuccessor(LoopMBB);
3254 LoopMBB->addSuccessor(LoopMBB);
3255 LoopMBB->addSuccessor(ExitMBB);
3256
3257 // Recompute live-ins for the new blocks. AI is still in MB at this
3258 // point; the caller erases it after expandAlloca returns.
3259 fullyRecomputeLiveIns({ExitMBB, LoopMBB});
3260}
3261
3263 const MachineFrameInfo &MFI = MF.getFrameInfo();
3264 if (!MFI.hasVarSizedObjects())
3265 return false;
3266 // Do not check for max stack object alignment here, because the stack
3267 // may not be complete yet. Assume that we will need PS_aligna if there
3268 // are variable-sized objects.
3269 return true;
3270}
3271
3272/// Adds all callee-saved registers as implicit uses or defs to the
3273/// instruction.
3274void HexagonFrameLowering::addCalleeSaveRegistersAsImpOperand(MachineInstr *MI,
3275 const CSIVect &CSI, bool IsDef, bool IsKill) const {
3276 // Add the callee-saved registers as implicit uses.
3277 for (auto &R : CSI)
3278 MI->addOperand(MachineOperand::CreateReg(R.getReg(), IsDef, true, IsKill));
3279}
3280
3281/// Determine whether the callee-saved register saves and restores should
3282/// be generated via inline code. If this function returns "true", inline
3283/// code will be generated. If this function returns "false", additional
3284/// checks are performed, which may still lead to the inline code.
3285bool HexagonFrameLowering::shouldInlineCSR(const MachineFunction &MF,
3286 const CSIVect &CSI) const {
3288 return true;
3290 return true;
3291 if (!hasFP(MF))
3292 return true;
3293 if (!isOptSize(MF) && !isMinSize(MF))
3295 return true;
3296
3297 // Check if CSI only has double registers, and if the registers form
3298 // a contiguous block starting from D8.
3299 BitVector Regs(Hexagon::NUM_TARGET_REGS);
3300 for (const CalleeSavedInfo &I : CSI) {
3301 MCRegister R = I.getReg();
3302 if (!Hexagon::DoubleRegsRegClass.contains(R))
3303 return true;
3304 Regs[R] = true;
3305 }
3306 int F = Regs.find_first();
3307 if (F != Hexagon::D8)
3308 return true;
3309 while (F >= 0) {
3310 int N = Regs.find_next(F);
3311 if (N >= 0 && N != F+1)
3312 return true;
3313 F = N;
3314 }
3315
3316 return false;
3317}
3318
3319bool HexagonFrameLowering::useSpillFunction(const MachineFunction &MF,
3320 const CSIVect &CSI) const {
3321 if (shouldInlineCSR(MF, CSI))
3322 return false;
3323 unsigned NumCSI = CSI.size();
3324 if (NumCSI <= 1)
3325 return false;
3326
3327 // Every spill stub saves the whole range starting at R16
3328 // (__save_r16_through_rNN), so a stub whose range reached the shadow call
3329 // stack pointer register would spill it along with the real callee-saved
3330 // registers - and since the SCS register is reserved it is absent from CSI,
3331 // so the stub's fixed frame layout would not match the one the compiler
3332 // assigned.
3333 //
3334 // shouldInlineCSR() above already makes this unreachable: it only lets a
3335 // stub through when CSI is a contiguous run of double registers starting at
3336 // D8, and reserving the SCS register always breaks the double it belongs
3337 // to, leaving its partner in CSI as a lone single register. This is a
3338 // cheap safety net so the guarantee does not rest on that reasoning alone.
3339 if (MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) {
3340 const auto &HST = MF.getSubtarget<HexagonSubtarget>();
3341 Register MaxReg = getMaxCalleeSavedReg(CSI, *HST.getRegisterInfo());
3342 if (HST.getSCSPReg().id() <= MaxReg.id())
3343 return false;
3344 }
3345
3346 const auto &CLOpts = MF.getSubtarget<HexagonSubtarget>().getCLOpts();
3347 unsigned Threshold = isOptSize(MF) ? CLOpts.spill_func_threshold_os
3348 : CLOpts.spill_func_threshold;
3349 return Threshold < NumCSI;
3350}
3351
3352bool HexagonFrameLowering::useRestoreFunction(const MachineFunction &MF,
3353 const CSIVect &CSI) const {
3354 if (shouldInlineCSR(MF, CSI))
3355 return false;
3356 // The returning restore stubs do jumpr r31, this breaks ShadowCallStack:
3357 if (MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack))
3358 return false;
3359 // The restore functions do a bit more than just restoring registers.
3360 // The non-returning versions will go back directly to the caller's
3361 // caller, others will clean up the stack frame in preparation for
3362 // a tail call. Using them can still save code size even if only one
3363 // register is getting restores. Make the decision based on -Oz:
3364 // using -Os will use inline restore for a single register.
3365 if (isMinSize(MF))
3366 return true;
3367 unsigned NumCSI = CSI.size();
3368 if (NumCSI <= 1)
3369 return false;
3370
3371 const auto &CLOpts = MF.getSubtarget<HexagonSubtarget>().getCLOpts();
3372 unsigned Threshold = isOptSize(MF) ? CLOpts.spill_func_threshold_os - 1
3373 : CLOpts.spill_func_threshold;
3374 return Threshold < NumCSI;
3375}
3376
3377bool HexagonFrameLowering::mayOverflowFrameOffset(MachineFunction &MF) const {
3378 unsigned StackSize = MF.getFrameInfo().estimateStackSize(MF);
3379 auto &HST = MF.getSubtarget<HexagonSubtarget>();
3380 // A fairly simplistic guess as to whether a potential load/store to a
3381 // stack location could require an extra register.
3382 if (HST.useHVXOps() && StackSize > 256)
3383 return true;
3384
3385 // Check if the function has store-immediate instructions that access
3386 // the stack. Since the offset field is not extendable, if the stack
3387 // size exceeds the offset limit (6 bits, shifted), the stores will
3388 // require a new base register.
3389 bool HasImmStack = false;
3390 unsigned MinLS = ~0u; // Log_2 of the memory access size.
3391
3392 for (const MachineBasicBlock &B : MF) {
3393 for (const MachineInstr &MI : B) {
3394 unsigned LS = 0;
3395 switch (MI.getOpcode()) {
3396 case Hexagon::S4_storeirit_io:
3397 case Hexagon::S4_storeirif_io:
3398 case Hexagon::S4_storeiri_io:
3399 ++LS;
3400 [[fallthrough]];
3401 case Hexagon::S4_storeirht_io:
3402 case Hexagon::S4_storeirhf_io:
3403 case Hexagon::S4_storeirh_io:
3404 ++LS;
3405 [[fallthrough]];
3406 case Hexagon::S4_storeirbt_io:
3407 case Hexagon::S4_storeirbf_io:
3408 case Hexagon::S4_storeirb_io:
3409 if (MI.getOperand(0).isFI())
3410 HasImmStack = true;
3411 MinLS = std::min(MinLS, LS);
3412 break;
3413 }
3414 }
3415 }
3416
3417 if (HasImmStack)
3418 return !isUInt<6>(StackSize >> MinLS);
3419
3420 return false;
3421}
3422
3423namespace {
3424// Struct used by orderFrameObjects to help sort the stack objects.
3425struct HexagonFrameSortingObject {
3426 bool IsValid = false;
3427 unsigned Index = 0; // Index of Object into MFI list.
3428 unsigned Size = 0;
3429 Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
3430};
3431
3432struct HexagonFrameSortingComparator {
3433 inline bool operator()(const HexagonFrameSortingObject &A,
3434 const HexagonFrameSortingObject &B) const {
3435 return std::make_tuple(!A.IsValid, A.ObjectAlignment, A.Size) <
3436 std::make_tuple(!B.IsValid, B.ObjectAlignment, B.Size);
3437 }
3438};
3439} // namespace
3440
3441// Sort objects on the stack by alignment value and then by size to minimize
3442// padding.
3444 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3445
3446 if (ObjectsToAllocate.empty())
3447 return;
3448
3449 const MachineFrameInfo &MFI = MF.getFrameInfo();
3450 int NObjects = ObjectsToAllocate.size();
3451
3452 // Create an array of all MFI objects.
3454 MFI.getObjectIndexEnd());
3455
3456 for (int i = 0, j = 0, e = MFI.getObjectIndexEnd(); i < e && j != NObjects;
3457 ++i) {
3458 if (i != ObjectsToAllocate[j])
3459 continue;
3460 j++;
3461
3462 // A variable size object has size equal to 0. Since Hexagon sets
3463 // getUseLocalStackAllocationBlock() to true, a local block is allocated
3464 // earlier. This case is not handled here for now.
3465 int Size = MFI.getObjectSize(i);
3466 if (Size == 0)
3467 return;
3468
3469 SortingObjects[i].IsValid = true;
3470 SortingObjects[i].Index = i;
3471 SortingObjects[i].Size = Size;
3472 SortingObjects[i].ObjectAlignment = MFI.getObjectAlign(i);
3473 }
3474
3475 // Sort objects by alignment and then by size.
3476 llvm::stable_sort(SortingObjects, HexagonFrameSortingComparator());
3477
3478 // Modify the original list to represent the final order.
3479 int i = NObjects;
3480 for (auto &Obj : SortingObjects) {
3481 if (i == 0)
3482 break;
3483 ObjectsToAllocate[--i] = Obj.Index;
3484 }
3485}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
uint64_t uint64_t
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file defines the DenseMap class.
This file contains constants used for implementing Dwarf debug support.
static MachineInstr * getReturn(MachineBasicBlock &MBB)
Returns the "return" instruction from this block, or nullptr if there isn't any.
static bool isOptNone(const MachineFunction &MF)
static std::optional< MachineBasicBlock::iterator > findCFILocation(MachineBasicBlock &B)
static bool enableAllocFrameElim(const MachineFunction &MF)
static const char * getSpillFunctionFor(Register MaxReg, SpillKind SpillType, bool Stkchk=false)
static bool hasReturn(const MachineBasicBlock &MBB)
Returns true if MBB contains an instruction that returns.
static bool needToReserveScavengingSpillSlots(MachineFunction &MF, const HexagonRegisterInfo &HRI, const TargetRegisterClass *RC)
Returns true if there are no caller-saved registers available in class RC.
static bool isOptSize(const MachineFunction &MF)
static Register getMax32BitSubRegister(Register Reg, const TargetRegisterInfo &TRI, bool hireg=true)
Map a register pair Reg to the subregister that has the greater "number", i.e.
static bool needsStackFrame(const MachineBasicBlock &MBB, const BitVector &CSR, const HexagonRegisterInfo &HRI)
Checks if the basic block contains any instruction that needs a stack frame to be already in place.
static bool hasTailCall(const MachineBasicBlock &MBB)
Returns true if MBB has a machine instructions that indicates a tail call in the block.
static Register getMaxCalleeSavedReg(ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo &TRI)
Returns the callee saved register with the largest id in the vector.
static bool isMinSize(const MachineFunction &MF)
static bool containsHLXObject(const llvm::HexagonSubtarget &HST, llvm::Type *Ty)
static unsigned SpillOptCount
static void dump_registers(BitVector &Regs, const TargetRegisterInfo &TRI)
static void emitSCSPrologue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
static bool isRestoreCall(unsigned Opc)
static void emitSCSEpilogue(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL)
IRTranslator LLVM IR MI
Legalize the Machine IR a function s Machine IR
Definition Legalizer.cpp:85
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the 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
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:325
Helper class for creating CFI instructions and inserting them into MIR.
void buildEscape(StringRef Bytes, StringRef Comment="") const
void buildRestore(MCRegister Reg) 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
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
MaybeAlign getFnStackAlign() const
Return the stack alignment for the function.
Definition Function.h:446
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void replaceInstr(MachineInstr *OldMI, MachineInstr *NewMI)
IndexType getIndex(MachineInstr *MI) const
MachineInstr * getInstr(IndexType Idx) const
void add(IndexType Start, IndexType End, bool Fixed, bool TiedEnd)
void insertCFIInstructions(MachineFunction &MF) const
bool hasFPImpl(const MachineFunction &MF) const override
bool enableCalleeSaveSkip(const MachineFunction &MF) const override
Returns true if the target can safely skip saving callee-saved registers for noreturn nounwind functi...
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
Perform most of the PEI work here:
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &ObjectsToAllocate) const override
Order the symbols in the local stack frame.
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const override
Replace a StackProbe stub (if any) with the actual probe code inline.
const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const override
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
bool needsAligna(const MachineFunction &MF) const
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Store the specified register of the given register class to the specified stack frame index.
const HexagonRegisterInfo & getRegisterInfo() const
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Load the specified register of the given register class from the specified stack frame index.
Hexagon target-specific information for each MachineFunction.
bool isEHReturnCalleeSaveReg(Register Reg) const
const MCPhysReg * getCallerSavedRegs(const MachineFunction *MF, const TargetRegisterClass *RC) const
bool isTypeForHLX(Type *VecTy) const
const HexagonInstrInfo * getInstrInfo() const override
const HexagonFrameLowering * getFrameLowering() const override
const HexagonRegisterInfo * getRegisterInfo() const override
const HexagonOptions & getCLOpts() const
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:630
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:672
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:758
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_same_value Current value of Register is the same as in the previous frame.
Definition MCDwarf.h:741
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
Describe properties that are true of each instruction in the target description file.
MCRegAliasIterator enumerates all registers aliasing Reg.
unsigned getID() const
getID() - Return the register class ID number.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
MachineInstrBundleIterator< const MachineInstr > const_iterator
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
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< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
bool dominates(const MachineInstr *A, const MachineInstr *B) const
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
bool hasCalls() const
Return true if the current function has any function calls.
Align getMaxAlign() const
Return alignment of this function's frame.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
LLVM_ABI int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
uint8_t getStackID(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Properties which a MachineFunction may have at a given point in time.
unsigned addFrameInst(const MCCFIInstruction &Inst)
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.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
Function & getFunction()
Return the LLVM function that this machine code represents.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
BasicBlockListType::iterator iterator
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
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 & addCFIIndex(unsigned CFIIndex) 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 & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool isReturn(QueryType Type=AnyInBundle) const
const MachineBasicBlock * getParent() const
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
mop_range implicit_operands()
LLVM_ABI void copyImplicitOps(MachineFunction &MF, const MachineInstr &MI)
Copy implicit register operands from specified instruction to this instruction.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
int64_t getImm() const
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
LLVM_ABI MachineBasicBlock * findNearestCommonDominator(ArrayRef< MachineBasicBlock * > Blocks) const
Returns the nearest common dominator of the given blocks.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
A vector that has set insertion semantics.
Definition SetVector.h:57
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM_ABI std::string lower() const
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...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
const TargetRegisterInfo & getRegisterInfo() const
virtual bool hasInlineStackProbe(const MachineFunction &MF) const
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
bool isPositionIndependent() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr MCPhysReg SP
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:316
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Dead
Unused definition.
@ Kill
The last use of a register.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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:1762
@ Off
Use window algorithm after SMS algorithm fails.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
FunctionPass * createHexagonCallFrameInformation()
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
@ Default
-O2, -Os, -Oz
Definition CodeGen.h:283
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RegState getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition LEB128.h:24
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:1788
MaybeAlign getStackAlign(const Function &F, unsigned Index)
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
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.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
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:82
static RegisterSet expandToSubRegs(RegisterRef R, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
std::map< RegisterRef, RangeList > RegToRangeMap
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135