52 #define DEBUG_TYPE "structurizecfg" 60 "structurizecfg-skip-uniform-regions",
62 cl::desc(
"Force whether the StructurizeCFG pass skips uniform regions"),
67 using BBValuePair = std::pair<BasicBlock *, Value *>;
89 class NearestCommonDominator {
92 bool ResultIsRemembered =
false;
98 ResultIsRemembered = Remember;
103 if (NewResult != Result)
104 ResultIsRemembered =
false;
106 ResultIsRemembered |= Remember;
111 explicit NearestCommonDominator(
DominatorTree *DomTree) : DT(DomTree) {}
127 bool resultIsRememberedBlock() {
return ResultIsRemembered; }
176 bool SkipUniformRegions;
193 BBPhiMap DeletedPhis;
194 BB2BBVecMap AddedPhis;
197 BranchVector Conditions;
201 BranchVector LoopConds;
208 unsigned getAdjustedLoopDepth(
RegionNode *RN);
220 void insertConditions(
bool Loops);
231 bool IncludeDominator);
245 void wireFlow(
bool ExitUseAllowed,
BasicBlock *LoopEnd);
247 void handleLoops(
bool ExitUseAllowed,
BasicBlock *LoopEnd);
256 explicit StructurizeCFG(
bool SkipUniformRegions_ =
false)
258 SkipUniformRegions(SkipUniformRegions_) {
260 SkipUniformRegions = ForceSkipUniformRegions.
getValue();
268 StringRef getPassName()
const override {
return "Structurize control flow"; }
271 if (SkipUniformRegions)
311 return LI->getLoopFor(SubRegion->
getExit());
314 return LI->getLoopFor(RN->
getEntry());
318 unsigned StructurizeCFG::getAdjustedLoopDepth(
RegionNode *RN) {
321 return LI->getLoopDepth(SubR->
getExit());
324 return LI->getLoopDepth(RN->
getEntry());
328 void StructurizeCFG::orderNodes() {
340 unsigned CurrentLoopDepth = 0;
341 Loop *CurrentLoop =
nullptr;
342 for (
auto I = RPOT.begin(),
E = RPOT.end();
I !=
E; ++
I) {
344 unsigned LoopDepth = getAdjustedLoopDepth(RN);
349 if (LoopDepth < CurrentLoopDepth) {
354 while (
unsigned &BlockCount = LoopBlocks[CurrentLoop]) {
356 if (getAdjustedLoop(cast<RegionNode>(*LoopI)) == CurrentLoop) {
358 Order.push_back(*LoopI);
363 CurrentLoop = getAdjustedLoop(RN);
365 LoopBlocks[CurrentLoop]--;
367 CurrentLoopDepth = LoopDepth;
383 if (Visited.count(Exit))
392 if (Visited.count(Succ))
398 Value *StructurizeCFG::invert(
Value *Condition) {
400 if (
Constant *
C = dyn_cast<Constant>(Condition))
408 if (
Instruction *Inst = dyn_cast<Instruction>(Condition)) {
420 if (
Argument *
Arg = dyn_cast<Argument>(Condition)) {
433 Value *Cond = Invert ? BoolFalse : BoolTrue;
437 if (Idx != (
unsigned)Invert)
444 void StructurizeCFG::gatherPredicates(
RegionNode *N) {
445 RegionInfo *RI = ParentRegion->getRegionInfo();
447 BBPredicates &Pred = Predicates[BB];
448 BBPredicates &LPred = LoopPreds[BB];
452 if (!ParentRegion->contains(
P))
456 if (R == ParentRegion) {
458 BranchInst *Term = cast<BranchInst>(
P->getTerminator());
464 if (Visited.count(
P)) {
469 if (Visited.count(Other) && !
Loops.count(Other) &&
470 !Pred.count(Other) && !Pred.count(
P)) {
472 Pred[Other] = BoolFalse;
477 Pred[
P] = buildCondition(Term, i,
false);
480 LPred[
P] = buildCondition(Term, i,
true);
493 if (Visited.count(Entry))
494 Pred[Entry] = BoolTrue;
496 LPred[Entry] = BoolFalse;
502 void StructurizeCFG::collectInfos() {
515 << (RN->
isSubRegion() ?
"SubRegion with entry: " :
"")
516 << RN->
getEntry()->getName() <<
" Loop Depth: " 517 << LI->getLoopDepth(RN->
getEntry()) <<
"\n");
520 gatherPredicates(RN);
531 void StructurizeCFG::insertConditions(
bool Loops) {
532 BranchVector &Conds = Loops ? LoopConds : Conditions;
533 Value *Default = Loops ? BoolTrue : BoolFalse;
547 BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];
549 NearestCommonDominator Dominator(DT);
550 Dominator.addBlock(Parent);
552 Value *ParentValue =
nullptr;
553 for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
555 Value *Pred = BBAndPred.second;
562 Dominator.addAndRememberBlock(BB);
568 if (!Dominator.resultIsRememberedBlock())
579 PhiMap &Map = DeletedPhis[To];
581 while (Phi.getBasicBlockIndex(From) != -1) {
583 Map[&Phi].push_back(std::make_pair(From, Deleted));
592 Phi.addIncoming(Undef, From);
594 AddedPhis[To].push_back(From);
598 void StructurizeCFG::setPhiValues() {
600 for (
const auto &AddedPhi : AddedPhis) {
602 const BBVector &From = AddedPhi.second;
604 if (!DeletedPhis.count(To))
607 PhiMap &Map = DeletedPhis[To];
608 for (
const auto &PI : Map) {
615 NearestCommonDominator Dominator(DT);
616 Dominator.addBlock(To);
617 for (
const auto &
VI : PI.second) {
619 Dominator.addAndRememberBlock(
VI.first);
622 if (!Dominator.resultIsRememberedBlock())
632 DeletedPhis.erase(To);
634 assert(DeletedPhis.empty());
638 void StructurizeCFG::killTerminator(
BasicBlock *BB) {
645 delPhiValues(BB, *
SI);
648 DA->removeValue(Term);
654 bool IncludeDominator) {
669 delPhiValues(BB, OldExit);
671 addPhiValues(BB, NewExit);
674 if (IncludeDominator) {
678 Dominator = DT->findNearestCommonDominator(Dominator, BB);
684 DT->changeImmediateDominator(NewExit, Dominator);
692 addPhiValues(BB, NewExit);
693 if (IncludeDominator)
694 DT->changeImmediateDominator(NewExit, BB);
701 BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
702 Order.back()->getEntry();
705 DT->addNewBlock(Flow, Dominator);
706 ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
711 BasicBlock *StructurizeCFG::needPrefix(
bool NeedEmpty) {
714 if (!PrevNode->isSubRegion()) {
715 killTerminator(Entry);
724 changeExit(PrevNode, Flow,
true);
725 PrevNode = ParentRegion->getBBNode(Flow);
731 bool ExitUseAllowed) {
732 if (!Order.empty() || !ExitUseAllowed)
733 return getNextFlow(Flow);
736 DT->changeImmediateDominator(Exit, Flow);
737 addPhiValues(Flow, Exit);
742 void StructurizeCFG::setPrevNode(
BasicBlock *BB) {
743 PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
749 BBPredicates &Preds = Predicates[Node->
getEntry()];
750 return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
751 return DT->dominates(BB, Pred.first);
756 bool StructurizeCFG::isPredictableTrue(
RegionNode *Node) {
757 BBPredicates &Preds = Predicates[Node->
getEntry()];
758 bool Dominated =
false;
764 for (std::pair<BasicBlock*, Value*> Pred : Preds) {
766 Value *V = Pred.second;
771 if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
780 void StructurizeCFG::wireFlow(
bool ExitUseAllowed,
785 if (isPredictableTrue(Node)) {
788 changeExit(PrevNode, Node->
getEntry(),
true);
797 BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);
801 addPhiValues(Flow, Entry);
802 DT->changeImmediateDominator(Entry, Flow);
805 while (!Order.empty() && !Visited.count(LoopEnd) &&
806 dominatesPredicates(Entry, Order.
back())) {
807 handleLoops(
false, LoopEnd);
810 changeExit(PrevNode, Next,
false);
815 void StructurizeCFG::handleLoops(
bool ExitUseAllowed,
820 if (!Loops.count(LoopStart)) {
821 wireFlow(ExitUseAllowed, LoopEnd);
825 if (!isPredictableTrue(Node))
826 LoopStart = needPrefix(
true);
829 wireFlow(
false, LoopEnd);
830 while (!Visited.count(LoopEnd)) {
831 handleLoops(
false, LoopEnd);
838 LoopStart->
setName(
"entry.orig");
846 DT->setNewRoot(NewEntry);
850 LoopEnd = needPrefix(
false);
851 BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
853 BoolUndef, LoopEnd));
854 addPhiValues(LoopEnd, LoopStart);
860 void StructurizeCFG::createFlow() {
862 bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);
872 while (!Order.empty()) {
873 handleLoops(EntryDominatesExit,
nullptr);
877 changeExit(PrevNode, Exit, EntryDominatesExit);
879 assert(EntryDominatesExit);
884 void StructurizeCFG::rebuildSSA() {
888 bool Initialized =
false;
891 for (
auto UI =
I.use_begin(),
E =
I.use_end(); UI !=
E;) {
896 }
else if (
PHINode *UserPN = dyn_cast<PHINode>(User)) {
897 if (UserPN->getIncomingBlock(U) == BB)
901 if (DT->dominates(&
I, User))
919 if (!
E->isSubRegion()) {
921 if (!Br || !Br->isConditional())
927 <<
" has uniform terminator\n");
940 if (!Br || !Br->isConditional())
943 if (!Br->getMetadata(UniformMDKindID))
958 if (SkipUniformRegions) {
963 unsigned UniformMDKindID =
964 R->
getEntry()->getContext().getMDKindID(
"structurizecfg.uniform");
965 DA = &getAnalysis<DivergenceAnalysis>();
968 LLVM_DEBUG(
dbgs() <<
"Skipping region with uniform control flow: " << *R
977 if (
E->isSubRegion())
991 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
992 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
997 insertConditions(
false);
998 insertConditions(
true);
1005 DeletedPhis.clear();
1017 return new StructurizeCFG(SkipUniformRegions);
Pass interface - Implemented by all 'passes'.
T * getNodeAs() const
Get the content of this RegionNode.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
Helper class for SSA formation on a set of values defined in multiple blocks.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Compute iterated dominance frontiers using a linear time algorithm.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
static const char *const FlowBlockName
Value * getCondition() const
This defines the Use class.
BlockT * getExit() const
Get the exit BasicBlock of the Region.
bool isSubRegion() const
Is this RegionNode a subregion?
LLVMContext & getContext() const
Get the context in which this basic block lives.
The pass manager to schedule RegionPasses.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
'undef' values are things that do not have specified contents.
unsigned getNumSuccessors() const
A Use represents the edge between a Value definition and its users.
void setName(const Twine &Name)
Change the name of the value.
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
block_range blocks()
Returns a range view of the basic blocks in the region.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
BlockT * getEntry() const
Get the entry BasicBlock of this RegionNode.
Type * getType() const
All values are typed, get the type of this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
bool isUniform(const Value *V) const
const BasicBlock & getEntryBlock() const
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
initializer< Ty > init(const Ty &Val)
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
Subclasses of this class are all able to terminate a basic block.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
void RewriteUseAfterInsertions(Use &U)
Rewrite a use like RewriteUse but handling in-block definitions.
Conditional or Unconditional Branch instruction.
A pass that runs on each Region in a function.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void replaceExit(BlockT *BB)
Replace the exit basic block of the region with the new basic block.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
int getNumOccurrences() const
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
const Instruction & back() const
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static Constant * getNot(Constant *C)
bool isTopLevelRegion() const
Check if a Region is the TopLevel region.
INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG", false, false) INITIALIZE_PASS_END(StructurizeCFG
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
void initializeStructurizeCFGPass(PassRegistry &)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
BlockT * getEntry() const
Get the entry BasicBlock of the Region.
AnalysisUsage & addRequiredID(const void *ID)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
pred_range predecessors(BasicBlock *BB)
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
iterator_range< user_iterator > users()
static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID, const DivergenceAnalysis &DA)
amdgpu Simplify well known AMD library false Value Value * Arg
bool contains(const BlockT *BB) const
Check if the region contains a BasicBlock.
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
void setCondition(Value *V)
RegionT * getParent() const
Get the parent of the Region.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
Legacy analysis pass which computes a DominatorTree.
Value * GetValueAtEndOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live at the end of the specified block...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setIncomingValue(unsigned i, Value *V)
Pass * createStructurizeCFGPass(bool SkipUniformRegions=false)
When SkipUniformRegions is true the structizer will not structurize regions that only contain uniform...
iterator_range< element_iterator > elements()
RegionT * getRegionFor(BlockT *BB) const
Get the smallest region that contains a BasicBlock.
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
const BasicBlock * getParent() const
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.