LLVM 22.0.0git
PrologEpilogInserter.cpp
Go to the documentation of this file.
1//===- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass is responsible for finalizing the functions frame layout, saving
10// callee saved registers, and for emitting prolog & epilog code for the
11// function.
12//
13// This pass must be run after register allocation. After this pass is
14// executed, it is illegal to construct MO_FrameIndex operands.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
38#include "llvm/CodeGen/PEI.h"
46#include "llvm/IR/Attributes.h"
47#include "llvm/IR/CallingConv.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/LLVMContext.h"
53#include "llvm/Pass.h"
55#include "llvm/Support/Debug.h"
61#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <limits>
65#include <utility>
66#include <vector>
67
68using namespace llvm;
69
70#define DEBUG_TYPE "prologepilog"
71
73
74STATISTIC(NumLeafFuncWithSpills, "Number of leaf functions with CSRs");
75STATISTIC(NumFuncSeen, "Number of functions seen in PEI");
76
77
78namespace {
79
80class PEIImpl {
81 RegScavenger *RS = nullptr;
82
83 // Save and Restore blocks of the current function. Typically there is a
84 // single save block, unless Windows EH funclets are involved.
85 MBBVector SaveBlocks;
86 MBBVector RestoreBlocks;
87
88 // Flag to control whether to use the register scavenger to resolve
89 // frame index materialization registers. Set according to
90 // TRI->requiresFrameIndexScavenging() for the current function.
91 bool FrameIndexVirtualScavenging = false;
92
93 // Flag to control whether the scavenger should be passed even though
94 // FrameIndexVirtualScavenging is used.
95 bool FrameIndexEliminationScavenging = false;
96
97 // Emit remarks.
99
100 void calculateCallFrameInfo(MachineFunction &MF);
101 void calculateSaveRestoreBlocks(MachineFunction &MF);
102 void spillCalleeSavedRegs(MachineFunction &MF);
103
104 void calculateFrameObjectOffsets(MachineFunction &MF);
105 void replaceFrameIndices(MachineFunction &MF);
106 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
107 int &SPAdj);
108 // Frame indices in debug values are encoded in a target independent
109 // way with simply the frame index and offset rather than any
110 // target-specific addressing mode.
111 bool replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
112 unsigned OpIdx, int SPAdj = 0);
113 // Does same as replaceFrameIndices but using the backward MIR walk and
114 // backward register scavenger walk.
115 void replaceFrameIndicesBackward(MachineFunction &MF);
116 void replaceFrameIndicesBackward(MachineBasicBlock *BB, MachineFunction &MF,
117 int &SPAdj);
118
119 void insertPrologEpilogCode(MachineFunction &MF);
120 void insertZeroCallUsedRegs(MachineFunction &MF);
121
122public:
123 PEIImpl(MachineOptimizationRemarkEmitter *ORE) : ORE(ORE) {}
124 bool run(MachineFunction &MF);
125};
126
127class PEILegacy : public MachineFunctionPass {
128public:
129 static char ID;
130
131 PEILegacy() : MachineFunctionPass(ID) {
133 }
134
135 void getAnalysisUsage(AnalysisUsage &AU) const override;
136
137 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
138 /// frame indexes with appropriate references.
139 bool runOnMachineFunction(MachineFunction &MF) override;
140};
141
142} // end anonymous namespace
143
144char PEILegacy::ID = 0;
145
147
148INITIALIZE_PASS_BEGIN(PEILegacy, DEBUG_TYPE, "Prologue/Epilogue Insertion",
149 false, false)
154 "Prologue/Epilogue Insertion & Frame Finalization", false,
155 false)
156
158 return new PEILegacy();
159}
160
161STATISTIC(NumBytesStackSpace,
162 "Number of bytes used for stack in all functions");
163
164void PEILegacy::getAnalysisUsage(AnalysisUsage &AU) const {
165 AU.setPreservesCFG();
170}
171
172/// StackObjSet - A set of stack object indexes
174
177
178/// Stash DBG_VALUEs that describe parameters and which are placed at the start
179/// of the block. Later on, after the prologue code has been emitted, the
180/// stashed DBG_VALUEs will be reinserted at the start of the block.
182 SavedDbgValuesMap &EntryDbgValues) {
184
185 for (auto &MI : MBB) {
186 if (!MI.isDebugInstr())
187 break;
188 if (!MI.isDebugValue() || !MI.getDebugVariable()->isParameter())
189 continue;
190 if (any_of(MI.debug_operands(),
191 [](const MachineOperand &MO) { return MO.isFI(); })) {
192 // We can only emit valid locations for frame indices after the frame
193 // setup, so do not stash away them.
194 FrameIndexValues.push_back(&MI);
195 continue;
196 }
197 const DILocalVariable *Var = MI.getDebugVariable();
198 const DIExpression *Expr = MI.getDebugExpression();
199 auto Overlaps = [Var, Expr](const MachineInstr *DV) {
200 return Var == DV->getDebugVariable() &&
201 Expr->fragmentsOverlap(DV->getDebugExpression());
202 };
203 // See if the debug value overlaps with any preceding debug value that will
204 // not be stashed. If that is the case, then we can't stash this value, as
205 // we would then reorder the values at reinsertion.
206 if (llvm::none_of(FrameIndexValues, Overlaps))
207 EntryDbgValues[&MBB].push_back(&MI);
208 }
209
210 // Remove stashed debug values from the block.
211 if (auto It = EntryDbgValues.find(&MBB); It != EntryDbgValues.end())
212 for (auto *MI : It->second)
213 MI->removeFromParent();
214}
215
216bool PEIImpl::run(MachineFunction &MF) {
217 NumFuncSeen++;
218 const Function &F = MF.getFunction();
219 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
220 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
221
222 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
223 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
224
225 // Spill frame pointer and/or base pointer registers if they are clobbered.
226 // It is placed before call frame instruction elimination so it will not mess
227 // with stack arguments.
228 TFI->spillFPBP(MF);
229
230 // Calculate the MaxCallFrameSize value for the function's frame
231 // information. Also eliminates call frame pseudo instructions.
232 calculateCallFrameInfo(MF);
233
234 // Determine placement of CSR spill/restore code and prolog/epilog code:
235 // place all spills in the entry block, all restores in return blocks.
236 calculateSaveRestoreBlocks(MF);
237
238 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
239 SavedDbgValuesMap EntryDbgValues;
240 for (MachineBasicBlock *SaveBlock : SaveBlocks)
241 stashEntryDbgValues(*SaveBlock, EntryDbgValues);
242
243 // Handle CSR spilling and restoring, for targets that need it.
245 spillCalleeSavedRegs(MF);
246
247 // Allow the target machine to make final modifications to the function
248 // before the frame layout is finalized.
250
251 // Calculate actual frame offsets for all abstract stack objects...
252 calculateFrameObjectOffsets(MF);
253
254 // Add prolog and epilog code to the function. This function is required
255 // to align the stack frame as necessary for any stack variables or
256 // called functions. Because of this, calculateCalleeSavedRegisters()
257 // must be called before this function in order to set the AdjustsStack
258 // and MaxCallFrameSize variables.
259 if (!F.hasFnAttribute(Attribute::Naked))
260 insertPrologEpilogCode(MF);
261
262 // Reinsert stashed debug values at the start of the entry blocks.
263 for (auto &I : EntryDbgValues)
264 I.first->insert(I.first->begin(), I.second.begin(), I.second.end());
265
266 // Allow the target machine to make final modifications to the function
267 // before the frame layout is finalized.
269
270 // Replace all MO_FrameIndex operands with physical register references
271 // and actual offsets.
272 if (TFI->needsFrameIndexResolution(MF)) {
273 // Allow the target to determine this after knowing the frame size.
274 FrameIndexEliminationScavenging =
275 (RS && !FrameIndexVirtualScavenging) ||
276 TRI->requiresFrameIndexReplacementScavenging(MF);
277
278 if (TRI->eliminateFrameIndicesBackwards())
279 replaceFrameIndicesBackward(MF);
280 else
281 replaceFrameIndices(MF);
282 }
283
284 // If register scavenging is needed, as we've enabled doing it as a
285 // post-pass, scavenge the virtual registers that frame index elimination
286 // inserted.
287 if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
289
290 // Warn on stack size when we exceeds the given limit.
291 MachineFrameInfo &MFI = MF.getFrameInfo();
292 uint64_t StackSize = MFI.getStackSize();
293
294 uint64_t Threshold = TFI->getStackThreshold();
295 if (MF.getFunction().hasFnAttribute("warn-stack-size")) {
296 bool Failed = MF.getFunction()
297 .getFnAttribute("warn-stack-size")
299 .getAsInteger(10, Threshold);
300 // Verifier should have caught this.
301 assert(!Failed && "Invalid warn-stack-size fn attr value");
302 (void)Failed;
303 }
304 uint64_t UnsafeStackSize = MFI.getUnsafeStackSize();
305 if (MF.getFunction().hasFnAttribute(Attribute::SafeStack))
306 StackSize += UnsafeStackSize;
307
308 if (StackSize > Threshold) {
309 DiagnosticInfoStackSize DiagStackSize(F, StackSize, Threshold, DS_Warning);
310 F.getContext().diagnose(DiagStackSize);
311 int64_t SpillSize = 0;
312 for (int Idx = MFI.getObjectIndexBegin(), End = MFI.getObjectIndexEnd();
313 Idx != End; ++Idx) {
314 if (MFI.isSpillSlotObjectIndex(Idx))
315 SpillSize += MFI.getObjectSize(Idx);
316 }
317
318 [[maybe_unused]] float SpillPct =
319 static_cast<float>(SpillSize) / static_cast<float>(StackSize);
321 dbgs() << formatv("{0}/{1} ({3:P}) spills, {2}/{1} ({4:P}) variables",
322 SpillSize, StackSize, StackSize - SpillSize, SpillPct,
323 1.0f - SpillPct));
324 if (UnsafeStackSize != 0) {
325 LLVM_DEBUG(dbgs() << formatv(", {0}/{2} ({1:P}) unsafe stack",
326 UnsafeStackSize,
327 static_cast<float>(UnsafeStackSize) /
328 static_cast<float>(StackSize),
329 StackSize));
330 }
331 LLVM_DEBUG(dbgs() << "\n");
332 }
333
334 ORE->emit([&]() {
335 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize",
337 &MF.front())
338 << ore::NV("NumStackBytes", StackSize)
339 << " stack bytes in function '"
340 << ore::NV("Function", MF.getFunction().getName()) << "'";
341 });
342
343 // Emit any remarks implemented for the target, based on final frame layout.
344 TFI->emitRemarks(MF, ORE);
345
346 delete RS;
347 SaveBlocks.clear();
348 RestoreBlocks.clear();
349 MFI.clearSavePoints();
350 MFI.clearRestorePoints();
351 return true;
352}
353
354/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
355/// frame indexes with appropriate references.
356bool PEILegacy::runOnMachineFunction(MachineFunction &MF) {
357 MachineOptimizationRemarkEmitter *ORE =
358 &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
359 return PEIImpl(ORE).run(MF);
360}
361
362PreservedAnalyses
367 if (!PEIImpl(&ORE).run(MF))
368 return PreservedAnalyses::all();
369
372 .preserve<MachineDominatorTreeAnalysis>()
373 .preserve<MachineLoopAnalysis>();
374}
375
376/// Calculate the MaxCallFrameSize variable for the function's frame
377/// information and eliminate call frame pseudo instructions.
378void PEIImpl::calculateCallFrameInfo(MachineFunction &MF) {
381 MachineFrameInfo &MFI = MF.getFrameInfo();
382
383 // Get the function call frame set-up and tear-down instruction opcode
384 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
385 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
386
387 // Early exit for targets which have no call frame setup/destroy pseudo
388 // instructions.
389 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
390 return;
391
392 // (Re-)Compute the MaxCallFrameSize.
393 [[maybe_unused]] uint64_t MaxCFSIn =
395 std::vector<MachineBasicBlock::iterator> FrameSDOps;
396 MFI.computeMaxCallFrameSize(MF, &FrameSDOps);
397 assert(MFI.getMaxCallFrameSize() <= MaxCFSIn &&
398 "Recomputing MaxCFS gave a larger value.");
399 assert((FrameSDOps.empty() || MF.getFrameInfo().adjustsStack()) &&
400 "AdjustsStack not set in presence of a frame pseudo instruction.");
401
402 if (TFI->canSimplifyCallFramePseudos(MF)) {
403 // If call frames are not being included as part of the stack frame, and
404 // the target doesn't indicate otherwise, remove the call frame pseudos
405 // here. The sub/add sp instruction pairs are still inserted, but we don't
406 // need to track the SP adjustment for frame index elimination.
407 for (MachineBasicBlock::iterator I : FrameSDOps)
408 TFI->eliminateCallFramePseudoInstr(MF, *I->getParent(), I);
409
410 // We can't track the call frame size after call frame pseudos have been
411 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
412 for (MachineBasicBlock &MBB : MF)
413 MBB.setCallFrameSize(0);
414 }
415}
416
417/// Compute the sets of entry and return blocks for saving and restoring
418/// callee-saved registers, and placing prolog and epilog code.
419void PEIImpl::calculateSaveRestoreBlocks(MachineFunction &MF) {
420 const MachineFrameInfo &MFI = MF.getFrameInfo();
421 // Even when we do not change any CSR, we still want to insert the
422 // prologue and epilogue of the function.
423 // So set the save points for those.
424
425 // Use the points found by shrink-wrapping, if any.
426 if (!MFI.getSavePoints().empty()) {
427 assert(MFI.getSavePoints().size() == 1 &&
428 "Multiple save points are not yet supported!");
429 const auto &SavePoint = *MFI.getSavePoints().begin();
430 SaveBlocks.push_back(SavePoint.first);
431 assert(MFI.getRestorePoints().size() == 1 &&
432 "Multiple restore points are not yet supported!");
433 const auto &RestorePoint = *MFI.getRestorePoints().begin();
434 MachineBasicBlock *RestoreBlock = RestorePoint.first;
435 // If RestoreBlock does not have any successor and is not a return block
436 // then the end point is unreachable and we do not need to insert any
437 // epilogue.
438 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
439 RestoreBlocks.push_back(RestoreBlock);
440 return;
441 }
442
443 // Save refs to entry and return blocks.
444 SaveBlocks.push_back(&MF.front());
445 for (MachineBasicBlock &MBB : MF) {
446 if (MBB.isEHFuncletEntry())
447 SaveBlocks.push_back(&MBB);
448 if (MBB.isReturnBlock())
449 RestoreBlocks.push_back(&MBB);
450 }
451}
452
454 const BitVector &SavedRegs) {
455 if (SavedRegs.empty())
456 return;
457
458 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
459 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
460 BitVector CSMask(SavedRegs.size());
461
462 for (unsigned i = 0; CSRegs[i]; ++i)
463 CSMask.set(CSRegs[i]);
464
465 std::vector<CalleeSavedInfo> CSI;
466 for (unsigned i = 0; CSRegs[i]; ++i) {
467 unsigned Reg = CSRegs[i];
468 if (SavedRegs.test(Reg)) {
469 bool SavedSuper = false;
470 for (const MCPhysReg &SuperReg : RegInfo->superregs(Reg)) {
471 // Some backends set all aliases for some registers as saved, such as
472 // Mips's $fp, so they appear in SavedRegs but not CSRegs.
473 if (SavedRegs.test(SuperReg) && CSMask.test(SuperReg)) {
474 SavedSuper = true;
475 break;
476 }
477 }
478
479 if (!SavedSuper)
480 CSI.push_back(CalleeSavedInfo(Reg));
481 }
482 }
483
484 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
485 MachineFrameInfo &MFI = F.getFrameInfo();
486 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
487 // If target doesn't implement this, use generic code.
488
489 if (CSI.empty())
490 return; // Early exit if no callee saved registers are modified!
491
492 unsigned NumFixedSpillSlots;
493 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
494 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
495
496 // Now that we know which registers need to be saved and restored, allocate
497 // stack slots for them.
498 for (auto &CS : CSI) {
499 // If the target has spilled this register to another register or already
500 // handled it , we don't need to allocate a stack slot.
501 if (CS.isSpilledToReg())
502 continue;
503
504 MCRegister Reg = CS.getReg();
505 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
506
507 int FrameIdx;
508 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
509 CS.setFrameIdx(FrameIdx);
510 continue;
511 }
512
513 // Check to see if this physreg must be spilled to a particular stack slot
514 // on this target.
515 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
516 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
517 FixedSlot->Reg != Reg)
518 ++FixedSlot;
519
520 unsigned Size = RegInfo->getSpillSize(*RC);
521 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
522 // Nope, just spill it anywhere convenient.
523 Align Alignment = RegInfo->getSpillAlign(*RC);
524 // We may not be able to satisfy the desired alignment specification of
525 // the TargetRegisterClass if the stack alignment is smaller. Use the
526 // min.
527 Alignment = std::min(Alignment, TFI->getStackAlign());
528 FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
529 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
530 } else {
531 // Spill it to the stack where we must.
532 FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
533 }
534
535 CS.setFrameIdx(FrameIdx);
536 }
537 }
538
539 MFI.setCalleeSavedInfo(CSI);
540}
541
542/// Helper function to update the liveness information for the callee-saved
543/// registers.
545 MachineFrameInfo &MFI = MF.getFrameInfo();
546 // Visited will contain all the basic blocks that are in the region
547 // where the callee saved registers are alive:
548 // - Anything that is not Save or Restore -> LiveThrough.
549 // - Save -> LiveIn.
550 // - Restore -> LiveOut.
551 // The live-out is not attached to the block, so no need to keep
552 // Restore in this set.
555 MachineBasicBlock *Entry = &MF.front();
556
557 assert(MFI.getSavePoints().size() < 2 &&
558 "Multiple save points not yet supported!");
559 MachineBasicBlock *Save = MFI.getSavePoints().empty()
560 ? nullptr
561 : (*MFI.getSavePoints().begin()).first;
562
563 if (!Save)
564 Save = Entry;
565
566 if (Entry != Save) {
567 WorkList.push_back(Entry);
568 Visited.insert(Entry);
569 }
570 Visited.insert(Save);
571
572 assert(MFI.getRestorePoints().size() < 2 &&
573 "Multiple restore points not yet supported!");
574 MachineBasicBlock *Restore = MFI.getRestorePoints().empty()
575 ? nullptr
576 : (*MFI.getRestorePoints().begin()).first;
577 if (Restore)
578 // By construction Restore cannot be visited, otherwise it
579 // means there exists a path to Restore that does not go
580 // through Save.
581 WorkList.push_back(Restore);
582
583 while (!WorkList.empty()) {
584 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
585 // By construction, the region that is after the save point is
586 // dominated by the Save and post-dominated by the Restore.
587 if (CurBB == Save && Save != Restore)
588 continue;
589 // Enqueue all the successors not already visited.
590 // Those are by construction either before Save or after Restore.
591 for (MachineBasicBlock *SuccBB : CurBB->successors())
592 if (Visited.insert(SuccBB).second)
593 WorkList.push_back(SuccBB);
594 }
595
596 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
597
599 for (const CalleeSavedInfo &I : CSI) {
600 for (MachineBasicBlock *MBB : Visited) {
601 MCRegister Reg = I.getReg();
602 // Add the callee-saved register as live-in.
603 // It's killed at the spill.
604 if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
605 MBB->addLiveIn(Reg);
606 }
607 // If callee-saved register is spilled to another register rather than
608 // spilling to stack, the destination register has to be marked as live for
609 // each MBB between the prologue and epilogue so that it is not clobbered
610 // before it is reloaded in the epilogue. The Visited set contains all
611 // blocks outside of the region delimited by prologue/epilogue.
612 if (I.isSpilledToReg()) {
613 for (MachineBasicBlock &MBB : MF) {
614 if (Visited.count(&MBB))
615 continue;
616 MCRegister DstReg = I.getDstReg();
617 if (!MBB.isLiveIn(DstReg))
618 MBB.addLiveIn(DstReg);
619 }
620 }
621 }
622}
623
624/// Insert spill code for the callee-saved registers used in the function.
625static void insertCSRSaves(MachineBasicBlock &SaveBlock,
627 MachineFunction &MF = *SaveBlock.getParent();
631
632 MachineBasicBlock::iterator I = SaveBlock.begin();
633 if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
634 for (const CalleeSavedInfo &CS : CSI) {
635 TFI->spillCalleeSavedRegister(SaveBlock, I, CS, TII, TRI);
636 }
637 }
638}
639
640/// Insert restore code for the callee-saved registers used in the function.
641static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
642 std::vector<CalleeSavedInfo> &CSI) {
643 MachineFunction &MF = *RestoreBlock.getParent();
647
648 // Restore all registers immediately before the return and any
649 // terminators that precede it.
651
652 if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
653 for (const CalleeSavedInfo &CI : reverse(CSI)) {
654 TFI->restoreCalleeSavedRegister(RestoreBlock, I, CI, TII, TRI);
655 }
656 }
657}
658
659void PEIImpl::spillCalleeSavedRegs(MachineFunction &MF) {
660 // We can't list this requirement in getRequiredProperties because some
661 // targets (WebAssembly) use virtual registers past this point, and the pass
662 // pipeline is set up without giving the passes a chance to look at the
663 // TargetMachine.
664 // FIXME: Find a way to express this in getRequiredProperties.
665 assert(MF.getProperties().hasNoVRegs());
666
667 const Function &F = MF.getFunction();
668 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
669 MachineFrameInfo &MFI = MF.getFrameInfo();
670
671 // Determine which of the registers in the callee save list should be saved.
672 BitVector SavedRegs;
673 TFI->determineCalleeSaves(MF, SavedRegs, RS);
674
675 // Assign stack slots for any callee-saved registers that must be spilled.
676 assignCalleeSavedSpillSlots(MF, SavedRegs);
677
678 // Add the code to save and restore the callee saved registers.
679 if (!F.hasFnAttribute(Attribute::Naked)) {
680 MFI.setCalleeSavedInfoValid(true);
681
682 std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
683
684 // Fill SavePoints and RestorePoints with CalleeSavedRegisters
685 if (!MFI.getSavePoints().empty()) {
686 SaveRestorePoints SaveRestorePts;
687 for (const auto &SavePoint : MFI.getSavePoints())
688 SaveRestorePts.insert({SavePoint.first, CSI});
689 MFI.setSavePoints(std::move(SaveRestorePts));
690
691 SaveRestorePts.clear();
692 for (const auto &RestorePoint : MFI.getRestorePoints())
693 SaveRestorePts.insert({RestorePoint.first, CSI});
694 MFI.setRestorePoints(std::move(SaveRestorePts));
695 }
696
697 if (!CSI.empty()) {
698 if (!MFI.hasCalls())
699 NumLeafFuncWithSpills++;
700
701 for (MachineBasicBlock *SaveBlock : SaveBlocks)
702 insertCSRSaves(*SaveBlock, CSI);
703
704 // Update the live-in information of all the blocks up to the save point.
705 updateLiveness(MF);
706
707 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
708 insertCSRRestores(*RestoreBlock, CSI);
709 }
710 }
711}
712
713/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
714static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
715 bool StackGrowsDown, int64_t &Offset,
716 Align &MaxAlign) {
717 // If the stack grows down, add the object size to find the lowest address.
718 if (StackGrowsDown)
719 Offset += MFI.getObjectSize(FrameIdx);
720
721 Align Alignment = MFI.getObjectAlign(FrameIdx);
722
723 // If the alignment of this object is greater than that of the stack, then
724 // increase the stack alignment to match.
725 MaxAlign = std::max(MaxAlign, Alignment);
726
727 // Adjust to alignment boundary.
728 Offset = alignTo(Offset, Alignment);
729
730 if (StackGrowsDown) {
731 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
732 << "]\n");
733 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
734 } else {
735 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
736 << "]\n");
737 MFI.setObjectOffset(FrameIdx, Offset);
738 Offset += MFI.getObjectSize(FrameIdx);
739 }
740}
741
742/// Compute which bytes of fixed and callee-save stack area are unused and keep
743/// track of them in StackBytesFree.
745 bool StackGrowsDown,
746 int64_t FixedCSEnd,
747 BitVector &StackBytesFree) {
748 // Avoid undefined int64_t -> int conversion below in extreme case.
749 if (FixedCSEnd > std::numeric_limits<int>::max())
750 return;
751
752 StackBytesFree.resize(FixedCSEnd, true);
753
754 SmallVector<int, 16> AllocatedFrameSlots;
755 // Add fixed objects.
756 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
757 // StackSlot scavenging is only implemented for the default stack.
759 AllocatedFrameSlots.push_back(i);
760 // Add callee-save objects if there are any.
761 for (int i = MFI.getObjectIndexBegin(); i < MFI.getObjectIndexEnd(); i++)
762 if (MFI.isCalleeSavedObjectIndex(i) &&
764 AllocatedFrameSlots.push_back(i);
765
766 for (int i : AllocatedFrameSlots) {
767 // These are converted from int64_t, but they should always fit in int
768 // because of the FixedCSEnd check above.
769 int ObjOffset = MFI.getObjectOffset(i);
770 int ObjSize = MFI.getObjectSize(i);
771 int ObjStart, ObjEnd;
772 if (StackGrowsDown) {
773 // ObjOffset is negative when StackGrowsDown is true.
774 ObjStart = -ObjOffset - ObjSize;
775 ObjEnd = -ObjOffset;
776 } else {
777 ObjStart = ObjOffset;
778 ObjEnd = ObjOffset + ObjSize;
779 }
780 // Ignore fixed holes that are in the previous stack frame.
781 if (ObjEnd > 0)
782 StackBytesFree.reset(ObjStart, ObjEnd);
783 }
784}
785
786/// Assign frame object to an unused portion of the stack in the fixed stack
787/// object range. Return true if the allocation was successful.
788static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
789 bool StackGrowsDown, Align MaxAlign,
790 BitVector &StackBytesFree) {
791 if (MFI.isVariableSizedObjectIndex(FrameIdx))
792 return false;
793
794 if (StackBytesFree.none()) {
795 // clear it to speed up later scavengeStackSlot calls to
796 // StackBytesFree.none()
797 StackBytesFree.clear();
798 return false;
799 }
800
801 Align ObjAlign = MFI.getObjectAlign(FrameIdx);
802 if (ObjAlign > MaxAlign)
803 return false;
804
805 int64_t ObjSize = MFI.getObjectSize(FrameIdx);
806 int FreeStart;
807 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
808 FreeStart = StackBytesFree.find_next(FreeStart)) {
809
810 // Check that free space has suitable alignment.
811 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
812 if (alignTo(ObjStart, ObjAlign) != ObjStart)
813 continue;
814
815 if (FreeStart + ObjSize > StackBytesFree.size())
816 return false;
817
818 bool AllBytesFree = true;
819 for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
820 if (!StackBytesFree.test(FreeStart + Byte)) {
821 AllBytesFree = false;
822 break;
823 }
824 if (AllBytesFree)
825 break;
826 }
827
828 if (FreeStart == -1)
829 return false;
830
831 if (StackGrowsDown) {
832 int ObjStart = -(FreeStart + ObjSize);
833 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
834 << ObjStart << "]\n");
835 MFI.setObjectOffset(FrameIdx, ObjStart);
836 } else {
837 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
838 << FreeStart << "]\n");
839 MFI.setObjectOffset(FrameIdx, FreeStart);
840 }
841
842 StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
843 return true;
844}
845
846/// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
847/// those required to be close to the Stack Protector) to stack offsets.
848static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
849 SmallSet<int, 16> &ProtectedObjs,
850 MachineFrameInfo &MFI, bool StackGrowsDown,
851 int64_t &Offset, Align &MaxAlign) {
852
853 for (int i : UnassignedObjs) {
854 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
855 ProtectedObjs.insert(i);
856 }
857}
858
859/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
860/// abstract stack objects.
861void PEIImpl::calculateFrameObjectOffsets(MachineFunction &MF) {
862 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
863
864 bool StackGrowsDown =
866
867 // Loop over all of the stack objects, assigning sequential addresses...
868 MachineFrameInfo &MFI = MF.getFrameInfo();
869
870 // Start at the beginning of the local area.
871 // The Offset is the distance from the stack top in the direction
872 // of stack growth -- so it's always nonnegative.
873 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
874 if (StackGrowsDown)
875 LocalAreaOffset = -LocalAreaOffset;
876 assert(LocalAreaOffset >= 0
877 && "Local area offset should be in direction of stack growth");
878 int64_t Offset = LocalAreaOffset;
879
880#ifdef EXPENSIVE_CHECKS
881 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
882 if (!MFI.isDeadObjectIndex(i) &&
884 assert(MFI.getObjectAlign(i) <= MFI.getMaxAlign() &&
885 "MaxAlignment is invalid");
886#endif
887
888 // If there are fixed sized objects that are preallocated in the local area,
889 // non-fixed objects can't be allocated right at the start of local area.
890 // Adjust 'Offset' to point to the end of last fixed sized preallocated
891 // object.
892 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
893 // Only allocate objects on the default stack.
895 continue;
896
897 int64_t FixedOff;
898 if (StackGrowsDown) {
899 // The maximum distance from the stack pointer is at lower address of
900 // the object -- which is given by offset. For down growing stack
901 // the offset is negative, so we negate the offset to get the distance.
902 FixedOff = -MFI.getObjectOffset(i);
903 } else {
904 // The maximum distance from the start pointer is at the upper
905 // address of the object.
906 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
907 }
908 if (FixedOff > Offset) Offset = FixedOff;
909 }
910
911 Align MaxAlign = MFI.getMaxAlign();
912 // First assign frame offsets to stack objects that are used to spill
913 // callee saved registers.
914 auto AllFIs = seq(MFI.getObjectIndexBegin(), MFI.getObjectIndexEnd());
915 for (int FI : reverse_conditionally(AllFIs, /*Reverse=*/!StackGrowsDown)) {
916 // Only allocate objects on the default stack.
917 if (!MFI.isCalleeSavedObjectIndex(FI) ||
919 continue;
920
921 // TODO: should this just be if (MFI.isDeadObjectIndex(FI))
922 if (!StackGrowsDown && MFI.isDeadObjectIndex(FI))
923 continue;
924
925 AdjustStackOffset(MFI, FI, StackGrowsDown, Offset, MaxAlign);
926 }
927
928 assert(MaxAlign == MFI.getMaxAlign() &&
929 "MFI.getMaxAlign should already account for all callee-saved "
930 "registers without a fixed stack slot");
931
932 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
933 // stack area.
934 int64_t FixedCSEnd = Offset;
935
936 // Make sure the special register scavenging spill slot is closest to the
937 // incoming stack pointer if a frame pointer is required and is closer
938 // to the incoming rather than the final stack pointer.
939 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
940 bool EarlyScavengingSlots = TFI.allocateScavengingFrameIndexesNearIncomingSP(MF);
941 if (RS && EarlyScavengingSlots) {
942 SmallVector<int, 2> SFIs;
944 for (int SFI : SFIs)
945 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
946 }
947
948 // FIXME: Once this is working, then enable flag will change to a target
949 // check for whether the frame is large enough to want to use virtual
950 // frame index registers. Functions which don't want/need this optimization
951 // will continue to use the existing code path.
953 Align Alignment = MFI.getLocalFrameMaxAlign();
954
955 // Adjust to alignment boundary.
956 Offset = alignTo(Offset, Alignment);
957
958 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
959
960 // Resolve offsets for objects in the local block.
961 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
962 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
963 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
964 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
965 << "]\n");
966 MFI.setObjectOffset(Entry.first, FIOffset);
967 }
968 // Allocate the local block
969 Offset += MFI.getLocalFrameSize();
970
971 MaxAlign = std::max(Alignment, MaxAlign);
972 }
973
974 // Retrieve the Exception Handler registration node.
975 int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
976 if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
977 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
978
979 // Make sure that the stack protector comes before the local variables on the
980 // stack.
981 SmallSet<int, 16> ProtectedObjs;
982 if (MFI.hasStackProtectorIndex()) {
983 int StackProtectorFI = MFI.getStackProtectorIndex();
984 StackObjSet LargeArrayObjs;
985 StackObjSet SmallArrayObjs;
986 StackObjSet AddrOfObjs;
987
988 // If we need a stack protector, we need to make sure that
989 // LocalStackSlotPass didn't already allocate a slot for it.
990 // If we are told to use the LocalStackAllocationBlock, the stack protector
991 // is expected to be already pre-allocated.
992 if (MFI.getStackID(StackProtectorFI) != TargetStackID::Default) {
993 // If the stack protector isn't on the default stack then it's up to the
994 // target to set the stack offset.
995 assert(MFI.getObjectOffset(StackProtectorFI) != 0 &&
996 "Offset of stack protector on non-default stack expected to be "
997 "already set.");
999 "Stack protector on non-default stack expected to not be "
1000 "pre-allocated by LocalStackSlotPass.");
1001 } else if (!MFI.getUseLocalStackAllocationBlock()) {
1002 AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset,
1003 MaxAlign);
1004 } else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex())) {
1006 "Stack protector not pre-allocated by LocalStackSlotPass.");
1007 }
1008
1009 // Assign large stack objects first.
1010 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1012 continue;
1013 if (MFI.isCalleeSavedObjectIndex(i))
1014 continue;
1015 if (RS && RS->isScavengingFrameIndex((int)i))
1016 continue;
1017 if (MFI.isDeadObjectIndex(i))
1018 continue;
1019 if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
1020 continue;
1021 // Only allocate objects on the default stack.
1022 if (MFI.getStackID(i) != TargetStackID::Default)
1023 continue;
1024
1025 switch (MFI.getObjectSSPLayout(i)) {
1027 continue;
1029 SmallArrayObjs.insert(i);
1030 continue;
1032 AddrOfObjs.insert(i);
1033 continue;
1035 LargeArrayObjs.insert(i);
1036 continue;
1037 }
1038 llvm_unreachable("Unexpected SSPLayoutKind.");
1039 }
1040
1041 // We expect **all** the protected stack objects to be pre-allocated by
1042 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
1043 // of them, we may end up messing up the expected order of the objects.
1045 !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
1046 AddrOfObjs.empty()))
1047 llvm_unreachable("Found protected stack objects not pre-allocated by "
1048 "LocalStackSlotPass.");
1049
1050 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1051 Offset, MaxAlign);
1052 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1053 Offset, MaxAlign);
1054 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
1055 Offset, MaxAlign);
1056 }
1057
1058 SmallVector<int, 8> ObjectsToAllocate;
1059
1060 // Then prepare to assign frame offsets to stack objects that are not used to
1061 // spill callee saved registers.
1062 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1064 continue;
1065 if (MFI.isCalleeSavedObjectIndex(i))
1066 continue;
1067 if (RS && RS->isScavengingFrameIndex((int)i))
1068 continue;
1069 if (MFI.isDeadObjectIndex(i))
1070 continue;
1071 if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
1072 continue;
1073 if (ProtectedObjs.count(i))
1074 continue;
1075 // Only allocate objects on the default stack.
1076 if (MFI.getStackID(i) != TargetStackID::Default)
1077 continue;
1078
1079 // Add the objects that we need to allocate to our working set.
1080 ObjectsToAllocate.push_back(i);
1081 }
1082
1083 // Allocate the EH registration node first if one is present.
1084 if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1085 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
1086 MaxAlign);
1087
1088 // Give the targets a chance to order the objects the way they like it.
1089 if (MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1091 TFI.orderFrameObjects(MF, ObjectsToAllocate);
1092
1093 // Keep track of which bytes in the fixed and callee-save range are used so we
1094 // can use the holes when allocating later stack objects. Only do this if
1095 // stack protector isn't being used and the target requests it and we're
1096 // optimizing.
1097 BitVector StackBytesFree;
1098 if (!ObjectsToAllocate.empty() &&
1099 MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1101 computeFreeStackSlots(MFI, StackGrowsDown, FixedCSEnd, StackBytesFree);
1102
1103 // Now walk the objects and actually assign base offsets to them.
1104 for (auto &Object : ObjectsToAllocate)
1105 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
1106 StackBytesFree))
1107 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign);
1108
1109 // Make sure the special register scavenging spill slot is closest to the
1110 // stack pointer.
1111 if (RS && !EarlyScavengingSlots) {
1112 SmallVector<int, 2> SFIs;
1113 RS->getScavengingFrameIndices(SFIs);
1114 for (int SFI : SFIs)
1115 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
1116 }
1117
1119 // If we have reserved argument space for call sites in the function
1120 // immediately on entry to the current function, count it as part of the
1121 // overall stack size.
1122 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
1123 Offset += MFI.getMaxCallFrameSize();
1124
1125 // Round up the size to a multiple of the alignment. If the function has
1126 // any calls or alloca's, align to the target's StackAlignment value to
1127 // ensure that the callee's frame or the alloca data is suitably aligned;
1128 // otherwise, for leaf functions, align to the TransientStackAlignment
1129 // value.
1130 Align StackAlign;
1131 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
1132 (RegInfo->hasStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
1133 StackAlign = TFI.getStackAlign();
1134 else
1135 StackAlign = TFI.getTransientStackAlign();
1136
1137 // If the frame pointer is eliminated, all frame offsets will be relative to
1138 // SP not FP. Align to MaxAlign so this works.
1139 StackAlign = std::max(StackAlign, MaxAlign);
1140 int64_t OffsetBeforeAlignment = Offset;
1141 Offset = alignTo(Offset, StackAlign);
1142
1143 // If we have increased the offset to fulfill the alignment constrants,
1144 // then the scavenging spill slots may become harder to reach from the
1145 // stack pointer, float them so they stay close.
1146 if (StackGrowsDown && OffsetBeforeAlignment != Offset && RS &&
1147 !EarlyScavengingSlots) {
1148 SmallVector<int, 2> SFIs;
1149 RS->getScavengingFrameIndices(SFIs);
1150 LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs()
1151 << "Adjusting emergency spill slots!\n";);
1152 int64_t Delta = Offset - OffsetBeforeAlignment;
1153 for (int SFI : SFIs) {
1155 << "Adjusting offset of emergency spill slot #" << SFI
1156 << " from " << MFI.getObjectOffset(SFI););
1157 MFI.setObjectOffset(SFI, MFI.getObjectOffset(SFI) - Delta);
1158 LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";);
1159 }
1160 }
1161 }
1162
1163 // Update frame info to pretend that this is part of the stack...
1164 int64_t StackSize = Offset - LocalAreaOffset;
1165 MFI.setStackSize(StackSize);
1166 NumBytesStackSpace += StackSize;
1167}
1168
1169/// insertPrologEpilogCode - Scan the function for modified callee saved
1170/// registers, insert spill code for these callee saved registers, then add
1171/// prolog and epilog code to the function.
1172void PEIImpl::insertPrologEpilogCode(MachineFunction &MF) {
1173 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1174
1175 // Add prologue to the function...
1176 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1177 TFI.emitPrologue(MF, *SaveBlock);
1178
1179 // Add epilogue to restore the callee-save registers in each exiting block.
1180 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1181 TFI.emitEpilogue(MF, *RestoreBlock);
1182
1183 // Zero call used registers before restoring callee-saved registers.
1184 insertZeroCallUsedRegs(MF);
1185
1186 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1187 TFI.inlineStackProbe(MF, *SaveBlock);
1188
1189 // Emit additional code that is required to support segmented stacks, if
1190 // we've been asked for it. This, when linked with a runtime with support
1191 // for segmented stacks (libgcc is one), will result in allocating stack
1192 // space in small chunks instead of one large contiguous block.
1193 if (MF.shouldSplitStack()) {
1194 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1195 TFI.adjustForSegmentedStacks(MF, *SaveBlock);
1196 }
1197
1198 // Emit additional code that is required to explicitly handle the stack in
1199 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1200 // approach is rather similar to that of Segmented Stacks, but it uses a
1201 // different conditional check and another BIF for allocating more stack
1202 // space.
1203 if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
1204 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1205 TFI.adjustForHiPEPrologue(MF, *SaveBlock);
1206}
1207
1208/// insertZeroCallUsedRegs - Zero out call used registers.
1209void PEIImpl::insertZeroCallUsedRegs(MachineFunction &MF) {
1210 const Function &F = MF.getFunction();
1211
1212 if (!F.hasFnAttribute("zero-call-used-regs"))
1213 return;
1214
1215 using namespace ZeroCallUsedRegs;
1216
1217 ZeroCallUsedRegsKind ZeroRegsKind =
1218 StringSwitch<ZeroCallUsedRegsKind>(
1219 F.getFnAttribute("zero-call-used-regs").getValueAsString())
1220 .Case("skip", ZeroCallUsedRegsKind::Skip)
1221 .Case("used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg)
1222 .Case("used-gpr", ZeroCallUsedRegsKind::UsedGPR)
1223 .Case("used-arg", ZeroCallUsedRegsKind::UsedArg)
1224 .Case("used", ZeroCallUsedRegsKind::Used)
1225 .Case("all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg)
1226 .Case("all-gpr", ZeroCallUsedRegsKind::AllGPR)
1227 .Case("all-arg", ZeroCallUsedRegsKind::AllArg)
1228 .Case("all", ZeroCallUsedRegsKind::All);
1229
1230 if (ZeroRegsKind == ZeroCallUsedRegsKind::Skip)
1231 return;
1232
1233 const bool OnlyGPR = static_cast<unsigned>(ZeroRegsKind) & ONLY_GPR;
1234 const bool OnlyUsed = static_cast<unsigned>(ZeroRegsKind) & ONLY_USED;
1235 const bool OnlyArg = static_cast<unsigned>(ZeroRegsKind) & ONLY_ARG;
1236
1237 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1238 const BitVector AllocatableSet(TRI.getAllocatableSet(MF));
1239
1240 // Mark all used registers.
1241 BitVector UsedRegs(TRI.getNumRegs());
1242 if (OnlyUsed)
1243 for (const MachineBasicBlock &MBB : MF)
1244 for (const MachineInstr &MI : MBB) {
1245 // skip debug instructions
1246 if (MI.isDebugInstr())
1247 continue;
1248
1249 for (const MachineOperand &MO : MI.operands()) {
1250 if (!MO.isReg())
1251 continue;
1252
1253 MCRegister Reg = MO.getReg();
1254 if (AllocatableSet[Reg.id()] && !MO.isImplicit() &&
1255 (MO.isDef() || MO.isUse()))
1256 UsedRegs.set(Reg.id());
1257 }
1258 }
1259
1260 // Get a list of registers that are used.
1261 BitVector LiveIns(TRI.getNumRegs());
1262 for (const MachineBasicBlock::RegisterMaskPair &LI : MF.front().liveins())
1263 LiveIns.set(LI.PhysReg);
1264
1265 BitVector RegsToZero(TRI.getNumRegs());
1266 for (MCRegister Reg : AllocatableSet.set_bits()) {
1267 // Skip over fixed registers.
1268 if (TRI.isFixedRegister(MF, Reg))
1269 continue;
1270
1271 // Want only general purpose registers.
1272 if (OnlyGPR && !TRI.isGeneralPurposeRegister(MF, Reg))
1273 continue;
1274
1275 // Want only used registers.
1276 if (OnlyUsed && !UsedRegs[Reg.id()])
1277 continue;
1278
1279 // Want only registers used for arguments.
1280 if (OnlyArg) {
1281 if (OnlyUsed) {
1282 if (!LiveIns[Reg.id()])
1283 continue;
1284 } else if (!TRI.isArgumentRegister(MF, Reg)) {
1285 continue;
1286 }
1287 }
1288
1289 RegsToZero.set(Reg.id());
1290 }
1291
1292 // Don't clear registers that are live when leaving the function.
1293 for (const MachineBasicBlock &MBB : MF)
1294 for (const MachineInstr &MI : MBB.terminators()) {
1295 if (!MI.isReturn())
1296 continue;
1297
1298 for (const auto &MO : MI.operands()) {
1299 if (!MO.isReg())
1300 continue;
1301
1302 MCRegister Reg = MO.getReg();
1303 if (!Reg)
1304 continue;
1305
1306 // This picks up sibling registers (e.q. %al -> %ah).
1307 // FIXME: Mixing physical registers and register units is likely a bug.
1308 for (MCRegUnit Unit : TRI.regunits(Reg))
1309 RegsToZero.reset(static_cast<unsigned>(Unit));
1310
1311 for (MCPhysReg SReg : TRI.sub_and_superregs_inclusive(Reg))
1312 RegsToZero.reset(SReg);
1313 }
1314 }
1315
1316 // Don't need to clear registers that are used/clobbered by terminating
1317 // instructions.
1318 for (const MachineBasicBlock &MBB : MF) {
1319 if (!MBB.isReturnBlock())
1320 continue;
1321
1324 ++I) {
1325 for (const MachineOperand &MO : I->operands()) {
1326 if (!MO.isReg())
1327 continue;
1328
1329 MCRegister Reg = MO.getReg();
1330 if (!Reg)
1331 continue;
1332
1333 for (const MCPhysReg Reg : TRI.sub_and_superregs_inclusive(Reg))
1334 RegsToZero.reset(Reg);
1335 }
1336 }
1337 }
1338
1339 // Don't clear registers that must be preserved.
1340 for (const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
1341 MCPhysReg CSReg = *CSRegs; ++CSRegs)
1342 for (MCRegister Reg : TRI.sub_and_superregs_inclusive(CSReg))
1343 RegsToZero.reset(Reg.id());
1344
1345 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1346 for (MachineBasicBlock &MBB : MF)
1347 if (MBB.isReturnBlock())
1348 TFI.emitZeroCallUsedRegs(RegsToZero, MBB);
1349}
1350
1351/// Replace all FrameIndex operands with physical register references and actual
1352/// offsets.
1353void PEIImpl::replaceFrameIndicesBackward(MachineFunction &MF) {
1354 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1355
1356 for (auto &MBB : MF) {
1357 int SPAdj = 0;
1358 if (!MBB.succ_empty()) {
1359 // Get the SP adjustment for the end of MBB from the start of any of its
1360 // successors. They should all be the same.
1361 assert(all_of(MBB.successors(), [&MBB](const MachineBasicBlock *Succ) {
1362 return Succ->getCallFrameSize() ==
1363 (*MBB.succ_begin())->getCallFrameSize();
1364 }));
1365 const MachineBasicBlock &FirstSucc = **MBB.succ_begin();
1366 SPAdj = TFI.alignSPAdjust(FirstSucc.getCallFrameSize());
1368 SPAdj = -SPAdj;
1369 }
1370
1371 replaceFrameIndicesBackward(&MBB, MF, SPAdj);
1372
1373 // We can't track the call frame size after call frame pseudos have been
1374 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1376 }
1377}
1378
1379/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1380/// register references and actual offsets.
1381void PEIImpl::replaceFrameIndices(MachineFunction &MF) {
1382 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1383
1384 for (auto &MBB : MF) {
1385 int SPAdj = TFI.alignSPAdjust(MBB.getCallFrameSize());
1387 SPAdj = -SPAdj;
1388
1389 replaceFrameIndices(&MBB, MF, SPAdj);
1390
1391 // We can't track the call frame size after call frame pseudos have been
1392 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1394 }
1395}
1396
1397bool PEIImpl::replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
1398 unsigned OpIdx, int SPAdj) {
1399 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1400 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1401 if (MI.isDebugValue()) {
1402
1403 MachineOperand &Op = MI.getOperand(OpIdx);
1404 assert(MI.isDebugOperand(&Op) &&
1405 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1406 " machine instruction");
1407 Register Reg;
1408 unsigned FrameIdx = Op.getIndex();
1409 unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
1410
1411 StackOffset Offset = TFI->getFrameIndexReference(MF, FrameIdx, Reg);
1412 Op.ChangeToRegister(Reg, false /*isDef*/);
1413
1414 const DIExpression *DIExpr = MI.getDebugExpression();
1415
1416 // If we have a direct DBG_VALUE, and its location expression isn't
1417 // currently complex, then adding an offset will morph it into a
1418 // complex location that is interpreted as being a memory address.
1419 // This changes a pointer-valued variable to dereference that pointer,
1420 // which is incorrect. Fix by adding DW_OP_stack_value.
1421
1422 if (MI.isNonListDebugValue()) {
1423 unsigned PrependFlags = DIExpression::ApplyOffset;
1424 if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1425 PrependFlags |= DIExpression::StackValue;
1426
1427 // If we have DBG_VALUE that is indirect and has a Implicit location
1428 // expression need to insert a deref before prepending a Memory
1429 // location expression. Also after doing this we change the DBG_VALUE
1430 // to be direct.
1431 if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1432 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1433 bool WithStackValue = true;
1434 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1435 // Make the DBG_VALUE direct.
1436 MI.getDebugOffset().ChangeToRegister(0, false);
1437 }
1438 DIExpr = TRI.prependOffsetExpression(DIExpr, PrependFlags, Offset);
1439 } else {
1440 // The debug operand at DebugOpIndex was a frame index at offset
1441 // `Offset`; now the operand has been replaced with the frame
1442 // register, we must add Offset with `register x, plus Offset`.
1443 unsigned DebugOpIndex = MI.getDebugOperandIndex(&Op);
1445 TRI.getOffsetOpcodes(Offset, Ops);
1446 DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, DebugOpIndex);
1447 }
1448 MI.getDebugExpressionOp().setMetadata(DIExpr);
1449 return true;
1450 }
1451
1452 if (MI.isDebugPHI()) {
1453 // Allow stack ref to continue onwards.
1454 return true;
1455 }
1456
1457 // TODO: This code should be commoned with the code for
1458 // PATCHPOINT. There's no good reason for the difference in
1459 // implementation other than historical accident. The only
1460 // remaining difference is the unconditional use of the stack
1461 // pointer as the base register.
1462 if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1463 assert((!MI.isDebugValue() || OpIdx == 0) &&
1464 "Frame indices can only appear as the first operand of a "
1465 "DBG_VALUE machine instruction");
1466 Register Reg;
1467 MachineOperand &Offset = MI.getOperand(OpIdx + 1);
1468 StackOffset refOffset = TFI->getFrameIndexReferencePreferSP(
1469 MF, MI.getOperand(OpIdx).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1470 assert(!refOffset.getScalable() &&
1471 "Frame offsets with a scalable component are not supported");
1472 Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj);
1473 MI.getOperand(OpIdx).ChangeToRegister(Reg, false /*isDef*/);
1474 return true;
1475 }
1476 return false;
1477}
1478
1479void PEIImpl::replaceFrameIndicesBackward(MachineBasicBlock *BB,
1480 MachineFunction &MF, int &SPAdj) {
1482 "getRegisterInfo() must be implemented!");
1483
1484 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1485 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1486 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1487
1488 RegScavenger *LocalRS = FrameIndexEliminationScavenging ? RS : nullptr;
1489 if (LocalRS)
1490 LocalRS->enterBasicBlockEnd(*BB);
1491
1492 for (MachineBasicBlock::iterator I = BB->end(); I != BB->begin();) {
1493 MachineInstr &MI = *std::prev(I);
1494
1495 if (TII.isFrameInstr(MI)) {
1496 SPAdj -= TII.getSPAdjust(MI);
1497 TFI.eliminateCallFramePseudoInstr(MF, *BB, &MI);
1498 continue;
1499 }
1500
1501 // Step backwards to get the liveness state at (immedately after) MI.
1502 if (LocalRS)
1503 LocalRS->backward(I);
1504
1505 bool RemovedMI = false;
1506 for (const auto &[Idx, Op] : enumerate(MI.operands())) {
1507 if (!Op.isFI())
1508 continue;
1509
1510 if (replaceFrameIndexDebugInstr(MF, MI, Idx, SPAdj))
1511 continue;
1512
1513 // Eliminate this FrameIndex operand.
1514 RemovedMI = TRI.eliminateFrameIndex(MI, SPAdj, Idx, LocalRS);
1515 if (RemovedMI)
1516 break;
1517 }
1518
1519 if (!RemovedMI)
1520 --I;
1521 }
1522}
1523
1524void PEIImpl::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1525 int &SPAdj) {
1527 "getRegisterInfo() must be implemented!");
1528 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1529 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1530 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1531
1532 bool InsideCallSequence = false;
1533
1534 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1535 if (TII.isFrameInstr(*I)) {
1536 InsideCallSequence = TII.isFrameSetup(*I);
1537 SPAdj += TII.getSPAdjust(*I);
1538 I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
1539 continue;
1540 }
1541
1542 MachineInstr &MI = *I;
1543 bool DoIncr = true;
1544 bool DidFinishLoop = true;
1545 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1546 if (!MI.getOperand(i).isFI())
1547 continue;
1548
1549 if (replaceFrameIndexDebugInstr(MF, MI, i, SPAdj))
1550 continue;
1551
1552 // Some instructions (e.g. inline asm instructions) can have
1553 // multiple frame indices and/or cause eliminateFrameIndex
1554 // to insert more than one instruction. We need the register
1555 // scavenger to go through all of these instructions so that
1556 // it can update its register information. We keep the
1557 // iterator at the point before insertion so that we can
1558 // revisit them in full.
1559 bool AtBeginning = (I == BB->begin());
1560 if (!AtBeginning) --I;
1561
1562 // If this instruction has a FrameIndex operand, we need to
1563 // use that target machine register info object to eliminate
1564 // it.
1565 TRI.eliminateFrameIndex(MI, SPAdj, i, RS);
1566
1567 // Reset the iterator if we were at the beginning of the BB.
1568 if (AtBeginning) {
1569 I = BB->begin();
1570 DoIncr = false;
1571 }
1572
1573 DidFinishLoop = false;
1574 break;
1575 }
1576
1577 // If we are looking at a call sequence, we need to keep track of
1578 // the SP adjustment made by each instruction in the sequence.
1579 // This includes both the frame setup/destroy pseudos (handled above),
1580 // as well as other instructions that have side effects w.r.t the SP.
1581 // Note that this must come after eliminateFrameIndex, because
1582 // if I itself referred to a frame index, we shouldn't count its own
1583 // adjustment.
1584 if (DidFinishLoop && InsideCallSequence)
1585 SPAdj += TII.getSPAdjust(MI);
1586
1587 if (DoIncr && I != BB->end())
1588 ++I;
1589 }
1590}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const TargetInstrInfo & TII
MachineBasicBlock & MBB
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< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
SmallVector< MachineBasicBlock *, 4 > MBBVector
static bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, Align MaxAlign, BitVector &StackBytesFree)
Assign frame object to an unused portion of the stack in the fixed stack object range.
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert spill code for the callee-saved registers used in the function.
static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs, SmallSet< int, 16 > &ProtectedObjs, MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset, Align &MaxAlign)
AssignProtectedObjSet - Helper function to assign large stack objects (i.e., those required to be clo...
static void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, int64_t &Offset, Align &MaxAlign)
AdjustStackOffset - Helper function used to adjust the stack frame offset.
SmallDenseMap< MachineBasicBlock *, SmallVector< MachineInstr *, 4 >, 4 > SavedDbgValuesMap
static void computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, int64_t FixedCSEnd, BitVector &StackBytesFree)
Compute which bytes of fixed and callee-save stack area are unused and keep track of them in StackByt...
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
SmallSetVector< int, 8 > StackObjSet
StackObjSet - A set of stack object indexes.
static void stashEntryDbgValues(MachineBasicBlock &MBB, SavedDbgValuesMap &EntryDbgValues)
Stash DBG_VALUEs that describe parameters and which are placed at the start of the block.
static void assignCalleeSavedSpillSlots(MachineFunction &F, const BitVector &SavedRegs)
This file declares the machine register scavenger class.
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool test(unsigned Idx) const
Definition BitVector.h:480
BitVector & reset()
Definition BitVector.h:411
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:319
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition BitVector.h:360
void clear()
clear - Removes all bits from the bitvector.
Definition BitVector.h:354
BitVector & set()
Definition BitVector.h:370
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:327
bool none() const
none - Returns true if none of the bits are set.
Definition BitVector.h:207
size_type size() const
size - Returns the number of bits in this bitvector.
Definition BitVector.h:178
bool empty() const
empty - Tests whether there are no bits in this bitvector.
Definition BitVector.h:175
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
DWARF expression.
LLVM_ABI bool isImplicit() const
Return whether this is an implicit location description.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI bool isComplex() const
Return whether the location is computed on the expression stack, meaning it cannot be a simple regist...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:765
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:270
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MachineInstrBundleIterator< const MachineInstr > const_iterator
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
unsigned getCallFrameSize() const
Return the call frame size on entry to this basic block.
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
LLVM_ABI void computeMaxCallFrameSize(MachineFunction &MF, std::vector< MachineBasicBlock::iterator > *FrameSDOps=nullptr)
Computes the maximum size of a callframe.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
int64_t getLocalFrameObjectCount() const
Return the number of objects allocated into the local object block.
bool hasCalls() const
Return true if the current function has any function calls.
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
Align getLocalFrameMaxAlign() const
Return the required alignment of the local object blob.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
@ SSPLK_SmallArray
Array or nested array < SSP-buffer-size.
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
@ SSPLK_None
Did not trigger a stack protector.
bool isCalleeSavedObjectIndex(int ObjectIdx) const
std::pair< int, int64_t > getLocalFrameObjectMap(int i) const
Get the local offset mapping for a for an object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setSavePoints(SaveRestorePoints NewSavePoints)
bool getUseLocalStackAllocationBlock() const
Get whether the local allocation blob should be allocated together or let PEI allocate the locals in ...
int getStackProtectorIndex() const
Return the index for the stack protector object.
void setCalleeSavedInfoValid(bool v)
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.
bool isMaxCallFrameSizeComputed() const
int64_t getLocalFrameSize() const
Get the size of the local object blob.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
void setCalleeSavedInfo(std::vector< CalleeSavedInfo > CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
uint64_t getUnsafeStackSize() const
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackProtectorIndex() const
void setRestorePoints(SaveRestorePoints NewRestorePoints)
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
const SaveRestorePoints & getRestorePoints() const
void setIsCalleeSavedObjectIndex(int ObjectIdx, bool IsCalleeSaved)
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.
int getObjectIndexBegin() const
Return the minimum frame object index.
const SaveRestorePoints & getSavePoints() const
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...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
void backward()
Update internal register state and move MBB iterator backwards.
void getScavengingFrameIndices(SmallVectorImpl< int > &A) const
Get an array of scavenging frame indices.
bool isScavengingFrameIndex(int FI) const
Query whether a frame index is a scavenging frame index.
constexpr unsigned id() const
Definition Register.h:100
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:133
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:175
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:183
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:472
Information about stack frame layout on the target.
virtual void spillFPBP(MachineFunction &MF) const
If frame pointer or base pointer is clobbered by an instruction, we should spill/restore it around th...
virtual void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
virtual const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
virtual bool enableStackSlotScavenging(const MachineFunction &MF) const
Returns true if the stack slot holes in the fixed and callee-save stack area should be used when allo...
virtual bool allocateScavengingFrameIndexesNearIncomingSP(const MachineFunction &MF) const
Control the placement of special register scavenging spill slots when allocating a stack frame.
Align getTransientStackAlign() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual uint64_t getStackThreshold() const
getStackThreshold - Return the maximum stack size
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
virtual void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Replace a StackProbe stub (if any) with the actual probe code inline.
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
void spillCalleeSavedRegister(MachineBasicBlock &SaveBlock, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegister - Default implementation for spilling a single callee saved register.
virtual void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &objectsToAllocate) const
Order the symbols in the local stack frame.
virtual void adjustForHiPEPrologue(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in the assembly prologue to ex...
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
virtual bool needsFrameIndexResolution(const MachineFunction &MF) const
virtual MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
virtual void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
virtual StackOffset getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI, Register &FrameReg, bool IgnoreSPUpdates) const
Same as getFrameIndexReference, except that the stack pointer (as opposed to the frame pointer) will ...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
virtual void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to have the function use segmented stacks.
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const
canSimplifyCallFramePseudos - When possible, it's best to simplify the call frame pseudo ops before d...
virtual void emitZeroCallUsedRegs(BitVector RegsToZero, MachineBasicBlock &MBB) const
emitZeroCallUsedRegs - Zeros out call used registers.
virtual void emitRemarks(const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const
This method is called at the end of prolog/epilog code insertion, so targets can emit remarks based o...
virtual bool targetHandlesStackFrameRounding() const
targetHandlesStackFrameRounding - Returns true if the target is responsible for rounding up the stack...
virtual void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
virtual int getSPAdjust(const MachineInstr &MI) const
Returns the actual stack pointer adjustment made by an instruction as part of a call sequence.
bool isFrameInstr(const MachineInstr &I) const
Returns true if the argument is a frame pseudo instruction.
bool isFrameSetup(const MachineInstr &I) const
Returns true if the argument is a frame setup pseudo instruction.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
virtual bool usesPhysRegsForValues() const
True if the target uses physical regs (as nearly all targets do).
TargetOptions Options
unsigned StackSymbolOrdering
StackSymbolOrdering - When true, this will allow CodeGen to order the local stack symbols (for code s...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2484
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
LLVM_ABI MachineFunctionPass * createPrologEpilogInserterPass()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
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:1744
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
DenseMap< MachineBasicBlock *, std::vector< CalleeSavedInfo > > SaveRestorePoints
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1751
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse)
Return a range that conditionally reverses C.
Definition STLExtras.h:1421
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
DWARFExpression::Operation Op
LLVM_ABI void initializePEILegacyPass(PassRegistry &)
auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:305
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39