30#define DEBUG_TYPE "ir"
31STATISTIC(NumInstrRenumberings,
"Number of renumberings across all blocks");
34 "experimental-debuginfo-iterators",
35 cl::desc(
"Enable communicating debuginfo positions through iterators, "
36 "eliminating intrinsics. Has no effect if "
37 "--preserve-input-debuginfo-format=true."),
40 "preserve-input-debuginfo-format", cl::Hidden,
41 cl::desc(
"When set to true, IR files will be processed and printed in "
42 "their current debug info format, regardless of default behaviour "
43 "or other flags passed. Has no effect if input IR does not "
44 "contain debug records or intrinsics. Ignored in llvm-link, "
45 "llvm-lto, and llvm-lto2."));
49 "write-experimental-debuginfo-iterators-to-bitcode", cl::Hidden,
53 assert(IsNewDbgInfoFormat &&
54 "Tried to create a marker in a non new debug-info block!");
56 return I->DebugMarker;
59 I->DebugMarker = Marker;
63DbgMarker *BasicBlock::createMarker(InstListType::iterator It) {
64 assert(IsNewDbgInfoFormat &&
65 "Tried to create a marker in a non new debug-info block!");
67 return createMarker(&*It);
72 setTrailingDbgRecords(
DM);
76void BasicBlock::convertToNewDbgValues() {
77 IsNewDbgInfoFormat =
true;
85 assert(!
I.DebugMarker &&
"DebugMarker already set on old-format instrs?");
90 DVI->eraseFromParent();
97 DLI->eraseFromParent();
101 if (DbgVarRecs.
empty())
115void BasicBlock::convertFromNewDbgValues() {
117 IsNewDbgInfoFormat =
false;
122 for (
auto &Inst : *
this) {
123 if (!Inst.DebugMarker)
128 InstList.insert(Inst.getIterator(),
129 DR.createDebugIntrinsic(getModule(),
nullptr));
137 assert(!getTrailingDbgRecords());
141void BasicBlock::dumpDbgValues()
const {
142 for (
auto &Inst : *
this) {
143 if (!Inst.DebugMarker)
146 dbgs() <<
"@ " << Inst.DebugMarker <<
" ";
147 Inst.DebugMarker->dump();
152void BasicBlock::setIsNewDbgInfoFormat(
bool NewFlag) {
153 if (NewFlag && !IsNewDbgInfoFormat)
154 convertToNewDbgValues();
155 else if (!NewFlag && IsNewDbgInfoFormat)
156 convertFromNewDbgValues();
158void BasicBlock::setNewDbgInfoFormatFlag(
bool NewFlag) {
159 IsNewDbgInfoFormat = NewFlag;
164 return F->getValueSymbolTable();
169 return getType()->getContext();
187 insertInto(NewParent, InsertBefore);
190 "Cannot insert block before another block with no function!");
192 end().getNodePtr()->setParent(
this);
199 assert(NewParent &&
"Expected a parent");
200 assert(!Parent &&
"Already has a parent");
205 NewParent->
insert(NewParent->
end(),
this);
210BasicBlock::~BasicBlock() {
211 validateInstrOrdering();
219 if (hasAddressTaken()) {
220 assert(!use_empty() &&
"There should be at least one blockaddress!");
223 while (!use_empty()) {
231 assert(
getParent() ==
nullptr &&
"BasicBlock still linked into the program!");
233 for (
auto &Inst : *
this) {
234 if (!Inst.DebugMarker)
236 Inst.DebugMarker->eraseFromParent();
241void BasicBlock::setParent(
Function *parent) {
243 if (Parent != parent)
244 Number = parent ? parent->NextBlockNum++ : -1u;
245 InstList.setSymTabObject(&Parent, parent);
250BasicBlock::instructionsWithoutDebug(
bool SkipPseudoOp)
const {
252 return !isa<DbgInfoIntrinsic>(
I) &&
253 !(SkipPseudoOp && isa<PseudoProbeInst>(
I));
260BasicBlock::instructionsWithoutDebug(
bool SkipPseudoOp) {
262 return !isa<DbgInfoIntrinsic>(
I) &&
263 !(SkipPseudoOp && isa<PseudoProbeInst>(
I));
270BasicBlock::sizeWithoutDebug()
const {
275void BasicBlock::removeFromParent() {
276 getParent()->getBasicBlockList().remove(getIterator());
280 return getParent()->getBasicBlockList().erase(getIterator());
287void BasicBlock::moveAfter(
BasicBlock *MovePos) {
292const Module *BasicBlock::getModule()
const {
296const DataLayout &BasicBlock::getDataLayout()
const {
297 return getModule()->getDataLayout();
300const CallInst *BasicBlock::getTerminatingMustTailCall()
const {
301 if (InstList.empty())
303 const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
304 if (!RI || RI == &InstList.front())
316 if (
auto *BI = dyn_cast<BitCastInst>(Prev)) {
319 if (!Prev || RV != Prev)
324 if (
auto *CI = dyn_cast<CallInst>(Prev)) {
325 if (CI->isMustTailCall())
331const CallInst *BasicBlock::getTerminatingDeoptimizeCall()
const {
332 if (InstList.empty())
334 auto *RI = dyn_cast<ReturnInst>(&InstList.back());
335 if (!RI || RI == &InstList.front())
338 if (
auto *CI = dyn_cast_or_null<CallInst>(RI->
getPrevNode()))
339 if (
Function *
F = CI->getCalledFunction())
340 if (
F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
346const CallInst *BasicBlock::getPostdominatingDeoptimizeCall()
const {
351 if (!Visited.
insert(Succ).second)
358const Instruction *BasicBlock::getFirstMayFaultInst()
const {
359 if (InstList.empty())
362 if (isa<LoadInst>(
I) || isa<StoreInst>(
I) || isa<CallBase>(
I))
367const Instruction* BasicBlock::getFirstNonPHI()
const {
369 if (!isa<PHINode>(
I))
386const Instruction *BasicBlock::getFirstNonPHIOrDbg(
bool SkipPseudoOp)
const {
388 if (isa<PHINode>(
I) || isa<DbgInfoIntrinsic>(
I))
391 if (SkipPseudoOp && isa<PseudoProbeInst>(
I))
400BasicBlock::getFirstNonPHIOrDbgOrLifetime(
bool SkipPseudoOp)
const {
402 if (isa<PHINode>(
I) || isa<DbgInfoIntrinsic>(
I))
405 if (
I.isLifetimeStartOrEnd())
408 if (SkipPseudoOp && isa<PseudoProbeInst>(
I))
422 if (InsertPt->isEHPad()) ++InsertPt;
426 InsertPt.setHeadBit(
true);
436 if (InsertPt->isEHPad())
439 if (isEntryBlock()) {
441 while (InsertPt !=
End &&
442 (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) ||
443 isa<PseudoProbeInst>(*InsertPt))) {
444 if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) {
445 if (!AI->isStaticAlloca())
454void BasicBlock::dropAllReferences() {
456 I.dropAllReferences();
459const BasicBlock *BasicBlock::getSinglePredecessor()
const {
461 if (PI ==
E)
return nullptr;
464 return (PI ==
E) ? ThePred :
nullptr ;
467const BasicBlock *BasicBlock::getUniquePredecessor()
const {
469 if (PI ==
E)
return nullptr;
472 for (;PI !=
E; ++PI) {
481bool BasicBlock::hasNPredecessors(
unsigned N)
const {
485bool BasicBlock::hasNPredecessorsOrMore(
unsigned N)
const {
489const BasicBlock *BasicBlock::getSingleSuccessor()
const {
491 if (
SI ==
E)
return nullptr;
494 return (
SI ==
E) ? TheSucc :
nullptr ;
497const BasicBlock *BasicBlock::getUniqueSuccessor()
const {
499 if (
SI ==
E)
return nullptr;
502 for (;
SI !=
E; ++
SI) {
512 PHINode *
P = empty() ? nullptr : dyn_cast<PHINode>(&*
begin());
513 return make_range<phi_iterator>(
P,
nullptr);
516void BasicBlock::removePredecessor(
BasicBlock *Pred,
517 bool KeepOneInputPHIs) {
520 "Pred is not a predecessor!");
523 if (empty() || !isa<PHINode>(
begin()))
526 unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
528 Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
529 if (KeepOneInputPHIs)
538 if (
Value *PhiConstant =
Phi.hasConstantValue()) {
539 Phi.replaceAllUsesWith(PhiConstant);
540 Phi.eraseFromParent();
545bool BasicBlock::canSplitPredecessors()
const {
547 if (isa<LandingPadInst>(FirstNonPHI))
557bool BasicBlock::isLegalToHoistInto()
const {
558 auto *
Term = getTerminator();
568 return !
Term->isSpecialTerminator();
571bool BasicBlock::isEntryBlock()
const {
573 assert(
F &&
"Block must have a parent function to use this API");
574 return this == &
F->getEntryBlock();
580 return splitBasicBlockBefore(
I, BBName);
582 assert(getTerminator() &&
"Can't use splitBasicBlock on degenerate BB!");
584 "Trying to get me to create degenerate basic block!");
596 BranchInst *BI = BranchInst::Create(New,
this);
604 New->replaceSuccessorsPhiUsesWith(
this, New);
608BasicBlock *BasicBlock::splitBasicBlockBefore(iterator
I,
const Twine &BBName) {
610 "Can't use splitBasicBlockBefore on degenerate BB!");
612 "Trying to get me to create degenerate basic block!");
614 assert((!isa<PHINode>(*
I) || getSinglePredecessor()) &&
615 "cannot split on multi incoming phis");
635 this->replacePhiUsesWith(Pred, New);
638 BranchInst *BI = BranchInst::Create(
this, New);
655 PHINode *PN = dyn_cast<PHINode>(&
I);
662void BasicBlock::replaceSuccessorsPhiUsesWith(
BasicBlock *Old,
670 Succ->replacePhiUsesWith(Old, New);
673void BasicBlock::replaceSuccessorsPhiUsesWith(
BasicBlock *New) {
674 this->replaceSuccessorsPhiUsesWith(
this, New);
677bool BasicBlock::isLandingPad()
const {
678 return isa<LandingPadInst>(getFirstNonPHI());
682 return dyn_cast<LandingPadInst>(getFirstNonPHI());
685std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight()
const {
687 if (
MDNode *MDIrrLoopHeader =
689 MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
690 if (MDName->
getString() ==
"loop_header_weight") {
691 auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
692 return std::optional<uint64_t>(CI->getValue().getZExtValue());
699 while (isa<DbgInfoIntrinsic>(It))
704void BasicBlock::renumberInstructions() {
710 BasicBlockBits
Bits = getBasicBlockBits();
711 Bits.InstrOrderValid =
true;
712 setBasicBlockBits(Bits);
714 NumInstrRenumberings++;
717void BasicBlock::flushTerminatorDbgRecords() {
728 if (!IsNewDbgInfoFormat)
737 DbgMarker *TrailingDbgRecords = getTrailingDbgRecords();
738 if (!TrailingDbgRecords)
743 Term->DebugMarker->absorbDebugValues(*TrailingDbgRecords,
false);
745 deleteTrailingDbgRecords();
768 if (!IsNewDbgInfoFormat)
772 bool InsertAtHead = Dest.getHeadBit();
773 bool ReadFromHead =
First.getHeadBit();
780 DbgMarker *SrcTrailingDbgRecords = Src->getTrailingDbgRecords();
781 if (!SrcTrailingDbgRecords)
784 Dest->adoptDbgRecords(Src, Src->end(), InsertAtHead);
786 assert(!Src->getTrailingDbgRecords());
793 if (Src->empty() || First != Src->begin() || !ReadFromHead)
797 if (!
First->hasDbgRecords())
800 createMarker(Dest)->absorbDebugValues(*
First->DebugMarker, InsertAtHead);
840 DbgMarker *MoreDanglingDbgRecords =
nullptr;
841 DbgMarker *OurTrailingDbgRecords = getTrailingDbgRecords();
842 if (Dest ==
end() && !Dest.getHeadBit() && OurTrailingDbgRecords) {
845 if (!
First.getHeadBit() &&
First->hasDbgRecords()) {
846 MoreDanglingDbgRecords = Src->getMarker(First);
850 if (
First->hasDbgRecords()) {
858 First->adoptDbgRecords(
this,
end(),
true);
862 DbgMarker *CurMarker = Src->createMarker(&*First);
866 deleteTrailingDbgRecords();
867 First.setHeadBit(
true);
871 spliceDebugInfoImpl(Dest, Src, First, Last);
875 if (!MoreDanglingDbgRecords)
880 DbgMarker *LastMarker = Src->createMarker(Last);
891 bool InsertAtHead = Dest.getHeadBit();
892 bool ReadFromHead =
First.getHeadBit();
895 bool ReadFromTail = !
Last.getTailBit();
896 bool LastIsEnd = (
Last == Src->end());
962 if ((DestMarker = getMarker(Dest))) {
964 assert(DestMarker == getTrailingDbgRecords());
965 deleteTrailingDbgRecords();
973 if (ReadFromTail && Src->getMarker(Last)) {
974 DbgMarker *FromLast = Src->getMarker(Last);
978 assert(FromLast == Src->getTrailingDbgRecords());
979 createMarker(Dest)->absorbDebugValues(*FromLast,
true);
981 Src->deleteTrailingDbgRecords();
984 Dest->adoptDbgRecords(Src, Last,
true);
986 assert(!Src->getTrailingDbgRecords());
989 DbgMarker *OntoDest = createMarker(Dest);
997 if (!ReadFromHead &&
First->hasDbgRecords()) {
998 if (Last != Src->end()) {
999 Last->adoptDbgRecords(Src, First,
true);
1001 DbgMarker *OntoLast = Src->createMarker(Last);
1002 DbgMarker *FromFirst = Src->createMarker(First);
1013 DbgMarker *NewDestMarker = createMarker(Dest);
1022 DbgMarker *FirstMarker = createMarker(First);
1029void BasicBlock::splice(iterator Dest,
BasicBlock *Src, iterator First,
1031 assert(Src->IsNewDbgInfoFormat == IsNewDbgInfoFormat);
1033#ifdef EXPENSIVE_CHECKS
1035 auto FromBBEnd = Src->end();
1036 for (
auto It = First; It !=
Last; ++It)
1037 assert(It != FromBBEnd &&
"FromBeginIt not before FromEndIt!");
1042 if (First == Last) {
1043 spliceDebugInfoEmptyBlock(Dest, Src, First, Last);
1048 if (IsNewDbgInfoFormat)
1049 spliceDebugInfo(Dest, Src, First, Last);
1052 getInstList().splice(Dest, Src->getInstList(), First, Last);
1054 flushTerminatorDbgRecords();
1058 assert(IsNewDbgInfoFormat);
1059 assert(
I->getParent() ==
this);
1061 iterator NextIt = std::next(
I->getIterator());
1062 DbgMarker *NextMarker = createMarker(NextIt);
1066void BasicBlock::insertDbgRecordBefore(
DbgRecord *DR,
1067 InstListType::iterator Where) {
1068 assert(Where ==
end() || Where->getParent() ==
this);
1069 bool InsertAtHead = Where.getHeadBit();
1071 M->insertDbgRecord(DR, InsertAtHead);
1075 return getMarker(std::next(
I->getIterator()));
1078DbgMarker *BasicBlock::getMarker(InstListType::iterator It) {
1083 return It->DebugMarker;
1086void BasicBlock::reinsertInstInDbgRecords(
1087 Instruction *
I, std::optional<DbgRecord::self_iterator> Pos) {
1143void BasicBlock::validateInstrOrdering()
const {
1144 if (!isInstrOrderValid())
1149 "cached instruction ordering is incorrect");
1155void BasicBlock::setTrailingDbgRecords(
DbgMarker *foo) {
1156 getContext().pImpl->setTrailingDbgRecords(
this, foo);
1159DbgMarker *BasicBlock::getTrailingDbgRecords() {
1160 return getContext().pImpl->getTrailingDbgRecords(
this);
1163void BasicBlock::deleteTrailingDbgRecords() {
1164 getContext().pImpl->deleteTrailingDbgRecords(
this);
VarLocInsertPt getNextNode(const DbgRecord *DVR)
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
bool WriteNewDbgInfoFormatToBitcode
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
llvm::cl::opt< bool > UseNewDbgInfoFormat
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
cl::opt< bool, true > WriteNewDbgInfoFormatToBitcode2("write-experimental-debuginfo-iterators-to-bitcode", cl::Hidden, cl::location(WriteNewDbgInfoFormatToBitcode), cl::init(true))
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
an instruction to allocate memory on the stack
LLVM Basic Block Representation.
void invalidateOrders()
Mark instruction ordering invalid. Done on every instruction insert.
InstListType::const_iterator const_iterator
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
const Function * getParent() const
Return the enclosing method, or null if none.
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
The address of a basic block.
Conditional or Unconditional Branch instruction.
This class represents a function call, abstracting a target machine's calling convention.
This is an important base class in LLVM.
void destroyConstant()
Called if some element of this constant is no longer valid.
A parsed version of the target data layout string in and methods for querying it.
This represents the llvm.dbg.label instruction.
Records a position in IR for a source label (DILabel).
Per-instruction record of debug-info.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
void absorbDebugValues(DbgMarker &Src, bool InsertAtHead)
Transfer any DbgRecords from Src into this DbgMarker.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange()
Produce a range over all the DbgRecords in this Marker.
simple_ilist< DbgRecord > StoredDbgRecords
List of DbgRecords, the non-instruction equivalent of llvm.dbg.
void insertDbgRecord(DbgRecord *New, bool InsertAtHead)
Insert a DbgRecord into this DbgMarker, at the end of the list.
Base class for non-instruction debug metadata records that have positions within IR.
This is the common base class for debug info intrinsics for variables.
Record of a variable value-assignment, aka a non instruction representation of the dbg....
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
Function::iterator insert(Function::iterator Position, BasicBlock *BB)
Insert BB in the basic block list at Position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
This is an important class for using LLVM in a threaded context.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
StringRef getString() const
A Module instance is used to store all the information related to an LLVM module.
void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New)
Replace every incoming basic block Old to basic block New.
Return a value (possibly void), from a function.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
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.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static IntegerType * getInt32Ty(LLVMContext &C)
Value * getOperand(unsigned i) const
This class provides a symbol table of name/value pairs.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Specialization of filter_iterator_base for forward iteration only.
self_iterator getIterator()
base_list_type::iterator iterator
A range adaptor for a pair of iterators.
NodeAddr< PhiNode * > Phi
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
const_iterator end(StringRef path)
Get end iterator over path.
This is an optimization pass for GlobalISel generic memory operations.
auto pred_end(const MachineBasicBlock *BB)
auto successors(const MachineBasicBlock *BB)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It)
Advance It while it points to a debug instruction and return the result.
bool hasNItems(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has exactly N items.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
void invalidateParentIListOrdering(ParentClass *Parent)
Notify basic blocks when an instruction is inserted.
auto pred_begin(const MachineBasicBlock *BB)
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Option to add extra bits to the ilist_iterator.
Option to add a pointer to this list's owner in every node.