123 using namespace llvm;
127 #define DEBUG_TYPE "newgvn" 129 STATISTIC(NumGVNInstrDeleted,
"Number of instructions deleted");
130 STATISTIC(NumGVNBlocksDeleted,
"Number of blocks deleted");
131 STATISTIC(NumGVNOpsSimplified,
"Number of Expressions simplified");
132 STATISTIC(NumGVNPhisAllSame,
"Number of PHIs whos arguments are all the same");
134 "Maximum Number of iterations it took to converge GVN");
135 STATISTIC(NumGVNLeaderChanges,
"Number of leader changes");
136 STATISTIC(NumGVNSortedLeaderChanges,
"Number of sorted leader changes");
137 STATISTIC(NumGVNAvoidedSortedLeaderChanges,
138 "Number of avoided sorted leader changes");
139 STATISTIC(NumGVNDeadStores,
"Number of redundant/dead stores eliminated");
140 STATISTIC(NumGVNPHIOfOpsCreated,
"Number of PHI of ops created");
142 "Number of things eliminated using PHI of ops");
144 "Controls which instructions are value numbered");
146 "Controls which instructions we create phi of ops for");
163 namespace GVNExpression {
187 TarjanSCC() : Components(1) {}
190 if (Root.lookup(Start) == 0)
195 unsigned ComponentID = ValueToComponent.lookup(V);
198 "Asking for a component for a value we never processed");
199 return Components[ComponentID];
206 unsigned int OurDFS = DFSNum;
208 if (
auto *InstOp = dyn_cast<Instruction>(
Op)) {
209 if (Root.lookup(
Op) == 0)
211 if (!InComponent.count(
Op))
212 Root[I] = std::min(Root.lookup(I), Root.lookup(
Op));
219 if (Root.lookup(I) == OurDFS) {
220 unsigned ComponentID = Components.size();
221 Components.resize(Components.size() + 1);
222 auto &Component = Components.back();
225 InComponent.insert(I);
226 ValueToComponent[
I] = ComponentID;
228 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
229 auto *Member = Stack.back();
231 Component.insert(Member);
232 InComponent.insert(Member);
233 ValueToComponent[Member] = ComponentID;
242 unsigned int DFSNum = 1;
292 class CongruenceClass {
294 using MemberType =
Value;
299 explicit CongruenceClass(
unsigned ID) : ID(ID) {}
301 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
303 unsigned getID()
const {
return ID; }
307 bool isDead()
const {
310 return empty() && memory_empty();
314 Value *getLeader()
const {
return RepLeader; }
315 void setLeader(
Value *Leader) { RepLeader = Leader; }
316 const std::pair<Value *, unsigned int> &getNextLeader()
const {
319 void resetNextLeader() { NextLeader = {
nullptr, ~0}; }
320 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
321 if (LeaderPair.second < NextLeader.second)
322 NextLeader = LeaderPair;
325 Value *getStoredValue()
const {
return RepStoredValue; }
326 void setStoredValue(
Value *Leader) { RepStoredValue = Leader; }
327 const MemoryAccess *getMemoryLeader()
const {
return RepMemoryAccess; }
328 void setMemoryLeader(
const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
331 const Expression *getDefiningExpr()
const {
return DefiningExpr; }
334 bool empty()
const {
return Members.empty(); }
335 unsigned size()
const {
return Members.size(); }
336 MemberSet::const_iterator
begin()
const {
return Members.
begin(); }
337 MemberSet::const_iterator
end()
const {
return Members.
end(); }
338 void insert(MemberType *M) { Members.insert(M); }
339 void erase(MemberType *M) { Members.erase(M); }
340 void swap(MemberSet &Other) { Members.swap(Other); }
343 bool memory_empty()
const {
return MemoryMembers.empty(); }
344 unsigned memory_size()
const {
return MemoryMembers.size(); }
345 MemoryMemberSet::const_iterator memory_begin()
const {
346 return MemoryMembers.begin();
348 MemoryMemberSet::const_iterator memory_end()
const {
349 return MemoryMembers.end();
352 return make_range(memory_begin(), memory_end());
355 void memory_insert(
const MemoryMemberType *M) { MemoryMembers.insert(M); }
356 void memory_erase(
const MemoryMemberType *M) { MemoryMembers.erase(M); }
359 unsigned getStoreCount()
const {
return StoreCount; }
360 void incStoreCount() { ++StoreCount; }
361 void decStoreCount() {
362 assert(StoreCount != 0 &&
"Store count went negative");
367 bool definesNoMemory()
const {
return StoreCount == 0 && memory_empty(); }
371 bool isEquivalentTo(
const CongruenceClass *Other)
const {
377 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
378 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
379 Other->RepMemoryAccess))
381 if (DefiningExpr != Other->DefiningExpr)
382 if (!DefiningExpr || !Other->DefiningExpr ||
383 *DefiningExpr != *Other->DefiningExpr)
386 if (Members.size() != Other->Members.size())
390 [&](
const Value *V) {
return Other->Members.count(V); });
397 Value *RepLeader =
nullptr;
401 std::pair<Value *, unsigned int> NextLeader = {
nullptr, ~0U};
404 Value *RepStoredValue =
nullptr;
419 MemoryMemberSet MemoryMembers;
444 auto Val =
static_cast<uintptr_t
>(-1);
445 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
446 return reinterpret_cast<const Expression *
>(Val);
450 auto Val =
static_cast<uintptr_t
>(~1U);
451 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
452 return reinterpret_cast<const Expression *
>(Val);
464 if (RHS == getTombstoneKey() || RHS == getEmptyKey())
472 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
473 LHS == getEmptyKey() || RHS == getEmptyKey())
497 std::unique_ptr<PredicateInfo> PredInfo;
503 mutable TarjanSCC SCCFinder;
507 unsigned int NumFuncArgs;
518 CongruenceClass *TOPClass;
519 std::vector<CongruenceClass *> CongruenceClasses;
520 unsigned NextCongruenceNum;
551 ExpressionToPhiOfOps;
600 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
603 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
608 ExpressionClassMap ExpressionToClass;
659 :
F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
660 PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
673 using ValPair = std::pair<Value *, BasicBlock *>;
677 bool &OriginalOpsConstant)
const;
690 createAggregateValueExpression(
Instruction *)
const;
694 CongruenceClass *createCongruenceClass(
Value *Leader,
const Expression *
E) {
695 auto *result =
new CongruenceClass(NextCongruenceNum++, Leader, E);
696 CongruenceClasses.emplace_back(result);
701 auto *CC = createCongruenceClass(
nullptr,
nullptr);
702 CC->setMemoryLeader(MA);
706 CongruenceClass *ensureLeaderOfMemoryClass(
MemoryAccess *MA) {
707 auto *CC = getMemoryClass(MA);
708 if (CC->getMemoryLeader() != MA)
709 CC = createMemoryClass(MA);
713 CongruenceClass *createSingletonCongruenceClass(
Value *Member) {
714 CongruenceClass *CClass = createCongruenceClass(Member,
nullptr);
715 CClass->insert(Member);
716 ValueToClass[Member] = CClass;
720 void initializeCongruenceClasses(
Function &F);
761 CongruenceClass *getClassForExpression(
const Expression *E)
const;
764 CongruenceClass *, CongruenceClass *);
766 CongruenceClass *, CongruenceClass *);
767 Value *getNextValueLeader(CongruenceClass *)
const;
768 const MemoryAccess *getNextMemoryLeader(CongruenceClass *)
const;
769 bool setMemoryClass(
const MemoryAccess *From, CongruenceClass *To);
770 CongruenceClass *getMemoryClass(
const MemoryAccess *MA)
const;
775 unsigned int getRank(
const Value *)
const;
776 bool shouldSwapOperands(
const Value *,
const Value *)
const;
781 Value *findConditionEquivalence(
Value *)
const;
785 void convertClassToDFSOrdered(
const CongruenceClass &,
789 void convertClassToLoadsAndStores(
const CongruenceClass &,
792 bool eliminateInstructions(
Function &);
803 template <
typename Map,
typename KeyType,
typename Func>
804 void for_each_found(Map &,
const KeyType &, Func);
805 template <
typename Map,
typename KeyType>
806 void touchAndErase(Map &,
const KeyType &);
807 void markUsersTouched(
Value *);
811 void markValueLeaderChangeTouched(CongruenceClass *CC);
812 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
813 void markPhiOfOpsChanged(
const Expression *E);
819 void iterateTouchedInstructions();
822 void cleanupTables();
823 std::pair<unsigned, unsigned> assignDFSNumbers(
BasicBlock *,
unsigned);
824 void updateProcessedCount(
const Value *V);
825 void verifyMemoryCongruency()
const;
826 void verifyIterationSettled(
Function &F);
827 void verifyStoreExpressions()
const;
831 void deleteExpression(
const Expression *E)
const;
835 template <
class T,
class Range>
T *getMinDFSOfRange(
const Range &)
const;
837 unsigned InstrToDFSNum(
const Value *V)
const {
838 assert(isa<Instruction>(V) &&
"This should not be used for MemoryAccesses");
839 return InstrDFS.
lookup(V);
843 return MemoryToDFSNum(MA);
846 Value *InstrFromDFSNum(
unsigned DFSNum) {
return DFSToInstr[DFSNum]; }
851 unsigned MemoryToDFSNum(
const Value *MA)
const {
852 assert(isa<MemoryAccess>(MA) &&
853 "This should not be used with instructions");
854 return isa<MemoryUseOrDef>(MA)
855 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
864 int64_t StartingVNCounter;
869 template <
typename T>
871 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
873 return LHS.MemoryExpression::equals(RHS);
884 if (
const auto *S = dyn_cast<StoreExpression>(&Other))
885 if (getStoredValue() != S->getStoredValue())
893 RPOOrdering.lookup(DT->getNode(From)) >=
894 RPOOrdering.lookup(DT->getNode(To));
905 auto *
Result = MSSA->getMemoryAccess(I);
911 return MSSA->getMemoryAccess(BB);
916 if (
auto *I = dyn_cast<Instruction>(V)) {
920 Parent = TempToBlock.lookup(V);
921 assert(Parent &&
"Every fake instruction should have a block");
926 assert(MP &&
"Should have been an instruction or a MemoryPhi");
927 return MP->getBlock();
933 void NewGVN::deleteExpression(
const Expression *
E)
const {
934 assert(isa<BasicExpression>(E));
935 auto *BE = cast<BasicExpression>(
E);
937 ExpressionAllocator.Deallocate(E);
942 if (
auto *II = dyn_cast<IntrinsicInst>(V))
943 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
944 return II->getOperand(0);
955 return CO && isa<PHINode>(CO);
963 [&](
const ValPair &P1,
const ValPair &P2) {
964 return BlockInstRange.lookup(P1.second).first <
965 BlockInstRange.lookup(P2.second).first;
973 return isa<Constant>(V) || isa<Argument>(V);
985 bool &OriginalOpsConstant)
const {
986 unsigned NumOps = PHIOperands.
size();
987 auto *E =
new (ExpressionAllocator)
PHIExpression(NumOps, PHIBlock);
989 E->allocateOperands(ArgRecycler, ExpressionAllocator);
990 E->setType(PHIOperands.
begin()->first->getType());
996 if (
auto *PHIOp = dyn_cast<PHINode>(I))
999 if (!ReachableEdges.count({BB, PHIBlock}))
1002 if (ValueToClass.lookup(P.first) == TOPClass)
1004 OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(P.first);
1005 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
1006 return lookupOperandLeader(P.first) !=
I;
1009 [&](
const ValPair &
P) ->
Value * {
1010 return lookupOperandLeader(P.first);
1018 bool AllConstant =
true;
1019 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I))
1029 auto Operand = lookupOperandLeader(
O);
1030 AllConstant = AllConstant && isa<Constant>(Operand);
1037 const Expression *NewGVN::createBinaryExpression(
unsigned Opcode,
Type *
T,
1050 if (shouldSwapOperands(Arg1, Arg2))
1057 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1070 if (
auto *
C = dyn_cast<Constant>(V)) {
1073 <<
" constant " << *
C <<
"\n");
1074 NumGVNOpsSimplified++;
1075 assert(isa<BasicExpression>(E) &&
1076 "We should always have had a basic expression here");
1077 deleteExpression(E);
1078 return createConstantExpression(
C);
1079 }
else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1082 <<
" variable " << *V <<
"\n");
1083 deleteExpression(E);
1084 return createVariableExpression(V);
1087 CongruenceClass *CC = ValueToClass.lookup(V);
1089 if (CC->getLeader() && CC->getLeader() !=
I) {
1091 if (!AllTempInstructions.count(I))
1092 addAdditionalUsers(V, I);
1093 return createVariableOrConstant(CC->getLeader());
1095 if (CC->getDefiningExpr()) {
1100 if (!AllTempInstructions.count(I))
1101 addAdditionalUsers(V, I);
1106 <<
" expression " << *CC->getDefiningExpr() <<
"\n");
1107 NumGVNOpsSimplified++;
1108 deleteExpression(E);
1109 return CC->getDefiningExpr();
1122 bool AllConstant = setBasicExpressionInfo(I, E);
1130 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
1131 E->swapOperands(0, 1);
1134 if (
auto *CI = dyn_cast<CmpInst>(I)) {
1138 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
1139 E->swapOperands(0, 1);
1142 E->
setOpcode((CI->getOpcode() << 8) | Predicate);
1145 "Wrong types on cmp instruction");
1150 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1152 }
else if (isa<SelectInst>(I)) {
1153 if (isa<Constant>(E->getOperand(0)) ||
1154 E->getOperand(1) == E->getOperand(2)) {
1158 E->getOperand(2), SQ);
1159 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1165 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1167 }
else if (
auto *BI = dyn_cast<BitCastInst>(I)) {
1170 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1172 }
else if (isa<GetElementPtrInst>(I)) {
1175 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1177 }
else if (AllConstant) {
1190 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1197 NewGVN::createAggregateValueExpression(
Instruction *I)
const {
1198 if (
auto *II = dyn_cast<InsertValueInst>(I)) {
1199 auto *E =
new (ExpressionAllocator)
1201 setBasicExpressionInfo(I, E);
1202 E->allocateIntOperands(ExpressionAllocator);
1205 }
else if (
auto *EI = dyn_cast<ExtractValueInst>(I)) {
1206 auto *E =
new (ExpressionAllocator)
1208 setBasicExpressionInfo(EI, E);
1209 E->allocateIntOperands(ExpressionAllocator);
1219 return SingletonDeadExpression;
1229 if (
auto *
C = dyn_cast<Constant>(V))
1230 return createConstantExpression(
C);
1231 return createVariableExpression(V);
1251 setBasicExpressionInfo(CI, E);
1256 bool NewGVN::someEquivalentDominates(
const Instruction *Inst,
1258 auto *CC = ValueToClass.lookup(Inst);
1279 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
1281 if (CC->getNextLeader().first &&
1282 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
1285 return Member != CC->getLeader() &&
1286 DT->dominates(cast<Instruction>(Member), U);
1292 Value *NewGVN::lookupOperandLeader(
Value *V)
const {
1293 CongruenceClass *CC = ValueToClass.lookup(V);
1300 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
1307 auto *CC = getMemoryClass(MA);
1308 assert(CC->getMemoryLeader() &&
1309 "Every MemoryAccess should be mapped to a congruence class with a " 1310 "representative memory access");
1311 return CC->getMemoryLeader();
1317 bool NewGVN::isMemoryAccessTOP(
const MemoryAccess *MA)
const {
1318 return getMemoryClass(MA) == TOPClass;
1325 new (ExpressionAllocator)
LoadExpression(1, LI, lookupMemoryLeader(MA));
1326 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1327 E->setType(LoadType);
1331 E->op_push_back(PointerOp);
1344 auto *E =
new (ExpressionAllocator)
1362 auto *SI = cast<StoreInst>(
I);
1363 auto *StoreAccess = getMemoryAccess(SI);
1365 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1367 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1369 StoreRHS = lookupMemoryLeader(StoreRHS);
1370 if (StoreRHS != StoreAccess->getDefiningAccess())
1371 addMemoryUsers(StoreRHS, StoreAccess);
1373 if (StoreRHS == StoreAccess)
1374 StoreRHS = MSSA->getLiveOnEntryDef();
1380 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1381 const auto *LastCC = ExpressionToClass.lookup(LastStore);
1387 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
1393 if (
auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
1395 LastStore->getOperand(0)) &&
1396 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
1399 deleteExpression(LastStore);
1405 return createStoreExpression(SI, StoreAccess);
1411 NewGVN::performSymbolicLoadCoercion(
Type *LoadType,
Value *LoadPtr,
1415 if (
auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1419 if (LI->
isAtomic() > DepSI->isAtomic() ||
1420 LoadType == DepSI->getValueOperand()->getType())
1424 if (
auto *C = dyn_cast<Constant>(
1425 lookupOperandLeader(DepSI->getValueOperand()))) {
1427 <<
" to constant " << *C <<
"\n");
1428 return createConstantExpression(
1432 }
else if (
auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
1434 if (LI->
isAtomic() > DepLI->isAtomic())
1439 if (
auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1440 if (
auto *PossibleConstant =
1443 <<
" to constant " << *PossibleConstant <<
"\n");
1444 return createConstantExpression(PossibleConstant);
1447 }
else if (
auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1450 if (
auto *PossibleConstant =
1453 <<
" to constant " << *PossibleConstant <<
"\n");
1454 return createConstantExpression(PossibleConstant);
1461 if (LoadPtr != lookupOperandLeader(DepInst) &&
1462 !AA->isMustAlias(LoadPtr, DepInst))
1473 else if (
auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1474 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1487 auto *LI = cast<LoadInst>(
I);
1496 if (isa<UndefValue>(LoadAddressLeader))
1500 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
1502 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1503 if (
auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1506 if (!ReachableBlocks.count(DefiningInst->
getParent()))
1512 if (
const auto *CoercionResult =
1513 performSymbolicLoadCoercion(LI->
getType(), LoadAddressLeader, LI,
1514 DefiningInst, DefiningAccess))
1515 return CoercionResult;
1519 const auto *
LE = createLoadExpression(LI->
getType(), LoadAddressLeader, LI,
1523 if (
LE->getMemoryLeader() != DefiningAccess)
1524 addMemoryUsers(
LE->getMemoryLeader(), OriginalAccess);
1529 NewGVN::performSymbolicPredicateInfoEvaluation(
Instruction *I)
const {
1530 auto *PI = PredInfo->getPredicateInfoFor(I);
1534 LLVM_DEBUG(
dbgs() <<
"Found predicate info from instruction !\n");
1541 auto *Cond = PWC->Condition;
1545 if (CopyOf == Cond) {
1548 if (isa<PredicateAssume>(PI))
1550 if (
auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1551 if (PBranch->TrueEdge)
1555 if (
auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1556 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
1573 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
1574 LLVM_DEBUG(
dbgs() <<
"Copy is not of any condition operands!\n");
1577 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1578 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
1579 bool SwappedOps =
false;
1581 if (shouldSwapOperands(FirstOp, SecondOp)) {
1586 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1588 if (isa<PredicateAssume>(PI)) {
1591 addPredicateUsers(PI, I);
1592 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1594 return createVariableOrConstant(FirstOp);
1597 if (
const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1605 addPredicateUsers(PI, I);
1606 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1608 return createVariableOrConstant(FirstOp);
1613 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1614 addPredicateUsers(PI, I);
1615 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1617 return createConstantExpression(cast<Constant>(FirstOp));
1625 auto *CI = cast<CallInst>(
I);
1626 if (
auto *II = dyn_cast<IntrinsicInst>(I)) {
1628 if (
auto *ReturnedValue = II->getReturnedArgOperand()) {
1629 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1630 if (
const auto *
Result = performSymbolicPredicateInfoEvaluation(I))
1632 return createVariableOrConstant(ReturnedValue);
1635 if (AA->doesNotAccessMemory(CI)) {
1636 return createCallExpression(CI, TOPClass->getMemoryLeader());
1637 }
else if (AA->onlyReadsMemory(CI)) {
1638 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
1639 return createCallExpression(CI, DefiningAccess);
1645 CongruenceClass *NewGVN::getMemoryClass(
const MemoryAccess *MA)
const {
1646 auto *
Result = MemoryAccessToClass.lookup(MA);
1654 CongruenceClass *NewClass) {
1656 "Every MemoryAccess should be getting mapped to a non-null class");
1660 <<
" with current MemoryAccess leader ");
1663 auto LookupResult = MemoryAccessToClass.find(From);
1664 bool Changed =
false;
1666 if (LookupResult != MemoryAccessToClass.end()) {
1667 auto *OldClass = LookupResult->second;
1668 if (OldClass != NewClass) {
1670 if (
auto *MP = dyn_cast<MemoryPhi>(From)) {
1671 OldClass->memory_erase(MP);
1672 NewClass->memory_insert(MP);
1674 if (OldClass->getMemoryLeader() == From) {
1675 if (OldClass->definesNoMemory()) {
1676 OldClass->setMemoryLeader(
nullptr);
1678 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1680 << OldClass->getID() <<
" to " 1681 << *OldClass->getMemoryLeader()
1682 <<
" due to removal of a memory member " << *From
1684 markMemoryLeaderChangeTouched(OldClass);
1689 LookupResult->second = NewClass;
1701 bool NewGVN::isCycleFree(
const Instruction *I)
const {
1707 auto ICS = InstCycleState.lookup(I);
1708 if (ICS == ICS_Unknown) {
1710 auto &SCC = SCCFinder.getComponentFor(I);
1712 if (SCC.size() == 1)
1713 InstCycleState.insert({I, ICS_CycleFree});
1718 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
1719 for (
auto *Member : SCC)
1720 if (
auto *MemberPhi = dyn_cast<PHINode>(Member))
1721 InstCycleState.insert({MemberPhi, ICS});
1724 if (ICS == ICS_Cycle)
1735 bool HasBackedge =
false;
1740 bool OriginalOpsConstant =
true;
1741 auto *E = cast<PHIExpression>(createPHIExpression(
1742 PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
1746 bool HasUndef =
false;
1748 if (isa<UndefValue>(
Arg)) {
1755 if (Filtered.begin() == Filtered.end()) {
1760 dbgs() <<
"PHI Node " << *I
1761 <<
" has no non-undef arguments, valuing it as undef\n");
1765 LLVM_DEBUG(
dbgs() <<
"No arguments of PHI node " << *I <<
" are live\n");
1766 deleteExpression(E);
1767 return createDeadExpression();
1769 Value *AllSameValue = *(Filtered.begin());
1788 if (HasBackedge && !OriginalOpsConstant &&
1789 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
1793 if (
auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1794 if (!someEquivalentDominates(AllSameInst, I))
1800 if (isa<Instruction>(AllSameValue) &&
1801 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1803 NumGVNPhisAllSame++;
1804 LLVM_DEBUG(
dbgs() <<
"Simplified PHI node " << *I <<
" to " << *AllSameValue
1806 deleteExpression(E);
1807 return createVariableOrConstant(AllSameValue);
1813 NewGVN::performSymbolicAggrValueEvaluation(
Instruction *I)
const {
1814 if (
auto *EI = dyn_cast<ExtractValueInst>(I)) {
1816 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1817 unsigned Opcode = 0;
1821 switch (II->getIntrinsicID()) {
1822 case Intrinsic::sadd_with_overflow:
1823 case Intrinsic::uadd_with_overflow:
1826 case Intrinsic::ssub_with_overflow:
1827 case Intrinsic::usub_with_overflow:
1828 Opcode = Instruction::Sub;
1830 case Intrinsic::smul_with_overflow:
1831 case Intrinsic::umul_with_overflow:
1832 Opcode = Instruction::Mul;
1841 assert(II->getNumArgOperands() == 2 &&
1842 "Expect two args for recognised intrinsics.");
1843 return createBinaryExpression(Opcode, EI->getType(),
1844 II->getArgOperand(0),
1845 II->getArgOperand(1),
I);
1850 return createAggregateValueExpression(I);
1854 assert(isa<CmpInst>(I) &&
"Expected a cmp instruction.");
1856 auto *CI = cast<CmpInst>(
I);
1859 auto Op0 = lookupOperandLeader(CI->
getOperand(0));
1860 auto Op1 = lookupOperandLeader(CI->
getOperand(1));
1861 auto OurPredicate = CI->getPredicate();
1862 if (shouldSwapOperands(Op0, Op1)) {
1864 OurPredicate = CI->getSwappedPredicate();
1871 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1872 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1877 if (CI->isTrueWhenEqual())
1879 else if (CI->isFalseWhenEqual())
1909 auto *PI = PredInfo->getPredicateInfoFor(
Op);
1910 if (
const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1911 if (PI == LastPredInfo)
1916 if (!DT->dominates(PBranch->To, getBlockForValue(I)))
1926 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1927 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1929 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1931 BranchPredicate = BranchCond->getSwappedPredicate();
1933 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1934 if (PBranch->TrueEdge) {
1939 addPredicateUsers(PI, I);
1940 return createConstantExpression(
1946 addPredicateUsers(PI, I);
1947 return createConstantExpression(
1953 if (BranchPredicate == OurPredicate) {
1954 addPredicateUsers(PI, I);
1956 return createConstantExpression(
1958 }
else if (BranchPredicate ==
1960 addPredicateUsers(PI, I);
1962 return createConstantExpression(
1970 return createExpression(I);
1975 NewGVN::performSymbolicEvaluation(
Value *V,
1978 if (
auto *C = dyn_cast<Constant>(V))
1979 E = createConstantExpression(C);
1980 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1981 E = createVariableExpression(V);
1986 auto *I = cast<Instruction>(V);
1988 case Instruction::ExtractValue:
1989 case Instruction::InsertValue:
1990 E = performSymbolicAggrValueEvaluation(I);
1992 case Instruction::PHI: {
1994 auto *PN = cast<PHINode>(
I);
1995 for (
unsigned i = 0; i < PN->getNumOperands(); ++i)
1996 Ops.
push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
1999 E = performSymbolicPHIEvaluation(Ops, I, getBlockForValue(I));
2002 E = performSymbolicCallEvaluation(I);
2005 E = performSymbolicStoreEvaluation(I);
2008 E = performSymbolicLoadEvaluation(I);
2010 case Instruction::BitCast:
2011 E = createExpression(I);
2013 case Instruction::ICmp:
2014 case Instruction::FCmp:
2015 E = performSymbolicCmpEvaluation(I);
2018 case Instruction::FAdd:
2019 case Instruction::Sub:
2020 case Instruction::FSub:
2021 case Instruction::Mul:
2022 case Instruction::FMul:
2023 case Instruction::UDiv:
2024 case Instruction::SDiv:
2025 case Instruction::FDiv:
2026 case Instruction::URem:
2027 case Instruction::SRem:
2028 case Instruction::FRem:
2029 case Instruction::Shl:
2030 case Instruction::LShr:
2031 case Instruction::AShr:
2032 case Instruction::And:
2033 case Instruction::Or:
2034 case Instruction::Xor:
2035 case Instruction::Trunc:
2036 case Instruction::ZExt:
2037 case Instruction::SExt:
2038 case Instruction::FPToUI:
2039 case Instruction::FPToSI:
2040 case Instruction::UIToFP:
2041 case Instruction::SIToFP:
2042 case Instruction::FPTrunc:
2043 case Instruction::FPExt:
2044 case Instruction::PtrToInt:
2045 case Instruction::IntToPtr:
2047 case Instruction::ExtractElement:
2048 case Instruction::InsertElement:
2049 case Instruction::ShuffleVector:
2050 case Instruction::GetElementPtr:
2051 E = createExpression(I);
2062 template <
typename Map,
typename KeyType,
typename Func>
2063 void NewGVN::for_each_found(Map &M,
const KeyType &
Key, Func
F) {
2064 const auto Result = M.find_as(Key);
2066 for (
typename Map::mapped_type::value_type Mapped :
Result->second)
2072 template <
typename Map,
typename KeyType>
2073 void NewGVN::touchAndErase(Map &M,
const KeyType &Key) {
2074 const auto Result = M.find_as(Key);
2076 for (
const typename Map::mapped_type::value_type Mapped :
Result->second)
2077 TouchedInstructions.set(InstrToDFSNum(Mapped));
2083 assert(User && To != User);
2084 if (isa<Instruction>(To))
2085 AdditionalUsers[To].insert(User);
2088 void NewGVN::markUsersTouched(
Value *V) {
2090 for (
auto *User : V->
users()) {
2091 assert(isa<Instruction>(User) &&
"Use of value not within an instruction?");
2092 TouchedInstructions.set(InstrToDFSNum(User));
2094 touchAndErase(AdditionalUsers, V);
2098 LLVM_DEBUG(
dbgs() <<
"Adding memory user " << *U <<
" to " << *To <<
"\n");
2099 MemoryToUsers[To].insert(U);
2102 void NewGVN::markMemoryDefTouched(
const MemoryAccess *MA) {
2103 TouchedInstructions.set(MemoryToDFSNum(MA));
2106 void NewGVN::markMemoryUsersTouched(
const MemoryAccess *MA) {
2107 if (isa<MemoryUse>(MA))
2109 for (
auto U : MA->
users())
2110 TouchedInstructions.set(MemoryToDFSNum(U));
2111 touchAndErase(MemoryToUsers, MA);
2117 if (AllTempInstructions.count(I))
2120 if (
auto *PBranch = dyn_cast<PredicateBranch>(PB))
2121 PredicateToUsers[PBranch->Condition].insert(I);
2122 else if (
auto *PAssume = dyn_cast<PredicateBranch>(PB))
2123 PredicateToUsers[PAssume->Condition].insert(I);
2127 void NewGVN::markPredicateUsersTouched(
Instruction *I) {
2128 touchAndErase(PredicateToUsers, I);
2132 void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
2133 for (
auto M : CC->memory())
2134 markMemoryDefTouched(M);
2139 void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
2140 for (
auto M : *CC) {
2141 if (
auto *I = dyn_cast<Instruction>(M))
2142 TouchedInstructions.set(InstrToDFSNum(I));
2143 LeaderChanges.insert(M);
2149 template <
class T,
class Range>
2150 T *NewGVN::getMinDFSOfRange(
const Range &
R)
const {
2151 std::pair<T *, unsigned> MinDFS = {
nullptr, ~0U};
2152 for (
const auto X : R) {
2153 auto DFSNum = InstrToDFSNum(
X);
2154 if (DFSNum < MinDFS.second)
2155 MinDFS = {
X, DFSNum};
2157 return MinDFS.first;
2163 const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC)
const {
2167 assert(!CC->definesNoMemory() &&
"Can't get next leader if there is none");
2168 if (CC->getStoreCount() > 0) {
2169 if (
auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
2170 return getMemoryAccess(NL);
2173 *CC, [&](
const Value *V) {
return isa<StoreInst>(V); }));
2174 return getMemoryAccess(cast<StoreInst>(V));
2176 assert(CC->getStoreCount() == 0);
2180 if (CC->memory_size() == 1)
2181 return *CC->memory_begin();
2182 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
2188 Value *NewGVN::getNextValueLeader(CongruenceClass *CC)
const {
2193 if (CC->size() == 1 || CC == TOPClass) {
2194 return *(CC->begin());
2195 }
else if (CC->getNextLeader().first) {
2196 ++NumGVNAvoidedSortedLeaderChanges;
2197 return CC->getNextLeader().first;
2199 ++NumGVNSortedLeaderChanges;
2203 return getMinDFSOfRange<Value>(*CC);
2216 void NewGVN::moveMemoryToNewCongruenceClass(
Instruction *I,
2218 CongruenceClass *OldClass,
2219 CongruenceClass *NewClass) {
2222 assert((!InstMA || !OldClass->getMemoryLeader() ||
2223 OldClass->getLeader() != I ||
2224 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2225 MemoryAccessToClass.lookup(InstMA)) &&
2226 "Representative MemoryAccess mismatch");
2228 if (!NewClass->getMemoryLeader()) {
2230 assert(NewClass->size() == 1 ||
2231 (isa<StoreInst>(
I) && NewClass->getStoreCount() == 1));
2232 NewClass->setMemoryLeader(InstMA);
2235 << NewClass->getID()
2236 <<
" due to new memory instruction becoming leader\n");
2237 markMemoryLeaderChangeTouched(NewClass);
2239 setMemoryClass(InstMA, NewClass);
2241 if (OldClass->getMemoryLeader() == InstMA) {
2242 if (!OldClass->definesNoMemory()) {
2243 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2245 << OldClass->getID() <<
" to " 2246 << *OldClass->getMemoryLeader()
2247 <<
" due to removal of old leader " << *InstMA <<
"\n");
2248 markMemoryLeaderChangeTouched(OldClass);
2250 OldClass->setMemoryLeader(
nullptr);
2257 CongruenceClass *OldClass,
2258 CongruenceClass *NewClass) {
2259 if (I == OldClass->getNextLeader().first)
2260 OldClass->resetNextLeader();
2263 NewClass->insert(I);
2265 if (NewClass->getLeader() !=
I)
2266 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
2268 if (
auto *SI = dyn_cast<StoreInst>(I)) {
2269 OldClass->decStoreCount();
2277 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
2280 if (
auto *SE = dyn_cast<StoreExpression>(E)) {
2281 NewClass->setStoredValue(SE->getStoredValue());
2282 markValueLeaderChangeTouched(NewClass);
2285 << NewClass->getID() <<
" from " 2286 << *NewClass->getLeader() <<
" to " << *SI
2287 <<
" because store joined class\n");
2290 NewClass->setLeader(SI);
2294 NewClass->incStoreCount();
2300 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
2302 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
2303 ValueToClass[
I] = NewClass;
2305 if (OldClass->empty() && OldClass != TOPClass) {
2306 if (OldClass->getDefiningExpr()) {
2307 LLVM_DEBUG(
dbgs() <<
"Erasing expression " << *OldClass->getDefiningExpr()
2308 <<
" from table\n");
2311 auto Iter = ExpressionToClass.find_as(
2313 if (Iter != ExpressionToClass.end())
2314 ExpressionToClass.erase(Iter);
2315 #ifdef EXPENSIVE_CHECKS 2317 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2318 "We erased the expression we just inserted, which should not happen");
2321 }
else if (OldClass->getLeader() ==
I) {
2326 << OldClass->getID() <<
"\n");
2327 ++NumGVNLeaderChanges;
2332 if (OldClass->getStoreCount() == 0) {
2333 if (OldClass->getStoredValue())
2334 OldClass->setStoredValue(
nullptr);
2336 OldClass->setLeader(getNextValueLeader(OldClass));
2337 OldClass->resetNextLeader();
2338 markValueLeaderChangeTouched(OldClass);
2344 void NewGVN::markPhiOfOpsChanged(
const Expression *E) {
2345 touchAndErase(ExpressionToPhiOfOps, E);
2353 CongruenceClass *IClass = ValueToClass.lookup(I);
2354 assert(IClass &&
"Should have found a IClass");
2356 assert(!IClass->isDead() &&
"Found a dead class");
2358 CongruenceClass *EClass =
nullptr;
2359 if (
const auto *VE = dyn_cast<VariableExpression>(E)) {
2360 EClass = ValueToClass.lookup(VE->getVariableValue());
2361 }
else if (isa<DeadExpression>(E)) {
2365 auto lookupResult = ExpressionToClass.insert({
E,
nullptr});
2368 if (lookupResult.second) {
2369 CongruenceClass *NewClass = createCongruenceClass(
nullptr, E);
2370 auto place = lookupResult.first;
2371 place->second = NewClass;
2374 if (
const auto *CE = dyn_cast<ConstantExpression>(E)) {
2375 NewClass->setLeader(CE->getConstantValue());
2376 }
else if (
const auto *SE = dyn_cast<StoreExpression>(E)) {
2378 NewClass->setLeader(SI);
2379 NewClass->setStoredValue(SE->getStoredValue());
2383 NewClass->setLeader(I);
2385 assert(!isa<VariableExpression>(E) &&
2386 "VariableExpression should have been handled already");
2390 <<
" using expression " << *E <<
" at " 2391 << NewClass->getID() <<
" and leader " 2392 << *(NewClass->getLeader()));
2393 if (NewClass->getStoredValue())
2395 << *(NewClass->getStoredValue()));
2398 EClass = lookupResult.first->second;
2399 if (isa<ConstantExpression>(E))
2400 assert((isa<Constant>(EClass->getLeader()) ||
2401 (EClass->getStoredValue() &&
2402 isa<Constant>(EClass->getStoredValue()))) &&
2403 "Any class with a constant expression should have a " 2406 assert(EClass &&
"Somehow don't have an eclass");
2408 assert(!EClass->isDead() &&
"We accidentally looked up a dead class");
2411 bool ClassChanged = IClass != EClass;
2412 bool LeaderChanged = LeaderChanges.erase(I);
2413 if (ClassChanged || LeaderChanged) {
2414 LLVM_DEBUG(
dbgs() <<
"New class " << EClass->getID() <<
" for expression " 2417 moveValueToNewCongruenceClass(I, E, IClass, EClass);
2418 markPhiOfOpsChanged(E);
2421 markUsersTouched(I);
2423 markMemoryUsersTouched(MA);
2424 if (
auto *CI = dyn_cast<CmpInst>(I))
2425 markPredicateUsersTouched(CI);
2431 if (ClassChanged && isa<StoreInst>(I)) {
2432 auto *OldE = ValueToExpression.lookup(I);
2435 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2439 if (Iter != ExpressionToClass.end())
2440 ExpressionToClass.erase(Iter);
2443 ValueToExpression[
I] =
E;
2450 if (ReachableEdges.insert({From, To}).second) {
2452 if (ReachableBlocks.insert(To).second) {
2454 <<
" marked reachable\n");
2455 const auto &InstRange = BlockInstRange.lookup(To);
2456 TouchedInstructions.set(InstRange.first, InstRange.second);
2459 <<
" was reachable, but new edge {" 2461 <<
"} to it found\n");
2468 TouchedInstructions.set(InstrToDFSNum(MemPhi));
2473 for (
auto InstNum : RevisitOnReachabilityChange[To])
2474 TouchedInstructions.set(InstNum);
2481 Value *NewGVN::findConditionEquivalence(
Value *Cond)
const {
2482 auto Result = lookupOperandLeader(Cond);
2490 if ((BR = dyn_cast<BranchInst>(TI)) && BR->
isConditional()) {
2492 Value *CondEvaluated = findConditionEquivalence(Cond);
2493 if (!CondEvaluated) {
2494 if (
auto *I = dyn_cast<Instruction>(Cond)) {
2496 if (
const auto *CE = dyn_cast<ConstantExpression>(E)) {
2497 CondEvaluated = CE->getConstantValue();
2499 }
else if (isa<ConstantInt>(Cond)) {
2500 CondEvaluated = Cond;
2506 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2509 <<
" evaluated to true\n");
2510 updateReachableEdge(B, TrueSucc);
2511 }
else if (CI->
isZero()) {
2513 <<
" evaluated to false\n");
2514 updateReachableEdge(B, FalseSucc);
2517 updateReachableEdge(B, TrueSucc);
2518 updateReachableEdge(B, FalseSucc);
2520 }
else if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
2527 Value *SwitchCond = SI->getCondition();
2528 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
2530 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
2531 auto *CondVal = cast<ConstantInt>(CondEvaluated);
2533 auto Case = *SI->findCaseValue(CondVal);
2534 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
2538 updateReachableEdge(B, SI->getDefaultDest());
2542 BasicBlock *TargetBlock = Case.getCaseSuccessor();
2543 updateReachableEdge(B, TargetBlock);
2545 for (
unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2546 BasicBlock *TargetBlock = SI->getSuccessor(i);
2547 ++SwitchEdges[TargetBlock];
2548 updateReachableEdge(B, TargetBlock);
2556 updateReachableEdge(B, TargetBlock);
2562 auto *MA = getMemoryAccess(TI);
2563 if (MA && !isa<MemoryUse>(MA)) {
2564 auto *CC = ensureLeaderOfMemoryClass(MA);
2565 if (setMemoryClass(MA, CC))
2566 markMemoryUsersTouched(MA);
2573 InstrDFS.erase(PHITemp);
2576 TempToBlock.erase(PHITemp);
2577 RealToTemp.erase(I);
2587 InstrDFS[
Op] = InstrToDFSNum(ExistingValue);
2588 AllTempInstructions.insert(Op);
2589 TempToBlock[
Op] = BB;
2590 RealToTemp[ExistingValue] =
Op;
2593 for (
auto *U : ExistingValue->
users())
2594 if (
auto *UI = dyn_cast<Instruction>(U))
2595 PHINodeUses.insert(UI);
2601 return isa<BinaryOperator>(
I) || isa<SelectInst>(I) || isa<CmpInst>(
I) ||
2605 bool NewGVN::OpIsSafeForPHIOfOpsHelper(
2610 if (!isa<Instruction>(V))
2612 auto OISIt = OpSafeForPHIOfOps.find(V);
2613 if (OISIt != OpSafeForPHIOfOps.end())
2614 return OISIt->second;
2618 if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
2619 OpSafeForPHIOfOps.insert({V,
true});
2623 if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
2624 OpSafeForPHIOfOps.insert({V,
false});
2628 auto *OrigI = cast<Instruction>(V);
2630 if (!isa<Instruction>(Op))
2633 auto OISIt = OpSafeForPHIOfOps.find(OrigI);
2634 if (OISIt != OpSafeForPHIOfOps.end()) {
2635 if (!OISIt->second) {
2636 OpSafeForPHIOfOps.insert({V,
false});
2641 if (!Visited.
insert(Op).second)
2643 Worklist.
push_back(cast<Instruction>(Op));
2655 bool NewGVN::OpIsSafeForPHIOfOps(
Value *V,
const BasicBlock *PHIBlock,
2658 if (!OpIsSafeForPHIOfOpsHelper(V, PHIBlock, Visited, Worklist))
2660 while (!Worklist.
empty()) {
2662 if (!OpIsSafeForPHIOfOpsHelper(I, PHIBlock, Visited, Worklist))
2665 OpSafeForPHIOfOps.insert({V,
true});
2678 unsigned IDFSNum = InstrToDFSNum(OrigInst);
2680 AllTempInstructions.insert(TransInst);
2684 TempToBlock.insert({TransInst, PredBB});
2685 InstrDFS.insert({TransInst, IDFSNum});
2687 const Expression *E = performSymbolicEvaluation(TransInst, Visited);
2688 InstrDFS.erase(TransInst);
2689 AllTempInstructions.erase(TransInst);
2690 TempToBlock.erase(TransInst);
2692 TempToMemory.erase(TransInst);
2695 auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
2697 ExpressionToPhiOfOps[
E].insert(OrigInst);
2698 LLVM_DEBUG(
dbgs() <<
"Cannot find phi of ops operand for " << *TransInst
2702 if (
auto *SI = dyn_cast<StoreInst>(FoundVal))
2715 if (!Visited.
insert(I).second)
2721 if (!isCycleFree(I))
2728 auto *MemAccess = getMemoryAccess(I);
2732 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2743 for (
auto *Op : Ops) {
2744 if (!isa<PHINode>(Op)) {
2745 auto *ValuePHI = RealToTemp.lookup(Op);
2751 OpPHI = cast<PHINode>(
Op);
2752 if (!SamePHIBlock) {
2753 SamePHIBlock = getBlockForValue(OpPHI);
2754 }
else if (SamePHIBlock != getBlockForValue(OpPHI)) {
2757 <<
"PHIs for operands are not all in the same block, aborting\n");
2772 auto *PHIBlock = getBlockForValue(OpPHI);
2773 RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(I));
2774 for (
unsigned PredNum = 0; PredNum < OpPHI->
getNumOperands(); ++PredNum) {
2776 Value *FoundVal =
nullptr;
2780 if (ReachableEdges.count({PredBB, PHIBlock})) {
2785 TempToMemory.insert({ValueOp, MemAccess});
2786 bool SafeForPHIOfOps =
true;
2788 for (
auto &Op : ValueOp->
operands()) {
2789 auto *OrigOp = &*
Op;
2792 if (isa<PHINode>(Op)) {
2794 if (Op != OrigOp && Op != I)
2796 }
else if (
auto *ValuePHI = RealToTemp.lookup(Op)) {
2797 if (getBlockForValue(ValuePHI) == PHIBlock)
2803 (Op != OrigOp || OpIsSafeForPHIOfOps(Op, PHIBlock, VisitedOps));
2810 FoundVal = !SafeForPHIOfOps ? nullptr
2811 : findLeaderForInst(ValueOp, Visited,
2812 MemAccess, I, PredBB);
2817 if (SafeForPHIOfOps)
2818 for (
auto Dep : CurrentDeps)
2819 addAdditionalUsers(Dep, I);
2825 LLVM_DEBUG(
dbgs() <<
"Skipping phi of ops operand for incoming block " 2827 <<
" because the block is unreachable\n");
2829 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
2833 LLVM_DEBUG(
dbgs() <<
"Found phi of ops operand " << *FoundVal <<
" in " 2836 for (
auto Dep : Deps)
2837 addAdditionalUsers(Dep, I);
2839 auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
2840 if (isa<ConstantExpression>(E) || isa<VariableExpression>(E)) {
2843 <<
"Not creating real PHI of ops because it simplified to existing " 2844 "value or constant\n");
2847 auto *ValuePHI = RealToTemp.lookup(I);
2848 bool NewPHI =
false;
2852 addPhiOfOps(ValuePHI, PHIBlock, I);
2854 NumGVNPHIOfOpsCreated++;
2857 for (
auto PHIOp : PHIOps)
2858 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2860 TempToBlock[ValuePHI] = PHIBlock;
2862 for (
auto PHIOp : PHIOps) {
2863 ValuePHI->setIncomingValue(i, PHIOp.first);
2864 ValuePHI->setIncomingBlock(i, PHIOp.second);
2868 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
2869 LLVM_DEBUG(
dbgs() <<
"Created phi of ops " << *ValuePHI <<
" for " << *I
2878 void NewGVN::initializeCongruenceClasses(
Function &F) {
2879 NextCongruenceNum = 0;
2889 TOPClass = createCongruenceClass(
nullptr,
nullptr);
2890 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
2892 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2893 createMemoryClass(MSSA->getLiveOnEntryDef());
2895 for (
auto DTN :
nodes(DT)) {
2901 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
2902 if (MemoryBlockDefs)
2903 for (
const auto &
Def : *MemoryBlockDefs) {
2904 MemoryAccessToClass[&
Def] = TOPClass;
2909 TOPClass->memory_insert(MP);
2910 MemoryPhiState.insert({MP, MPS_TOP});
2913 if (MD && isa<StoreInst>(MD->getMemoryInst()))
2914 TOPClass->incStoreCount();
2920 for (
auto &I : *BB) {
2921 if (isa<PHINode>(&I))
2922 for (
auto *U : I.
users())
2923 if (
auto *UInst = dyn_cast<Instruction>(U))
2925 PHINodeUses.insert(UInst);
2930 TOPClass->insert(&I);
2931 ValueToClass[&
I] = TOPClass;
2936 for (
auto &FA : F.
args())
2937 createSingletonCongruenceClass(&FA);
2940 void NewGVN::cleanupTables() {
2941 for (
unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
2943 <<
" has " << CongruenceClasses[i]->
size()
2947 delete CongruenceClasses[i];
2948 CongruenceClasses[i] =
nullptr;
2953 AllTempInstructions.end());
2954 AllTempInstructions.
clear();
2958 for (
auto *I : TempInst) {
2962 while (!TempInst.empty()) {
2963 auto *I = TempInst.back();
2964 TempInst.pop_back();
2968 ValueToClass.clear();
2969 ArgRecycler.clear(ExpressionAllocator);
2970 ExpressionAllocator.Reset();
2971 CongruenceClasses.clear();
2972 ExpressionToClass.clear();
2973 ValueToExpression.clear();
2975 AdditionalUsers.clear();
2976 ExpressionToPhiOfOps.clear();
2977 TempToBlock.clear();
2978 TempToMemory.clear();
2979 PHINodeUses.clear();
2980 OpSafeForPHIOfOps.clear();
2981 ReachableBlocks.clear();
2982 ReachableEdges.clear();
2984 ProcessedCount.clear();
2987 InstructionsToErase.clear();
2989 BlockInstRange.clear();
2990 TouchedInstructions.clear();
2991 MemoryAccessToClass.clear();
2992 PredicateToUsers.clear();
2993 MemoryToUsers.clear();
2994 RevisitOnReachabilityChange.clear();
2999 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(
BasicBlock *B,
3001 unsigned End = Start;
3003 InstrDFS[MemPhi] = End++;
3004 DFSToInstr.emplace_back(MemPhi);
3008 for (
auto &I : *B) {
3014 LLVM_DEBUG(
dbgs() <<
"Skipping trivially dead instruction " << I <<
"\n");
3015 markInstructionForDeletion(&I);
3018 if (isa<PHINode>(&I))
3019 RevisitOnReachabilityChange[
B].set(End);
3020 InstrDFS[&
I] = End++;
3021 DFSToInstr.emplace_back(&I);
3027 return std::make_pair(Start, End);
3030 void NewGVN::updateProcessedCount(
const Value *V) {
3032 if (ProcessedCount.count(V) == 0) {
3033 ProcessedCount.insert({V, 1});
3035 ++ProcessedCount[V];
3036 assert(ProcessedCount[V] < 100 &&
3037 "Seem to have processed the same Value a lot");
3043 void NewGVN::valueNumberMemoryPhi(
MemoryPhi *MP) {
3050 return cast<MemoryAccess>(U) != MP &&
3051 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
3052 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
3057 if (Filtered.begin() == Filtered.end()) {
3058 if (setMemoryClass(MP, TOPClass))
3059 markMemoryUsersTouched(MP);
3065 auto LookupFunc = [&](
const Use &U) {
3066 return lookupMemoryLeader(cast<MemoryAccess>(U));
3068 auto MappedBegin =
map_iterator(Filtered.begin(), LookupFunc);
3069 auto MappedEnd =
map_iterator(Filtered.end(), LookupFunc);
3073 const auto *AllSameValue = *MappedBegin;
3076 MappedBegin, MappedEnd,
3077 [&AllSameValue](
const MemoryAccess *V) {
return V == AllSameValue; });
3080 LLVM_DEBUG(
dbgs() <<
"Memory Phi value numbered to " << *AllSameValue
3089 CongruenceClass *CC =
3090 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
3091 auto OldState = MemoryPhiState.lookup(MP);
3092 assert(OldState != MPS_Invalid &&
"Invalid memory phi state");
3093 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
3094 MemoryPhiState[MP] = NewState;
3095 if (setMemoryClass(MP, CC) || OldState != NewState)
3096 markMemoryUsersTouched(MP);
3101 void NewGVN::valueNumberInstruction(
Instruction *I) {
3107 Symbolized = performSymbolicEvaluation(I, Visited);
3109 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
3110 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
3111 auto *PHIE = makePossiblePHIOfOps(I, Visited);
3116 }
else if (
auto *Op = RealToTemp.lookup(I)) {
3117 removePhiOfOps(I, Op);
3126 if (Symbolized ==
nullptr)
3127 Symbolized = createUnknownExpression(I);
3128 performCongruenceFinding(I, Symbolized);
3134 auto *Symbolized = createUnknownExpression(I);
3135 performCongruenceFinding(I, Symbolized);
3137 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->
getParent());
3143 bool NewGVN::singleReachablePHIPath(
3146 if (First == Second)
3148 if (MSSA->isLiveOnEntryDef(First))
3156 if (Visited.
count(First))
3160 const auto *EndDef = First;
3162 if (ChainDef == Second)
3164 if (MSSA->isLiveOnEntryDef(ChainDef))
3168 auto *MP = cast<MemoryPhi>(EndDef);
3169 auto ReachableOperandPred = [&](
const Use &U) {
3172 auto FilteredPhiArgs =
3175 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3176 std::back_inserter(OperandList));
3177 bool Okay = OperandList.size() == 1;
3180 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
3182 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
3191 void NewGVN::verifyMemoryCongruency()
const {
3194 for (
const auto *CC : CongruenceClasses) {
3195 if (CC == TOPClass || CC->isDead())
3197 if (CC->getStoreCount() != 0) {
3198 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
3199 "Any class with a store as a leader should have a " 3200 "representative stored value");
3201 assert(CC->getMemoryLeader() &&
3202 "Any congruence class with a store should have a " 3203 "representative access");
3206 if (CC->getMemoryLeader())
3207 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
3208 "Representative MemoryAccess does not appear to be reverse " 3210 for (
auto M : CC->memory())
3211 assert(MemoryAccessToClass.lookup(M) == CC &&
3212 "Memory member does not appear to be reverse mapped properly");
3220 auto ReachableAccessPred =
3221 [&](
const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
3222 bool Result = ReachableBlocks.count(Pair.first->getBlock());
3223 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
3224 MemoryToDFSNum(Pair.first) == 0)
3226 if (
auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3231 if (
auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3232 for (
auto &U : MemPHI->incoming_values()) {
3233 if (
auto *I = dyn_cast<Instruction>(&*U)) {
3245 for (
auto KV : Filtered) {
3246 if (
auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
3248 if (FirstMUD && SecondMUD) {
3250 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
3251 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
3252 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
3253 "The instructions for these memory operations should have " 3254 "been in the same congruence class or reachable through" 3255 "a single argument phi");
3257 }
else if (
auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
3260 auto ReachableOperandPred = [&](
const Use &U) {
3261 return ReachableEdges.count(
3262 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
3267 auto FilteredPhiArgs =
3271 std::back_inserter(PhiOpClasses), [&](
const Use &U) {
3272 const MemoryDef *MD = cast<MemoryDef>(U);
3276 PhiOpClasses.begin()) &&
3277 "All MemoryPhi arguments should be in the same class");
3286 void NewGVN::verifyIterationSettled(
Function &F) {
3296 std::map<const Value *, CongruenceClass> BeforeIteration;
3298 for (
auto &KV : ValueToClass) {
3299 if (
auto *I = dyn_cast<Instruction>(KV.first))
3301 if (InstrToDFSNum(I) == 0)
3303 BeforeIteration.insert({KV.first, *KV.second});
3306 TouchedInstructions.set();
3307 TouchedInstructions.reset(0);
3308 iterateTouchedInstructions();
3311 for (
const auto &KV : ValueToClass) {
3312 if (
auto *I = dyn_cast<Instruction>(KV.first))
3314 if (InstrToDFSNum(I) == 0)
3318 auto *BeforeCC = &BeforeIteration.
find(KV.first)->second;
3319 auto *AfterCC = KV.second;
3322 if (!EqualClasses.
count({BeforeCC, AfterCC})) {
3323 assert(BeforeCC->isEquivalentTo(AfterCC) &&
3324 "Value number changed after main loop completed!");
3325 EqualClasses.
insert({BeforeCC, AfterCC});
3336 void NewGVN::verifyStoreExpressions()
const {
3341 std::pair<
const Value *,
3342 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3344 for (
const auto &KV : ExpressionToClass) {
3345 if (
auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3347 auto Res = StoreExpressionSet.insert(
3348 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3349 SE->getStoredValue())});
3350 bool Okay = Res.second;
3355 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3356 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3357 lookupOperandLeader(SE->getStoredValue()));
3358 assert(Okay &&
"Stored expression conflict exists in expression table");
3359 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3360 assert(ValueExpr && ValueExpr->equals(*SE) &&
3361 "StoreExpression in ExpressionToClass is not latest " 3362 "StoreExpression for value");
3371 void NewGVN::iterateTouchedInstructions() {
3372 unsigned int Iterations = 0;
3374 int FirstInstr = TouchedInstructions.find_first();
3376 if (FirstInstr == -1)
3378 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
3379 while (TouchedInstructions.any()) {
3385 for (
unsigned InstrNum : TouchedInstructions.set_bits()) {
3389 if (InstrNum == 0) {
3390 TouchedInstructions.reset(InstrNum);
3394 Value *V = InstrFromDFSNum(InstrNum);
3395 const BasicBlock *CurrBlock = getBlockForValue(V);
3398 if (CurrBlock != LastBlock) {
3399 LastBlock = CurrBlock;
3400 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3401 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3404 if (!BlockReachable) {
3405 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3408 <<
" because it is unreachable\n");
3411 updateProcessedCount(CurrBlock);
3415 TouchedInstructions.reset(InstrNum);
3417 if (
auto *MP = dyn_cast<MemoryPhi>(V)) {
3419 valueNumberMemoryPhi(MP);
3420 }
else if (
auto *I = dyn_cast<Instruction>(V)) {
3421 valueNumberInstruction(I);
3425 updateProcessedCount(V);
3428 NumGVNMaxIterations =
std::max(NumGVNMaxIterations.getValue(), Iterations);
3432 bool NewGVN::runGVN() {
3435 bool Changed =
false;
3437 MSSAWalker = MSSA->getWalker();
3438 SingletonDeadExpression =
new (ExpressionAllocator)
DeadExpression();
3442 unsigned ICount = 1;
3444 DFSToInstr.emplace_back(
nullptr);
3454 unsigned Counter = 0;
3455 for (
auto &B : RPOT) {
3456 auto *Node = DT->getNode(B);
3457 assert(Node &&
"RPO and Dominator tree should have same reachability");
3458 RPOOrdering[Node] = ++Counter;
3461 for (
auto &B : RPOT) {
3462 auto *Node = DT->getNode(B);
3463 if (Node->getChildren().size() > 1)
3466 return RPOOrdering[
A] < RPOOrdering[
B];
3473 const auto &BlockRange = assignDFSNumbers(B, ICount);
3474 BlockInstRange.insert({
B, BlockRange});
3475 ICount += BlockRange.second - BlockRange.first;
3477 initializeCongruenceClasses(F);
3479 TouchedInstructions.resize(ICount);
3483 ExpressionToClass.reserve(ICount);
3486 const auto &InstRange = BlockInstRange.lookup(&F.
getEntryBlock());
3487 TouchedInstructions.set(InstRange.first, InstRange.second);
3489 <<
" marked reachable\n");
3492 iterateTouchedInstructions();
3493 verifyMemoryCongruency();
3494 verifyIterationSettled(F);
3495 verifyStoreExpressions();
3497 Changed |= eliminateInstructions(F);
3500 for (
Instruction *ToErase : InstructionsToErase) {
3501 if (!ToErase->use_empty())
3504 if (ToErase->getParent())
3505 ToErase->eraseFromParent();
3509 auto UnreachableBlockPred = [&](
const BasicBlock &BB) {
3510 return !ReachableBlocks.count(&BB);
3515 <<
" is unreachable\n");
3516 deleteInstructionsInBlock(&BB);
3574 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3585 void NewGVN::convertClassToDFSOrdered(
3589 for (
auto D : Dense) {
3594 assert(BB &&
"Should have figured out a basic block for value");
3602 if (
auto *SI = dyn_cast<StoreInst>(
D)) {
3614 "The dense set member should always be an instruction");
3619 if (
auto *PN = RealToTemp.lookup(Def)) {
3621 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3630 unsigned int UseCount = 0;
3632 for (
auto &U : Def->
uses()) {
3633 if (
auto *I = dyn_cast<Instruction>(U.getUser())) {
3635 if (InstructionsToErase.count(I))
3640 if (
auto *
P = dyn_cast<PHINode>(I)) {
3641 IBlock =
P->getIncomingBlock(U);
3644 VDUse.
LocalNum = InstrDFS.size() + 1;
3646 IBlock = getBlockForValue(I);
3652 if (ReachableBlocks.count(IBlock) == 0)
3668 ProbablyDead.
insert(Def);
3670 UseCounts[
Def] = UseCount;
3676 void NewGVN::convertClassToLoadsAndStores(
3677 const CongruenceClass &Dense,
3679 for (
auto D : Dense) {
3680 if (!isa<LoadInst>(
D) && !isa<StoreInst>(
D))
3691 if (
auto *I = dyn_cast<Instruction>(
D))
3711 if (!isa<LoadInst>(I))
3723 static const unsigned KnownIDs[] = {
3736 void NewGVN::deleteInstructionsInBlock(
BasicBlock *BB) {
3738 ++NumGVNBlocksDeleted;
3742 auto StartPoint = BB->
rbegin();
3750 if (isa<LandingPadInst>(Inst))
3754 ++NumGVNInstrDeleted;
3763 void NewGVN::markInstructionForDeletion(
Instruction *I) {
3765 InstructionsToErase.insert(I);
3769 LLVM_DEBUG(
dbgs() <<
"Replacing " << *I <<
" with " << *V <<
"\n");
3773 markInstructionForDeletion(I);
3780 class ValueDFSStack {
3782 Value *back()
const {
return ValueStack.back(); }
3783 std::pair<int, int> dfs_back()
const {
return DFSStack.back(); }
3785 void push_back(
Value *V,
int DFSIn,
int DFSOut) {
3786 ValueStack.emplace_back(V);
3787 DFSStack.emplace_back(DFSIn, DFSOut);
3790 bool empty()
const {
return DFSStack.empty(); }
3792 bool isInScope(
int DFSIn,
int DFSOut)
const {
3795 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3798 void popUntilDFSScope(
int DFSIn,
int DFSOut) {
3801 assert(ValueStack.size() == DFSStack.size() &&
3802 "Mismatch between ValueStack and DFSStack");
3804 !DFSStack.empty() &&
3805 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3806 DFSStack.pop_back();
3807 ValueStack.pop_back();
3819 CongruenceClass *NewGVN::getClassForExpression(
const Expression *E)
const {
3820 if (
auto *VE = dyn_cast<VariableExpression>(E))
3821 return ValueToClass.lookup(VE->getVariableValue());
3822 else if (isa<DeadExpression>(E))
3824 return ExpressionToClass.lookup(E);
3833 if (
auto *CE = dyn_cast<ConstantExpression>(E))
3834 return CE->getConstantValue();
3835 if (
auto *VE = dyn_cast<VariableExpression>(E)) {
3836 auto *V = VE->getVariableValue();
3838 return VE->getVariableValue();
3841 auto *CC = getClassForExpression(E);
3845 return CC->getLeader();
3847 for (
auto Member : *CC) {
3849 if (MemberInst == OrigInst)
3854 if (DT->dominates(getBlockForValue(MemberInst), BB))
3860 bool NewGVN::eliminateInstructions(
Function &F) {
3884 bool AnythingReplaced =
false;
3888 DT->updateDFSNumbers();
3894 if (!ReachableEdges.count({PHI->getIncomingBlock(Operand), BB})) {
3898 <<
" with undef due to it being unreachable\n");
3912 for (
auto &KV : ReachableEdges)
3913 ReachablePredCount[KV.getEnd()]++;
3914 for (
auto &BBPair : RevisitOnReachabilityChange) {
3915 for (
auto InstNum : BBPair.second) {
3916 auto *Inst = InstrFromDFSNum(InstNum);
3918 PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
3921 auto *BB = BBPair.first;
3922 if (ReachablePredCount.
lookup(BB) != PHI->getNumIncomingValues())
3923 ReplaceUnreachablePHIArgs(PHI, BB);
3929 for (
auto *CC :
reverse(CongruenceClasses)) {
3930 LLVM_DEBUG(
dbgs() <<
"Eliminating in congruence class " << CC->getID()
3936 if (CC->isDead() || CC->empty())
3939 if (CC == TOPClass) {
3940 for (
auto M : *CC) {
3941 auto *VTE = ValueToExpression.lookup(M);
3942 if (VTE && isa<DeadExpression>(VTE))
3943 markInstructionForDeletion(cast<Instruction>(M));
3944 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3945 InstructionsToErase.count(cast<Instruction>(M))) &&
3946 "Everything in TOP should be unreachable or dead at this " 3952 assert(CC->getLeader() &&
"We should have had a leader");
3958 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
3961 for (
auto M : *CC) {
3964 if (Member == Leader || !isa<Instruction>(Member) ||
3966 MembersLeft.
insert(Member);
3969 LLVM_DEBUG(
dbgs() <<
"Found replacement " << *(Leader) <<
" for " 3970 << *Member <<
"\n");
3971 auto *I = cast<Instruction>(Member);
3972 assert(Leader != I &&
"About to accidentally remove our leader");
3973 replaceInstruction(I, Leader);
3974 AnythingReplaced =
true;
3976 CC->swap(MembersLeft);
3979 if (CC->size() != 1 || RealToTemp.count(Leader)) {
3984 ValueDFSStack EliminationStack;
3988 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
3992 for (
auto &VD : DFSOrderedSet) {
3993 int MemberDFSIn = VD.DFSIn;
3994 int MemberDFSOut = VD.DFSOut;
3996 bool FromStore = VD.Def.getInt();
4001 auto *DefInst = dyn_cast_or_null<Instruction>(
Def);
4002 if (DefInst && AllTempInstructions.count(DefInst)) {
4003 auto *PN = cast<PHINode>(DefInst);
4008 AllTempInstructions.erase(PN);
4009 auto *DefBlock = getBlockForValue(Def);
4013 PN->insertBefore(&DefBlock->front());
4015 NumGVNPHIOfOpsEliminations++;
4018 if (EliminationStack.empty()) {
4022 << EliminationStack.dfs_back().first <<
"," 4023 << EliminationStack.dfs_back().second <<
")\n");
4026 LLVM_DEBUG(
dbgs() <<
"Current DFS numbers are (" << MemberDFSIn <<
"," 4027 << MemberDFSOut <<
")\n");
4041 bool ShouldPush = Def && EliminationStack.empty();
4043 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
4045 if (OutOfScope || ShouldPush) {
4047 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
4048 bool ShouldPush = Def && EliminationStack.empty();
4050 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
4069 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
4070 isa<Instruction>(
Def) && !FromStore)
4071 markInstructionForDeletion(cast<Instruction>(Def));
4077 assert(isa<Instruction>(U->get()) &&
4078 "Current def should have been an instruction");
4079 assert(isa<Instruction>(U->getUser()) &&
4080 "Current user should have been an instruction");
4086 Instruction *InstUse = cast<Instruction>(U->getUser());
4087 if (InstructionsToErase.count(InstUse)) {
4088 auto &UseCount = UseCounts[U->get()];
4089 if (--UseCount == 0) {
4090 ProbablyDead.
insert(cast<Instruction>(U->get()));
4096 if (EliminationStack.empty())
4099 Value *DominatingLeader = EliminationStack.back();
4102 bool isSSACopy = II && II->
getIntrinsicID() == Intrinsic::ssa_copy;
4104 DominatingLeader = II->getOperand(0);
4107 if (U->get() == DominatingLeader)
4110 <<
"Found replacement " << *DominatingLeader <<
" for " 4111 << *U->get() <<
" in " << *(U->getUser()) <<
"\n");
4116 auto *ReplacedInst = cast<Instruction>(U->get());
4117 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
4118 if (!PI || DominatingLeader != PI->OriginalOp)
4120 U->set(DominatingLeader);
4123 auto &LeaderUseCount = UseCounts[DominatingLeader];
4125 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
4126 ProbablyDead.
erase(cast<Instruction>(DominatingLeader));
4129 if (LeaderUseCount == 0 && isSSACopy)
4132 AnythingReplaced =
true;
4139 for (
auto *I : ProbablyDead)
4141 markInstructionForDeletion(I);
4145 for (
auto *Member : *CC)
4146 if (!isa<Instruction>(Member) ||
4147 !InstructionsToErase.count(cast<Instruction>(Member)))
4148 MembersLeft.
insert(Member);
4149 CC->swap(MembersLeft);
4152 if (CC->getStoreCount() > 0) {
4153 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
4154 llvm::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
4155 ValueDFSStack EliminationStack;
4156 for (
auto &VD : PossibleDeadStores) {
4157 int MemberDFSIn = VD.DFSIn;
4158 int MemberDFSOut = VD.DFSOut;
4159 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
4160 if (EliminationStack.empty() ||
4161 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
4163 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
4164 if (EliminationStack.empty()) {
4165 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
4170 if (isa<LoadInst>(Member))
4172 assert(!EliminationStack.empty());
4173 Instruction *Leader = cast<Instruction>(EliminationStack.back());
4178 <<
" that is dominated by " << *Leader <<
"\n");
4179 markInstructionForDeletion(Member);
4185 return AnythingReplaced;
4193 unsigned int NewGVN::getRank(
const Value *V)
const {
4197 if (isa<ConstantExpr>(V))
4199 if (isa<UndefValue>(V))
4201 if (isa<Constant>(V))
4203 else if (
auto *A = dyn_cast<Argument>(V))
4204 return 3 + A->getArgNo();
4208 unsigned Result = InstrToDFSNum(V);
4210 return 4 + NumFuncArgs + Result;
4217 bool NewGVN::shouldSwapOperands(
const Value *A,
const Value *B)
const {
4221 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
4252 if (skipFunction(F))
4254 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4255 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4256 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
4257 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
4258 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
Legacy wrapper pass to provide the GlobalsAAResult object.
void initializeNewGVNLegacyPassPass(PassRegistry &)
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
static ConstantInt * getFalse(LLVMContext &Context)
This class is the base class for the comparison instructions.
void setInt(IntType IntVal)
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the load at De...
~BasicExpression() override
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
unsigned getValueID() const
Return an ID for the concrete type of this object.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
void dropAllReferences()
Drop all references to operands.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS)
Compute iterated dominance frontiers using a linear time algorithm.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS)
This is the interface for a simple mod/ref and alias analysis over globals.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
static bool okayForPHIOfOps(const Instruction *I)
Implements a dense probed hash-table based set.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
bool isTerminator() const
1 1 1 0 True if unordered or not equal
Recycle small arrays allocated from a BumpPtrAllocator.
void deleteValue()
Delete a pointer to a generic Value.
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
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
reverse_iterator rbegin()
Value * getCondition() const
This defines the Use class.
Constant * getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, const DataLayout &DL)
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
ExactEqualsExpression(const Expression &E)
LLVMContext & getContext() const
Get the context in which this basic block lives.
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is false when two compares have matching operands.
hash_code getComputedHash() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
void setPointer(PointerTy PtrVal)
static cl::opt< bool > EnablePhiOfOps("enable-phi-of-ops", cl::init(true), cl::Hidden)
Currently, the generation "phi of ops" can result in correctness issues.
~AggregateValueExpression() override
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Value * SimplifyGEPInst(Type *SrcTy, ArrayRef< Value *> Ops, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
hash_code getComputedHash() const
int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr, MemIntrinsic *DepMI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the memory int...
Constant * getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Encapsulates MemorySSA, including all data associated with memory accesses.
static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is true when two compares have matching operands.
PointerIntPair< Value *, 1, bool > Def
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
bool equals(const Expression &Other) const override
This file provides an implementation of debug counters.
static unsigned getHashValue(const ExactEqualsExpression &E)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Value * SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
Type * getType() const
All values are typed, get the type of this value.
static int getID(struct InternalInstruction *insn, const void *miiArg)
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static bool isCounterSet(unsigned ID)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
This is the generic walker interface for walkers of MemorySSA.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static const Expression * getEmptyKey()
Value * getOperand(unsigned i) const
int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr, StoreInst *DepSI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the store at D...
Value * getOperand(unsigned i_nocapture) const
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree...
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
unsigned getNumOperands() const
friend const_iterator end(StringRef path)
Get end iterator over path.
Value * SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q)
Given operands for a SelectInst, fold the result or return null.
Control flow instructions. These all have token chains.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Allocate memory in an ever growing pool, as if by bump-pointer.
Conditional or Unconditional Branch instruction.
static void setCounterValue(unsigned ID, int64_t Count)
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Constant * getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
mapped_iterator< ItTy, FuncTy > map_iterator(ItTy I, FuncTy F)
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static int64_t getCounterValue(unsigned ID)
Value * SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
Represent the analysis usage information of a pass.
iterator_range< def_chain_iterator< T, true > > optimized_def_chain(T MA)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
This file provides the interface for LLVM's Global Value Numbering pass.
FunctionPass class - This class is used to implement most global optimizations.
Value * getPointerOperand()
unsigned getDFSNumOut() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static bool shouldExecute(unsigned CounterName)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static const Expression * getTombstoneKey()
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
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.
static bool isCopyOfAPHI(const Value *V)
void sort(IteratorTy Start, IteratorTy End)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
void setOpcode(unsigned opcode)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
PreservedAnalyses run(Function &F, AnalysisManager< Function > &AM)
Run the pass over the function.
BasicBlock * getBlock() const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
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...
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
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.
A range adaptor for a pair of iterators.
static bool alwaysAvailable(Value *V)
Class that has the common methods + fields of memory uses/defs.
iterator_range< user_iterator > users()
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
An opaque object representing a hash code.
bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates uninitialized memory (such ...
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
bool operator<(const ValueDFS &Other) const
amdgpu Simplify well known AMD library false Value Value * Arg
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
iterator_range< typename GraphTraits< GraphType >::nodes_iterator > nodes(const GraphType &G)
static Value * getCopyOf(const Value *V)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates zero-filled memory (such as...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
iterator find(const_arg_type_t< ValueT > V)
~LoadExpression() override
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
~CallExpression() override
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant *> Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
void preserve()
Mark an analysis as preserved.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
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...
static std::string getBlockName(const BasicBlock *B)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
~StoreExpression() override
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool equals(const Expression &Other) const override
static bool isEqual(const Expression *LHS, const Expression *RHS)
static bool isCopyOfPHI(const Value *V, const PHINode *PN)
0 0 0 1 True if ordered and equal
Module * getParent()
Get the module that this global value is contained inside of...
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.
~PHIExpression() override
Value * getOperand(unsigned N) const
The header file for the GVN pass that contains expression handling classes.
bool wouldInstructionBeTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used...
static cl::opt< bool > EnableStoreRefinement("enable-store-refinement", cl::init(false), cl::Hidden)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
FunctionPass * createNewGVNPass()
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
unsigned getOpcode() const
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
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...
static unsigned getHashValue(const Expression *E)
virtual bool exactlyEquals(const Expression &Other) const
op_range incoming_values()
OutputIt copy(R &&Range, OutputIt Out)
void op_push_back(Value *Arg)
Value * getPointerOperand()
DEBUG_COUNTER(VNCounter, "newgvn-vn", "Controls which instructions are value numbered")
static IntegerType * getInt8Ty(LLVMContext &C)
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false, false) INITIALIZE_PASS_END(NewGVNLegacyPass
static void patchReplacementInstruction(Instruction *I, Value *Repl)
void allocateOperands(RecyclerType &Recycler, BumpPtrAllocator &Allocator)
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
bool operator==(const Expression &Other) const