85 #define DEBUG_TYPE "loop-unswitch" 87 STATISTIC(NumBranches,
"Number of branches unswitched");
88 STATISTIC(NumSwitches,
"Number of switches unswitched");
89 STATISTIC(NumGuards,
"Number of guards unswitched");
90 STATISTIC(NumSelects ,
"Number of selects unswitched");
91 STATISTIC(NumTrivial ,
"Number of unswitches that are trivial");
92 STATISTIC(NumSimplify,
"Number of simplifications of unswitched code");
93 STATISTIC(TotalInsts,
"Total number of instructions analyzed");
103 class LUAnalysisCache {
104 using UnswitchedValsMap =
106 using UnswitchedValsIt = UnswitchedValsMap::iterator;
108 struct LoopProperties {
109 unsigned CanBeUnswitchedCount;
110 unsigned WasUnswitchedCount;
111 unsigned SizeEstimation;
112 UnswitchedValsMap UnswitchedVals;
117 using LoopPropsMap = std::map<const Loop *, LoopProperties>;
118 using LoopPropsMapIt = LoopPropsMap::iterator;
120 LoopPropsMap LoopsProperties;
121 UnswitchedValsMap *CurLoopInstructions =
nullptr;
122 LoopProperties *CurrentLoopProperties =
nullptr;
141 LUAnalysisCache() : MaxSize(
Threshold) {}
149 void forgetLoop(
const Loop *L);
161 bool CostAllowsUnswitching();
166 void cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
170 class LoopUnswitch :
public LoopPass {
177 std::vector<Loop*> LoopProcessWorklist;
179 LUAnalysisCache BranchesInfo;
181 bool OptimizeForSize;
182 bool redoLoop =
false;
184 Loop *currentLoop =
nullptr;
187 std::unique_ptr<MemorySSAUpdater> MSSAU;
197 std::vector<BasicBlock*> LoopBlocks;
199 std::vector<BasicBlock*> NewBlocks;
201 bool hasBranchDivergence;
206 explicit LoopUnswitch(
bool Os =
false,
bool hasBranchDivergence =
false)
207 :
LoopPass(ID), OptimizeForSize(Os),
208 hasBranchDivergence(hasBranchDivergence) {
213 bool processCurrentLoop();
214 bool isUnreachableDueToPreviousUnswitching(
BasicBlock *);
226 if (hasBranchDivergence)
232 void releaseMemory()
override {
233 BranchesInfo.forgetLoop(currentLoop);
236 void initLoopData() {
243 void SplitExitEdges(
Loop *L,
246 bool TryTrivialLoopUnswitch(
bool &Changed);
255 void RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
258 void EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
263 void SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L);
277 LoopPropsMapIt PropsIt;
279 std::tie(PropsIt, Inserted) =
280 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
282 LoopProperties &Props = PropsIt->second;
303 Props.SizeEstimation = Metrics.
NumInsts;
304 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
305 Props.WasUnswitchedCount = 0;
306 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
310 <<
", contents cannot be " 317 CurrentLoopProperties = &Props;
318 CurLoopInstructions = &Props.UnswitchedVals;
324 void LUAnalysisCache::forgetLoop(
const Loop *L) {
325 LoopPropsMapIt LIt = LoopsProperties.find(L);
327 if (LIt != LoopsProperties.end()) {
328 LoopProperties &Props = LIt->second;
329 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
330 Props.SizeEstimation;
331 LoopsProperties.erase(LIt);
334 CurrentLoopProperties =
nullptr;
335 CurLoopInstructions =
nullptr;
342 (*CurLoopInstructions)[
SI].insert(V);
346 bool LUAnalysisCache::isUnswitched(
const SwitchInst *SI,
const Value *V) {
347 return (*CurLoopInstructions)[
SI].count(V);
350 bool LUAnalysisCache::CostAllowsUnswitching() {
351 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
357 void LUAnalysisCache::cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
359 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
360 LoopProperties &OldLoopProps = *CurrentLoopProperties;
361 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
365 --OldLoopProps.CanBeUnswitchedCount;
366 ++OldLoopProps.WasUnswitchedCount;
367 NewLoopProps.WasUnswitchedCount = 0;
368 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
369 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
370 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
372 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
377 for (UnswitchedValsIt
I = Insts.begin();
I != Insts.end(); ++
I) {
380 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
381 assert(NewInst &&
"All instructions that are in SrcBB must be in VMap.");
383 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
400 return new LoopUnswitch(Os, hasBranchDivergence);
426 auto CacheIt = Cache.
find(Cond);
427 if (CacheIt != Cache.
end())
428 return CacheIt->second;
438 if (isa<Constant>(Cond))
return nullptr;
450 if (BO->getOpcode() == Instruction::And ||
451 BO->getOpcode() == Instruction::Or) {
454 switch (ParentChain) {
456 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
460 NewChain = BO->getOpcode() == Instruction::Or ?
OC_OpChainOr :
464 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
478 ParentChain = NewChain;
483 ParentChain, Cache, MSSAU)) {
489 ParentChain = NewChain;
491 ParentChain, Cache, MSSAU)) {
498 Cache[Cond] =
nullptr;
505 static std::pair<Value *, OperatorChain>
515 "Do not expect a partial LIV with mixed operator chain");
516 return {FCond, OpChain};
523 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
525 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
527 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
529 MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
530 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
531 assert(DT &&
"Cannot update MemorySSA without a valid DomTree.");
543 bool Changed =
false;
549 Changed |= processCurrentLoop();
560 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(
BasicBlock *BB) {
563 while (currentLoop->
contains(DomBB)) {
567 DomBB = Node->getBlock();
573 if (!isa<ConstantInt>(Cond))
601 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
604 auto hasUndefInPHI = [](
PHINode &PN) {
605 for (
Value *Opd : PN.incoming_values()) {
606 if (isa<UndefValue>(Opd))
613 if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
617 if (isa<UndefValue>(SI.getTrueValue()) ||
618 isa<UndefValue>(SI.getFalseValue()))
624 if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
630 bool LoopUnswitch::processCurrentLoop() {
631 bool Changed =
false;
650 if (!BranchesInfo.countLoop(
651 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
657 if (TryTrivialLoopUnswitch(Changed)) {
663 if (OptimizeForSize ||
683 for (
const auto BB : currentLoop->
blocks()) {
684 for (
auto &
I : *BB) {
687 if (CS.isConvergent())
689 if (
auto *II = dyn_cast<InvokeInst>(&
I))
690 if (!II->getUnwindDest()->canSplitPredecessors())
692 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
693 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
700 Changed, MSSAU.get())
725 if (SanitizeMemory &&
729 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
733 if (isUnreachableDueToPreviousUnswitching(*
I))
738 if (BI->isConditional()) {
742 Changed, MSSAU.get())
750 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
754 std::tie(LoopCond, OpChain) =
758 if (LoopCond && NumCases) {
769 if (BranchesInfo.isUnswitched(SI, AllZero))
772 UnswitchVal = AllZero;
777 if (BranchesInfo.isUnswitched(SI, AllOne))
780 UnswitchVal = AllOne;
783 "Expect to unswitch on trivial chain");
787 for (
auto Case : SI->
cases()) {
788 Constant *UnswitchValCandidate = Case.getCaseValue();
789 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
790 UnswitchVal = UnswitchValCandidate;
799 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
805 BranchesInfo.setUnswitched(SI, UnswitchVal);
814 if (
SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
816 Changed, MSSAU.get())
818 if (LoopCond && UnswitchIfProfitable(LoopCond,
836 std::set<BasicBlock*> &Visited) {
837 if (!Visited.insert(BB).second) {
845 if (ExitBB)
return false;
860 if (
I.mayHaveSideEffects())
870 std::set<BasicBlock*> Visited;
881 bool LoopUnswitch::UnswitchIfProfitable(
Value *LoopCond,
Constant *Val,
884 if (!BranchesInfo.CostAllowsUnswitching()) {
887 <<
" at non-trivial condition '" << *Val
888 <<
"' == " << *LoopCond <<
"\n" 889 <<
". Cost too high.\n");
892 if (hasBranchDivergence &&
893 getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
896 <<
" at non-trivial condition '" << *Val
897 <<
"' == " << *LoopCond <<
"\n" 898 <<
". Condition is divergent.\n");
902 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
933 void LoopUnswitch::EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
939 assert(TrueDest != FalseDest &&
"Branch targets should be different");
942 Value *BranchVal = LIC;
943 bool Swapped =
false;
944 if (!isa<ConstantInt>(Val) ||
956 auto *OldBranchParent = OldBranch->
getParent();
960 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
972 if (TrueDest != OldBranchSucc)
974 if (FalseDest != OldBranchSucc)
978 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
984 MSSAU->applyUpdates(Updates, *DT);
1000 void LoopUnswitch::UnswitchTrivialCondition(
Loop *L,
Value *Cond,
Constant *Val,
1005 <<
" blocks] in Function " 1007 <<
" on cond: " << *Val <<
" == " << *Cond <<
"\n");
1010 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1011 SEWP->getSE().forgetTopmostLoop(L);
1033 assert(OldBranch &&
"Failed to split the preheader");
1034 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1047 RewriteLoopBodyWithConditionConstant(L, Cond, Val,
false);
1058 bool LoopUnswitch::TryTrivialLoopUnswitch(
bool &Changed) {
1084 if (!currentLoop->
contains(CurrentBB) || !Visited.
insert(CurrentBB).second)
1091 if (
I.mayHaveSideEffects())
1094 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1095 if (BI->isUnconditional()) {
1096 CurrentBB = BI->getSuccessor(0);
1098 CurrentBB = BI->getSuccessor(0);
1100 CurrentBB = BI->getSuccessor(1);
1105 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1118 CurrentTerm = CurrentBB->getTerminator();
1126 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1128 if (!BI->isConditional())
1132 Changed, MSSAU.get())
1137 if (!LoopCond || LoopCond != BI->getCondition())
1145 BI->getSuccessor(0)))) {
1148 BI->getSuccessor(1)))) {
1154 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1160 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1164 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1167 Changed, MSSAU.get())
1181 for (
auto Case : SI->
cases()) {
1183 if ((LoopExitCandidate =
1190 if (BranchesInfo.isUnswitched(SI, CaseVal))
1192 LoopExitBB = LoopExitCandidate;
1200 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1203 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1207 BranchesInfo.setUnswitched(SI, CondVal);
1216 void LoopUnswitch::SplitExitEdges(
Loop *L,
1219 for (
unsigned i = 0,
e = ExitBlocks.
size(); i !=
e; ++i) {
1234 void LoopUnswitch::UnswitchNontrivialCondition(
Value *LIC,
Constant *Val,
1239 <<
" blocks] in Function " << F->
getName() <<
" when '" 1240 << *Val <<
"' == " << *LIC <<
"\n");
1244 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1245 SEWP->getSE().forgetTopmostLoop(L);
1256 SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1257 LoopBlocks.push_back(NewPreheader);
1267 SplitExitEdges(L, ExitBlocks);
1274 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.
begin(), ExitBlocks.
end());
1279 NewBlocks.reserve(LoopBlocks.size());
1281 for (
unsigned i = 0,
e = LoopBlocks.size(); i !=
e; ++i) {
1284 NewBlocks.push_back(NewBB);
1285 VMap[LoopBlocks[i]] = NewBB;
1293 NewBlocks[0]->getIterator(), F->
end());
1300 BranchesInfo.cloneData(NewLoop, L, VMap);
1309 for (
unsigned i = 0,
e = ExitBlocks.
size(); i !=
e; ++i) {
1310 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1312 if (
Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1313 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1316 "Exit block should have been split to have one successor!");
1321 for (
PHINode &PN : ExitSucc->phis()) {
1322 Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
1325 PN.addIncoming(V, NewExit);
1330 &*ExitSucc->getFirstInsertionPt());
1343 for (
unsigned i = 0,
e = NewBlocks.size(); i !=
e; ++i) {
1347 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
1348 if (II->getIntrinsicID() == Intrinsic::assume)
1356 "Preheader splitting did not work correctly!");
1363 MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1367 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1372 MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1381 LoopProcessWorklist.push_back(NewLoop);
1393 RewriteLoopBodyWithConditionConstant(L, LIC, Val,
false);
1398 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1399 LICHandle && !isa<Constant>(LICHandle))
1400 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val,
true);
1408 std::vector<Instruction*> &Worklist) {
1410 Worklist.erase(
std::remove(Worklist.begin(), Worklist.end(),
I),
1417 std::vector<Instruction *> &Worklist,
Loop *L,
1419 LLVM_DEBUG(
dbgs() <<
"Replace with '" << *V <<
"': " << *I <<
"\n");
1424 Worklist.push_back(
Use);
1428 Worklist.push_back(cast<Instruction>(U));
1443 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
1446 assert(!isa<Constant>(LIC) &&
"Why are we unswitching on a constant?");
1457 std::vector<Instruction*> Worklist;
1462 if (IsEqual || (isa<ConstantInt>(Val) &&
1469 !cast<ConstantInt>(Val)->getZExtValue());
1475 Worklist.push_back(UI);
1481 SimplifyCode(Worklist, L);
1495 if (
Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1511 Worklist.push_back(UI);
1515 if (!SI || !isa<ConstantInt>(Val))
continue;
1538 if (Latch && DT->
dominates(SISucc, Latch))
1545 SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
1558 NewSISucc->getTerminator()->eraseFromParent();
1562 for (
PHINode &PN : NewSISucc->phis())
1571 SimplifyCode(Worklist, L);
1582 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L) {
1584 while (!Worklist.empty()) {
1586 Worklist.pop_back();
1595 Worklist.push_back(
Use);
1599 MSSAU->removeMemoryAccess(I);
1615 if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1616 if (BI->isUnconditional()) {
1623 if (!SinglePred)
continue;
1624 assert(SinglePred == Pred &&
"CFG broken");
1630 auto SuccIt = Succ->
begin();
1631 while (
PHINode *PN = dyn_cast<PHINode>(SuccIt++)) {
1632 for (
unsigned It = 0,
E = PN->getNumOperands(); It !=
E; ++It)
1633 if (
Instruction *
Use = dyn_cast<Instruction>(PN->getOperand(It)))
1634 Worklist.push_back(
Use);
1636 Worklist.push_back(cast<Instruction>(U));
1663 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Pass interface - Implemented by all 'passes'.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void initializeLoopUnswitchPass(PassRegistry &)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
bool VerifyMemorySSA
Enables verification of MemorySSA.
This class represents lattice values for constants.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
ArrayRef< BasicBlock *>::const_iterator block_iterator
OperatorChain
Operator chain lattice.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
void push_back(const T &Elt)
static void ReplaceUsesOfWith(Instruction *I, Value *V, std::vector< Instruction *> &Worklist, Loop *L, LPPassManager *LPM, MemorySSAUpdater *MSSAU)
When we find that I really equals V, remove I from the program, replacing all uses with V and update ...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
Value * getCondition() const
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...
bool isVectorTy() const
True if this is an instance of VectorType.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
bool notDuplicatable
True if this function cannot be duplicated.
LLVMContext & getContext() const
Get the context in which this basic block lives.
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
static Loop * CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Option class for critical edge splitting.
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
A Use represents the edge between a Value definition and its users.
Encapsulates MemorySSA, including all data associated with memory accesses.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockT * getHeader() const
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...
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const
Returns true if the instruction in a loop is guaranteed to execute at least once. ...
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
iterator find(const KeyT &Val)
static Value * FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed, OperatorChain &ParentChain, DenseMap< Value *, Value *> &Cache, MemorySSAUpdater *MSSAU)
Cond is a condition that occurs in L.
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
iterator find(const_arg_type_t< KeyT > Val)
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
This function has undefined behavior.
DomTreeNodeBase * getIDom() const
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...
static void RemoveFromWorklist(Instruction *I, std::vector< Instruction *> &Worklist)
Remove all instances of I from the worklist vector specified.
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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...
Represent the analysis usage information of a pass.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, BasicBlock *&ExitBB, std::set< BasicBlock *> &Visited)
Check to see if all paths from BB exit the loop with no side effects (including infinite loops)...
This instruction compares its operands according to the predicate given to the constructor.
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.
self_iterator getIterator()
static bool EqualityPropUnSafe(Value &LoopCond)
FIXME: Remove this workaround when freeze related patches are done.
INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops", false, false) INITIALIZE_PASS_END(LoopUnswitch
static Constant * getAllOnesValue(Type *Ty)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void deleteSimpleAnalysisValue(Value *V, Loop *L)
deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes that implement simple anal...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
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.
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
LoopT * AllocateLoop(ArgsTy &&... Args)
CHAIN = SC CHAIN, Imm128 - System call.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
Pass * createLoopUnswitchPass(bool OptimizeForSize=false, bool hasBranchDivergence=false)
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LoopT * getParentLoop() const
Predicate getPredicate() const
Return the predicate for this instruction.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
void cloneBasicBlockSimpleAnalysis(BasicBlock *From, BasicBlock *To, Loop *L)
SimpleAnalysis - Provides simple interface to update analysis info maintained by various passes...
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
block_iterator block_end() const
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
CaseIt case_default()
Returns an iterator that points to the default case.
bool isUnconditional() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
unsigned NumInsts
Number of instructions in the analyzed blocks.
iterator_range< block_iterator > blocks() const
static BasicBlock * isTrivialLoopExitBlock(Loop *L, BasicBlock *BB)
Return true if the specified block unconditionally leads to an exit from the specified loop...
block_iterator block_begin() const
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...