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