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 if (StackGrowsDown) {
915 for (int FI = MFI.getObjectIndexBegin(); FI < MFI.getObjectIndexEnd();
916 FI++) {
917 // Only allocate objects on the default stack.
918 if (!MFI.isCalleeSavedObjectIndex(FI) ||
920 continue;
921 // TODO: should we be using MFI.isDeadObjectIndex(FI) here?
922 AdjustStackOffset(MFI, FI, StackGrowsDown, Offset, MaxAlign);
923 }
924 } else {
925 for (int FI = MFI.getObjectIndexEnd() - 1; FI >= MFI.getObjectIndexBegin();
926 FI--) {
927 // Only allocate objects on the default stack.
928 if (!MFI.isCalleeSavedObjectIndex(FI) ||
930 continue;
931
932 if (MFI.isDeadObjectIndex(FI))
933 continue;
934
935 AdjustStackOffset(MFI, FI, StackGrowsDown, Offset, MaxAlign);
936 }
937 }
938
939 assert(MaxAlign == MFI.getMaxAlign() &&
940 "MFI.getMaxAlign should already account for all callee-saved "
941 "registers without a fixed stack slot");
942
943 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
944 // stack area.
945 int64_t FixedCSEnd = Offset;
946
947 // Make sure the special register scavenging spill slot is closest to the
948 // incoming stack pointer if a frame pointer is required and is closer
949 // to the incoming rather than the final stack pointer.
950 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
951 bool EarlyScavengingSlots = TFI.allocateScavengingFrameIndexesNearIncomingSP(MF);
952 if (RS && EarlyScavengingSlots) {
953 SmallVector<int, 2> SFIs;
955 for (int SFI : SFIs)
956 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
957 }
958
959 // FIXME: Once this is working, then enable flag will change to a target
960 // check for whether the frame is large enough to want to use virtual
961 // frame index registers. Functions which don't want/need this optimization
962 // will continue to use the existing code path.
964 Align Alignment = MFI.getLocalFrameMaxAlign();
965
966 // Adjust to alignment boundary.
967 Offset = alignTo(Offset, Alignment);
968
969 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
970
971 // Resolve offsets for objects in the local block.
972 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
973 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
974 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
975 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
976 << "]\n");
977 MFI.setObjectOffset(Entry.first, FIOffset);
978 }
979 // Allocate the local block
980 Offset += MFI.getLocalFrameSize();
981
982 MaxAlign = std::max(Alignment, MaxAlign);
983 }
984
985 // Retrieve the Exception Handler registration node.
986 int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
987 if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
988 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
989
990 // Make sure that the stack protector comes before the local variables on the
991 // stack.
992 SmallSet<int, 16> ProtectedObjs;
993 if (MFI.hasStackProtectorIndex()) {
994 int StackProtectorFI = MFI.getStackProtectorIndex();
995 StackObjSet LargeArrayObjs;
996 StackObjSet SmallArrayObjs;
997 StackObjSet AddrOfObjs;
998
999 // If we need a stack protector, we need to make sure that
1000 // LocalStackSlotPass didn't already allocate a slot for it.
1001 // If we are told to use the LocalStackAllocationBlock, the stack protector
1002 // is expected to be already pre-allocated.
1003 if (MFI.getStackID(StackProtectorFI) != TargetStackID::Default) {
1004 // If the stack protector isn't on the default stack then it's up to the
1005 // target to set the stack offset.
1006 assert(MFI.getObjectOffset(StackProtectorFI) != 0 &&
1007 "Offset of stack protector on non-default stack expected to be "
1008 "already set.");
1010 "Stack protector on non-default stack expected to not be "
1011 "pre-allocated by LocalStackSlotPass.");
1012 } else if (!MFI.getUseLocalStackAllocationBlock()) {
1013 AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset,
1014 MaxAlign);
1015 } else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex())) {
1017 "Stack protector not pre-allocated by LocalStackSlotPass.");
1018 }
1019
1020 // Assign large stack objects first.
1021 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1023 continue;
1024 if (MFI.isCalleeSavedObjectIndex(i))
1025 continue;
1026 if (RS && RS->isScavengingFrameIndex((int)i))
1027 continue;
1028 if (MFI.isDeadObjectIndex(i))
1029 continue;
1030 if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
1031 continue;
1032 // Only allocate objects on the default stack.
1033 if (MFI.getStackID(i) != TargetStackID::Default)
1034 continue;
1035
1036 switch (MFI.getObjectSSPLayout(i)) {
1038 continue;
1040 SmallArrayObjs.insert(i);
1041 continue;
1043 AddrOfObjs.insert(i);
1044 continue;
1046 LargeArrayObjs.insert(i);
1047 continue;
1048 }
1049 llvm_unreachable("Unexpected SSPLayoutKind.");
1050 }
1051
1052 // We expect **all** the protected stack objects to be pre-allocated by
1053 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
1054 // of them, we may end up messing up the expected order of the objects.
1056 !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
1057 AddrOfObjs.empty()))
1058 llvm_unreachable("Found protected stack objects not pre-allocated by "
1059 "LocalStackSlotPass.");
1060
1061 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1062 Offset, MaxAlign);
1063 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1064 Offset, MaxAlign);
1065 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
1066 Offset, MaxAlign);
1067 }
1068
1069 SmallVector<int, 8> ObjectsToAllocate;
1070
1071 // Then prepare to assign frame offsets to stack objects that are not used to
1072 // spill callee saved registers.
1073 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1075 continue;
1076 if (MFI.isCalleeSavedObjectIndex(i))
1077 continue;
1078 if (RS && RS->isScavengingFrameIndex((int)i))
1079 continue;
1080 if (MFI.isDeadObjectIndex(i))
1081 continue;
1082 if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
1083 continue;
1084 if (ProtectedObjs.count(i))
1085 continue;
1086 // Only allocate objects on the default stack.
1087 if (MFI.getStackID(i) != TargetStackID::Default)
1088 continue;
1089
1090 // Add the objects that we need to allocate to our working set.
1091 ObjectsToAllocate.push_back(i);
1092 }
1093
1094 // Allocate the EH registration node first if one is present.
1095 if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1096 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
1097 MaxAlign);
1098
1099 // Give the targets a chance to order the objects the way they like it.
1100 if (MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1102 TFI.orderFrameObjects(MF, ObjectsToAllocate);
1103
1104 // Keep track of which bytes in the fixed and callee-save range are used so we
1105 // can use the holes when allocating later stack objects. Only do this if
1106 // stack protector isn't being used and the target requests it and we're
1107 // optimizing.
1108 BitVector StackBytesFree;
1109 if (!ObjectsToAllocate.empty() &&
1110 MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1112 computeFreeStackSlots(MFI, StackGrowsDown, FixedCSEnd, StackBytesFree);
1113
1114 // Now walk the objects and actually assign base offsets to them.
1115 for (auto &Object : ObjectsToAllocate)
1116 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
1117 StackBytesFree))
1118 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign);
1119
1120 // Make sure the special register scavenging spill slot is closest to the
1121 // stack pointer.
1122 if (RS && !EarlyScavengingSlots) {
1123 SmallVector<int, 2> SFIs;
1124 RS->getScavengingFrameIndices(SFIs);
1125 for (int SFI : SFIs)
1126 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
1127 }
1128
1130 // If we have reserved argument space for call sites in the function
1131 // immediately on entry to the current function, count it as part of the
1132 // overall stack size.
1133 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
1134 Offset += MFI.getMaxCallFrameSize();
1135
1136 // Round up the size to a multiple of the alignment. If the function has
1137 // any calls or alloca's, align to the target's StackAlignment value to
1138 // ensure that the callee's frame or the alloca data is suitably aligned;
1139 // otherwise, for leaf functions, align to the TransientStackAlignment
1140 // value.
1141 Align StackAlign;
1142 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
1143 (RegInfo->hasStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
1144 StackAlign = TFI.getStackAlign();
1145 else
1146 StackAlign = TFI.getTransientStackAlign();
1147
1148 // If the frame pointer is eliminated, all frame offsets will be relative to
1149 // SP not FP. Align to MaxAlign so this works.
1150 StackAlign = std::max(StackAlign, MaxAlign);
1151 int64_t OffsetBeforeAlignment = Offset;
1152 Offset = alignTo(Offset, StackAlign);
1153
1154 // If we have increased the offset to fulfill the alignment constrants,
1155 // then the scavenging spill slots may become harder to reach from the
1156 // stack pointer, float them so they stay close.
1157 if (StackGrowsDown && OffsetBeforeAlignment != Offset && RS &&
1158 !EarlyScavengingSlots) {
1159 SmallVector<int, 2> SFIs;
1160 RS->getScavengingFrameIndices(SFIs);
1161 LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs()
1162 << "Adjusting emergency spill slots!\n";);
1163 int64_t Delta = Offset - OffsetBeforeAlignment;
1164 for (int SFI : SFIs) {
1166 << "Adjusting offset of emergency spill slot #" << SFI
1167 << " from " << MFI.getObjectOffset(SFI););
1168 MFI.setObjectOffset(SFI, MFI.getObjectOffset(SFI) - Delta);
1169 LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";);
1170 }
1171 }
1172 }
1173
1174 // Update frame info to pretend that this is part of the stack...
1175 int64_t StackSize = Offset - LocalAreaOffset;
1176 MFI.setStackSize(StackSize);
1177 NumBytesStackSpace += StackSize;
1178}
1179
1180/// insertPrologEpilogCode - Scan the function for modified callee saved
1181/// registers, insert spill code for these callee saved registers, then add
1182/// prolog and epilog code to the function.
1183void PEIImpl::insertPrologEpilogCode(MachineFunction &MF) {
1184 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1185
1186 // Add prologue to the function...
1187 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1188 TFI.emitPrologue(MF, *SaveBlock);
1189
1190 // Add epilogue to restore the callee-save registers in each exiting block.
1191 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1192 TFI.emitEpilogue(MF, *RestoreBlock);
1193
1194 // Zero call used registers before restoring callee-saved registers.
1195 insertZeroCallUsedRegs(MF);
1196
1197 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1198 TFI.inlineStackProbe(MF, *SaveBlock);
1199
1200 // Emit additional code that is required to support segmented stacks, if
1201 // we've been asked for it. This, when linked with a runtime with support
1202 // for segmented stacks (libgcc is one), will result in allocating stack
1203 // space in small chunks instead of one large contiguous block.
1204 if (MF.shouldSplitStack()) {
1205 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1206 TFI.adjustForSegmentedStacks(MF, *SaveBlock);
1207 }
1208
1209 // Emit additional code that is required to explicitly handle the stack in
1210 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1211 // approach is rather similar to that of Segmented Stacks, but it uses a
1212 // different conditional check and another BIF for allocating more stack
1213 // space.
1214 if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
1215 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1216 TFI.adjustForHiPEPrologue(MF, *SaveBlock);
1217}
1218
1219/// insertZeroCallUsedRegs - Zero out call used registers.
1220void PEIImpl::insertZeroCallUsedRegs(MachineFunction &MF) {
1221 const Function &F = MF.getFunction();
1222
1223 if (!F.hasFnAttribute("zero-call-used-regs"))
1224 return;
1225
1226 using namespace ZeroCallUsedRegs;
1227
1228 ZeroCallUsedRegsKind ZeroRegsKind =
1229 StringSwitch<ZeroCallUsedRegsKind>(
1230 F.getFnAttribute("zero-call-used-regs").getValueAsString())
1231 .Case("skip", ZeroCallUsedRegsKind::Skip)
1232 .Case("used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg)
1233 .Case("used-gpr", ZeroCallUsedRegsKind::UsedGPR)
1234 .Case("used-arg", ZeroCallUsedRegsKind::UsedArg)
1235 .Case("used", ZeroCallUsedRegsKind::Used)
1236 .Case("all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg)
1237 .Case("all-gpr", ZeroCallUsedRegsKind::AllGPR)
1238 .Case("all-arg", ZeroCallUsedRegsKind::AllArg)
1239 .Case("all", ZeroCallUsedRegsKind::All);
1240
1241 if (ZeroRegsKind == ZeroCallUsedRegsKind::Skip)
1242 return;
1243
1244 const bool OnlyGPR = static_cast<unsigned>(ZeroRegsKind) & ONLY_GPR;
1245 const bool OnlyUsed = static_cast<unsigned>(ZeroRegsKind) & ONLY_USED;
1246 const bool OnlyArg = static_cast<unsigned>(ZeroRegsKind) & ONLY_ARG;
1247
1248 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1249 const BitVector AllocatableSet(TRI.getAllocatableSet(MF));
1250
1251 // Mark all used registers.
1252 BitVector UsedRegs(TRI.getNumRegs());
1253 if (OnlyUsed)
1254 for (const MachineBasicBlock &MBB : MF)
1255 for (const MachineInstr &MI : MBB) {
1256 // skip debug instructions
1257 if (MI.isDebugInstr())
1258 continue;
1259
1260 for (const MachineOperand &MO : MI.operands()) {
1261 if (!MO.isReg())
1262 continue;
1263
1264 MCRegister Reg = MO.getReg();
1265 if (AllocatableSet[Reg.id()] && !MO.isImplicit() &&
1266 (MO.isDef() || MO.isUse()))
1267 UsedRegs.set(Reg.id());
1268 }
1269 }
1270
1271 // Get a list of registers that are used.
1272 BitVector LiveIns(TRI.getNumRegs());
1273 for (const MachineBasicBlock::RegisterMaskPair &LI : MF.front().liveins())
1274 LiveIns.set(LI.PhysReg);
1275
1276 BitVector RegsToZero(TRI.getNumRegs());
1277 for (MCRegister Reg : AllocatableSet.set_bits()) {
1278 // Skip over fixed registers.
1279 if (TRI.isFixedRegister(MF, Reg))
1280 continue;
1281
1282 // Want only general purpose registers.
1283 if (OnlyGPR && !TRI.isGeneralPurposeRegister(MF, Reg))
1284 continue;
1285
1286 // Want only used registers.
1287 if (OnlyUsed && !UsedRegs[Reg.id()])
1288 continue;
1289
1290 // Want only registers used for arguments.
1291 if (OnlyArg) {
1292 if (OnlyUsed) {
1293 if (!LiveIns[Reg.id()])
1294 continue;
1295 } else if (!TRI.isArgumentRegister(MF, Reg)) {
1296 continue;
1297 }
1298 }
1299
1300 RegsToZero.set(Reg.id());
1301 }
1302
1303 // Don't clear registers that are live when leaving the function.
1304 for (const MachineBasicBlock &MBB : MF)
1305 for (const MachineInstr &MI : MBB.terminators()) {
1306 if (!MI.isReturn())
1307 continue;
1308
1309 for (const auto &MO : MI.operands()) {
1310 if (!MO.isReg())
1311 continue;
1312
1313 MCRegister Reg = MO.getReg();
1314 if (!Reg)
1315 continue;
1316
1317 // This picks up sibling registers (e.q. %al -> %ah).
1318 // FIXME: Mixing physical registers and register units is likely a bug.
1319 for (MCRegUnit Unit : TRI.regunits(Reg))
1320 RegsToZero.reset(static_cast<unsigned>(Unit));
1321
1322 for (MCPhysReg SReg : TRI.sub_and_superregs_inclusive(Reg))
1323 RegsToZero.reset(SReg);
1324 }
1325 }
1326
1327 // Don't need to clear registers that are used/clobbered by terminating
1328 // instructions.
1329 for (const MachineBasicBlock &MBB : MF) {
1330 if (!MBB.isReturnBlock())
1331 continue;
1332
1335 ++I) {
1336 for (const MachineOperand &MO : I->operands()) {
1337 if (!MO.isReg())
1338 continue;
1339
1340 MCRegister Reg = MO.getReg();
1341 if (!Reg)
1342 continue;
1343
1344 for (const MCPhysReg Reg : TRI.sub_and_superregs_inclusive(Reg))
1345 RegsToZero.reset(Reg);
1346 }
1347 }
1348 }
1349
1350 // Don't clear registers that must be preserved.
1351 for (const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
1352 MCPhysReg CSReg = *CSRegs; ++CSRegs)
1353 for (MCRegister Reg : TRI.sub_and_superregs_inclusive(CSReg))
1354 RegsToZero.reset(Reg.id());
1355
1356 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1357 for (MachineBasicBlock &MBB : MF)
1358 if (MBB.isReturnBlock())
1359 TFI.emitZeroCallUsedRegs(RegsToZero, MBB);
1360}
1361
1362/// Replace all FrameIndex operands with physical register references and actual
1363/// offsets.
1364void PEIImpl::replaceFrameIndicesBackward(MachineFunction &MF) {
1365 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1366
1367 for (auto &MBB : MF) {
1368 int SPAdj = 0;
1369 if (!MBB.succ_empty()) {
1370 // Get the SP adjustment for the end of MBB from the start of any of its
1371 // successors. They should all be the same.
1372 assert(all_of(MBB.successors(), [&MBB](const MachineBasicBlock *Succ) {
1373 return Succ->getCallFrameSize() ==
1374 (*MBB.succ_begin())->getCallFrameSize();
1375 }));
1376 const MachineBasicBlock &FirstSucc = **MBB.succ_begin();
1377 SPAdj = TFI.alignSPAdjust(FirstSucc.getCallFrameSize());
1379 SPAdj = -SPAdj;
1380 }
1381
1382 replaceFrameIndicesBackward(&MBB, MF, SPAdj);
1383
1384 // We can't track the call frame size after call frame pseudos have been
1385 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1387 }
1388}
1389
1390/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1391/// register references and actual offsets.
1392void PEIImpl::replaceFrameIndices(MachineFunction &MF) {
1393 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1394
1395 for (auto &MBB : MF) {
1396 int SPAdj = TFI.alignSPAdjust(MBB.getCallFrameSize());
1398 SPAdj = -SPAdj;
1399
1400 replaceFrameIndices(&MBB, MF, SPAdj);
1401
1402 // We can't track the call frame size after call frame pseudos have been
1403 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1405 }
1406}
1407
1408bool PEIImpl::replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
1409 unsigned OpIdx, int SPAdj) {
1410 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1411 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1412 if (MI.isDebugValue()) {
1413
1414 MachineOperand &Op = MI.getOperand(OpIdx);
1415 assert(MI.isDebugOperand(&Op) &&
1416 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1417 " machine instruction");
1418 Register Reg;
1419 unsigned FrameIdx = Op.getIndex();
1420 unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
1421
1422 StackOffset Offset = TFI->getFrameIndexReference(MF, FrameIdx, Reg);
1423 Op.ChangeToRegister(Reg, false /*isDef*/);
1424
1425 const DIExpression *DIExpr = MI.getDebugExpression();
1426
1427 // If we have a direct DBG_VALUE, and its location expression isn't
1428 // currently complex, then adding an offset will morph it into a
1429 // complex location that is interpreted as being a memory address.
1430 // This changes a pointer-valued variable to dereference that pointer,
1431 // which is incorrect. Fix by adding DW_OP_stack_value.
1432
1433 if (MI.isNonListDebugValue()) {
1434 unsigned PrependFlags = DIExpression::ApplyOffset;
1435 if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1436 PrependFlags |= DIExpression::StackValue;
1437
1438 // If we have DBG_VALUE that is indirect and has a Implicit location
1439 // expression need to insert a deref before prepending a Memory
1440 // location expression. Also after doing this we change the DBG_VALUE
1441 // to be direct.
1442 if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1443 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1444 bool WithStackValue = true;
1445 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1446 // Make the DBG_VALUE direct.
1447 MI.getDebugOffset().ChangeToRegister(0, false);
1448 }
1449 DIExpr = TRI.prependOffsetExpression(DIExpr, PrependFlags, Offset);
1450 } else {
1451 // The debug operand at DebugOpIndex was a frame index at offset
1452 // `Offset`; now the operand has been replaced with the frame
1453 // register, we must add Offset with `register x, plus Offset`.
1454 unsigned DebugOpIndex = MI.getDebugOperandIndex(&Op);
1456 TRI.getOffsetOpcodes(Offset, Ops);
1457 DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, DebugOpIndex);
1458 }
1459 MI.getDebugExpressionOp().setMetadata(DIExpr);
1460 return true;
1461 }
1462
1463 if (MI.isDebugPHI()) {
1464 // Allow stack ref to continue onwards.
1465 return true;
1466 }
1467
1468 // TODO: This code should be commoned with the code for
1469 // PATCHPOINT. There's no good reason for the difference in
1470 // implementation other than historical accident. The only
1471 // remaining difference is the unconditional use of the stack
1472 // pointer as the base register.
1473 if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1474 assert((!MI.isDebugValue() || OpIdx == 0) &&
1475 "Frame indices can only appear as the first operand of a "
1476 "DBG_VALUE machine instruction");
1477 Register Reg;
1478 MachineOperand &Offset = MI.getOperand(OpIdx + 1);
1479 StackOffset refOffset = TFI->getFrameIndexReferencePreferSP(
1480 MF, MI.getOperand(OpIdx).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1481 assert(!refOffset.getScalable() &&
1482 "Frame offsets with a scalable component are not supported");
1483 Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj);
1484 MI.getOperand(OpIdx).ChangeToRegister(Reg, false /*isDef*/);
1485 return true;
1486 }
1487 return false;
1488}
1489
1490void PEIImpl::replaceFrameIndicesBackward(MachineBasicBlock *BB,
1491 MachineFunction &MF, int &SPAdj) {
1493 "getRegisterInfo() must be implemented!");
1494
1495 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1496 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1497 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1498
1499 RegScavenger *LocalRS = FrameIndexEliminationScavenging ? RS : nullptr;
1500 if (LocalRS)
1501 LocalRS->enterBasicBlockEnd(*BB);
1502
1503 for (MachineBasicBlock::iterator I = BB->end(); I != BB->begin();) {
1504 MachineInstr &MI = *std::prev(I);
1505
1506 if (TII.isFrameInstr(MI)) {
1507 SPAdj -= TII.getSPAdjust(MI);
1508 TFI.eliminateCallFramePseudoInstr(MF, *BB, &MI);
1509 continue;
1510 }
1511
1512 // Step backwards to get the liveness state at (immedately after) MI.
1513 if (LocalRS)
1514 LocalRS->backward(I);
1515
1516 bool RemovedMI = false;
1517 for (const auto &[Idx, Op] : enumerate(MI.operands())) {
1518 if (!Op.isFI())
1519 continue;
1520
1521 if (replaceFrameIndexDebugInstr(MF, MI, Idx, SPAdj))
1522 continue;
1523
1524 // Eliminate this FrameIndex operand.
1525 RemovedMI = TRI.eliminateFrameIndex(MI, SPAdj, Idx, LocalRS);
1526 if (RemovedMI)
1527 break;
1528 }
1529
1530 if (!RemovedMI)
1531 --I;
1532 }
1533}
1534
1535void PEIImpl::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1536 int &SPAdj) {
1538 "getRegisterInfo() must be implemented!");
1539 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1540 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1541 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1542
1543 bool InsideCallSequence = false;
1544
1545 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1546 if (TII.isFrameInstr(*I)) {
1547 InsideCallSequence = TII.isFrameSetup(*I);
1548 SPAdj += TII.getSPAdjust(*I);
1549 I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
1550 continue;
1551 }
1552
1553 MachineInstr &MI = *I;
1554 bool DoIncr = true;
1555 bool DidFinishLoop = true;
1556 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1557 if (!MI.getOperand(i).isFI())
1558 continue;
1559
1560 if (replaceFrameIndexDebugInstr(MF, MI, i, SPAdj))
1561 continue;
1562
1563 // Some instructions (e.g. inline asm instructions) can have
1564 // multiple frame indices and/or cause eliminateFrameIndex
1565 // to insert more than one instruction. We need the register
1566 // scavenger to go through all of these instructions so that
1567 // it can update its register information. We keep the
1568 // iterator at the point before insertion so that we can
1569 // revisit them in full.
1570 bool AtBeginning = (I == BB->begin());
1571 if (!AtBeginning) --I;
1572
1573 // If this instruction has a FrameIndex operand, we need to
1574 // use that target machine register info object to eliminate
1575 // it.
1576 TRI.eliminateFrameIndex(MI, SPAdj, i, RS);
1577
1578 // Reset the iterator if we were at the beginning of the BB.
1579 if (AtBeginning) {
1580 I = BB->begin();
1581 DoIncr = false;
1582 }
1583
1584 DidFinishLoop = false;
1585 break;
1586 }
1587
1588 // If we are looking at a call sequence, we need to keep track of
1589 // the SP adjustment made by each instruction in the sequence.
1590 // This includes both the frame setup/destroy pseudos (handled above),
1591 // as well as other instructions that have side effects w.r.t the SP.
1592 // Note that this must come after eliminateFrameIndex, because
1593 // if I itself referred to a frame index, we shouldn't count its own
1594 // adjustment.
1595 if (DidFinishLoop && InsideCallSequence)
1596 SPAdj += TII.getSPAdjust(MI);
1597
1598 if (DoIncr && I != BB->end())
1599 ++I;
1600 }
1601}
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...
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 &)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39