127#define DEBUG_TYPE "newgvn"
129STATISTIC(NumGVNInstrDeleted,
"Number of instructions deleted");
130STATISTIC(NumGVNBlocksDeleted,
"Number of blocks deleted");
131STATISTIC(NumGVNOpsSimplified,
"Number of Expressions simplified");
132STATISTIC(NumGVNPhisAllSame,
"Number of PHIs whos arguments are all the same");
134 "Maximum Number of iterations it took to converge GVN");
135STATISTIC(NumGVNLeaderChanges,
"Number of leader changes");
136STATISTIC(NumGVNSortedLeaderChanges,
"Number of sorted leader changes");
138 "Number of avoided sorted leader changes");
139STATISTIC(NumGVNDeadStores,
"Number of redundant/dead stores eliminated");
140STATISTIC(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");
163namespace 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;
207 for (
const auto &
Op :
I->operands()) {
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);
225 InComponent.insert(
I);
226 ValueToComponent[
I] = ComponentID;
228 while (!
Stack.empty() && Root.lookup(
Stack.back()) >= OurDFS) {
232 InComponent.insert(Member);
233 ValueToComponent[
Member] = ComponentID;
242 unsigned int DFSNum = 1;
292class CongruenceClass {
294 using MemberType =
Value;
299 explicit CongruenceClass(
unsigned ID) :
ID(
ID) {}
300 CongruenceClass(
unsigned ID, std::pair<Value *, unsigned int> Leader,
302 :
ID(
ID), RepLeader(Leader), DefiningExpr(E) {}
304 unsigned getID()
const {
return ID; }
311 return empty() && memory_empty();
315 Value *getLeader()
const {
return RepLeader.first; }
316 void setLeader(std::pair<Value *, unsigned int> Leader) {
319 const std::pair<Value *, unsigned int> &getNextLeader()
const {
322 void resetNextLeader() { NextLeader = {
nullptr, ~0}; }
323 bool addPossibleLeader(std::pair<Value *, unsigned int> LeaderPair) {
324 if (LeaderPair.second < RepLeader.second) {
325 NextLeader = RepLeader;
326 RepLeader = LeaderPair;
328 }
else if (LeaderPair.second < NextLeader.second) {
329 NextLeader = LeaderPair;
335 void setStoredValue(
Value *Leader) { RepStoredValue = Leader; }
336 const MemoryAccess *getMemoryLeader()
const {
return RepMemoryAccess; }
337 void setMemoryLeader(
const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
340 const Expression *getDefiningExpr()
const {
return DefiningExpr; }
343 bool empty()
const {
return Members.empty(); }
344 unsigned size()
const {
return Members.size(); }
347 void insert(MemberType *M) { Members.insert(M); }
348 void erase(MemberType *M) { Members.erase(M); }
352 bool memory_empty()
const {
return MemoryMembers.empty(); }
353 unsigned memory_size()
const {
return MemoryMembers.size(); }
355 return MemoryMembers.begin();
358 return MemoryMembers.end();
361 return make_range(memory_begin(), memory_end());
364 void memory_insert(
const MemoryMemberType *M) { MemoryMembers.insert(M); }
365 void memory_erase(
const MemoryMemberType *M) { MemoryMembers.erase(M); }
368 unsigned getStoreCount()
const {
return StoreCount; }
369 void incStoreCount() { ++StoreCount; }
370 void decStoreCount() {
371 assert(StoreCount != 0 &&
"Store count went negative");
376 bool definesNoMemory()
const {
return StoreCount == 0 && memory_empty(); }
380 bool isEquivalentTo(
const CongruenceClass *
Other)
const {
386 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
388 Other->RepMemoryAccess))
390 if (DefiningExpr !=
Other->DefiningExpr)
391 if (!DefiningExpr || !
Other->DefiningExpr ||
392 *DefiningExpr != *
Other->DefiningExpr)
395 if (Members.size() !=
Other->Members.size())
406 std::pair<Value *, unsigned int> RepLeader = {
nullptr, ~0
U};
411 std::pair<Value *, unsigned int> NextLeader = {
nullptr, ~0
U};
414 Value *RepStoredValue =
nullptr;
429 MemoryMemberSet MemoryMembers;
448 return E.exactlyEquals(
Other);
454 auto Val =
static_cast<uintptr_t
>(-1);
455 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
456 return reinterpret_cast<const Expression *
>(Val);
460 auto Val =
static_cast<uintptr_t
>(~1U);
461 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
462 return reinterpret_cast<const Expression *
>(Val);
466 return E->getComputedHash();
470 return E.getComputedHash();
474 if (
RHS == getTombstoneKey() ||
RHS == getEmptyKey())
482 if (
LHS == getTombstoneKey() ||
RHS == getTombstoneKey() ||
483 LHS == getEmptyKey() ||
RHS == getEmptyKey())
489 if (
LHS->getComputedHash() !=
RHS->getComputedHash())
508 std::unique_ptr<PredicateInfo> PredInfo;
514 mutable TarjanSCC SCCFinder;
518 unsigned int NumFuncArgs = 0;
529 CongruenceClass *TOPClass =
nullptr;
530 std::vector<CongruenceClass *> CongruenceClasses;
531 unsigned NextCongruenceNum = 0;
566 ExpressionToPhiOfOps;
615 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
618 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
623 ExpressionClassMap ExpressionToClass;
675 :
F(
F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), AC(AC),
DL(
DL),
677 SQ(
DL, TLI, DT, AC, nullptr,
false,
691 : Expr(Expr), ExtraDep(ExtraDep), PredDep(PredDep) {}
692 ExprResult(
const ExprResult &) =
delete;
693 ExprResult(ExprResult &&
Other)
695 Other.Expr =
nullptr;
696 Other.ExtraDep =
nullptr;
697 Other.PredDep =
nullptr;
699 ExprResult &operator=(
const ExprResult &
Other) =
delete;
700 ExprResult &operator=(ExprResult &&
Other) =
delete;
702 ~ExprResult() {
assert(!ExtraDep &&
"unhandled ExtraDep"); }
704 operator bool()
const {
return Expr; }
706 static ExprResult
none() {
return {
nullptr,
nullptr,
nullptr}; }
707 static ExprResult some(
const Expression *Expr,
Value *ExtraDep =
nullptr) {
708 return {Expr, ExtraDep,
nullptr};
710 static ExprResult some(
const Expression *Expr,
712 return {Expr,
nullptr, PredDep};
716 return {Expr, ExtraDep, PredDep};
727 using ValPair = std::pair<Value *, BasicBlock *>;
731 bool &OriginalOpsConstant)
const;
744 createAggregateValueExpression(
Instruction *)
const;
748 CongruenceClass *createCongruenceClass(
Value *Leader,
const Expression *
E) {
751 unsigned LeaderDFS = 0;
758 else if (
auto *
I = dyn_cast<Instruction>(Leader))
759 LeaderDFS = InstrToDFSNum(
I);
761 new CongruenceClass(NextCongruenceNum++, {Leader, LeaderDFS},
E);
762 CongruenceClasses.emplace_back(result);
767 auto *
CC = createCongruenceClass(
nullptr,
nullptr);
768 CC->setMemoryLeader(MA);
772 CongruenceClass *ensureLeaderOfMemoryClass(
MemoryAccess *MA) {
773 auto *
CC = getMemoryClass(MA);
774 if (
CC->getMemoryLeader() != MA)
775 CC = createMemoryClass(MA);
779 CongruenceClass *createSingletonCongruenceClass(
Value *Member) {
780 CongruenceClass *CClass = createCongruenceClass(Member,
nullptr);
781 CClass->insert(Member);
782 ValueToClass[
Member] = CClass;
786 void initializeCongruenceClasses(
Function &
F);
804 ExprResult performSymbolicEvaluation(
Instruction *,
811 ExprResult performSymbolicCallEvaluation(
Instruction *)
const;
817 ExprResult performSymbolicCmpEvaluation(
Instruction *)
const;
818 ExprResult performSymbolicPredicateInfoEvaluation(
IntrinsicInst *)
const;
823 CongruenceClass *getClassForExpression(
const Expression *
E)
const;
826 CongruenceClass *, CongruenceClass *);
828 CongruenceClass *, CongruenceClass *);
829 Value *getNextValueLeader(CongruenceClass *)
const;
830 const MemoryAccess *getNextMemoryLeader(CongruenceClass *)
const;
832 CongruenceClass *getMemoryClass(
const MemoryAccess *MA)
const;
837 unsigned int getRank(
const Value *)
const;
838 bool shouldSwapOperands(
const Value *,
const Value *)
const;
839 bool shouldSwapOperandsForIntrinsic(
const Value *,
const Value *,
845 Value *findConditionEquivalence(
Value *)
const;
849 void convertClassToDFSOrdered(
const CongruenceClass &,
853 void convertClassToLoadsAndStores(
const CongruenceClass &,
856 bool eliminateInstructions(
Function &);
864 template <
typename Map,
typename KeyType>
865 void touchAndErase(Map &,
const KeyType &);
866 void markUsersTouched(
Value *);
870 void markValueLeaderChangeTouched(CongruenceClass *
CC);
871 void markMemoryLeaderChangeTouched(CongruenceClass *
CC);
878 void iterateTouchedInstructions();
881 void cleanupTables();
882 std::pair<unsigned, unsigned> assignDFSNumbers(
BasicBlock *,
unsigned);
883 void updateProcessedCount(
const Value *V);
884 void verifyMemoryCongruency()
const;
885 void verifyIterationSettled(
Function &
F);
886 void verifyStoreExpressions()
const;
893 template <
class T,
class Range>
T *getMinDFSOfRange(
const Range &)
const;
895 unsigned InstrToDFSNum(
const Value *V)
const {
896 assert(isa<Instruction>(V) &&
"This should not be used for MemoryAccesses");
897 return InstrDFS.
lookup(V);
901 return MemoryToDFSNum(MA);
904 Value *InstrFromDFSNum(
unsigned DFSNum) {
return DFSToInstr[DFSNum]; }
909 unsigned MemoryToDFSNum(
const Value *MA)
const {
910 assert(isa<MemoryAccess>(MA) &&
911 "This should not be used with instructions");
912 return isa<MemoryUseOrDef>(MA)
913 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
929 if (!isa<LoadExpression>(
RHS) && !isa<StoreExpression>(
RHS))
931 return LHS.MemoryExpression::equals(
RHS);
942 if (
const auto *S = dyn_cast<StoreExpression>(&
Other))
952 if (
auto *
RHS = dyn_cast<CallExpression>(&
Other))
986 if (
auto *
I = dyn_cast<Instruction>(V)) {
987 auto *Parent =
I->getParent();
990 Parent = TempToBlock.
lookup(V);
991 assert(Parent &&
"Every fake instruction should have a block");
995 auto *MP = dyn_cast<MemoryPhi>(V);
996 assert(MP &&
"Should have been an instruction or a MemoryPhi");
997 return MP->getBlock();
1003void NewGVN::deleteExpression(
const Expression *
E)
const {
1004 assert(isa<BasicExpression>(
E));
1005 auto *BE = cast<BasicExpression>(
E);
1012 if (
auto *
II = dyn_cast<IntrinsicInst>(V))
1013 if (
II->getIntrinsicID() == Intrinsic::ssa_copy)
1014 return II->getOperand(0);
1025 return CO && isa<PHINode>(CO);
1032 llvm::sort(Ops, [&](
const ValPair &P1,
const ValPair &P2) {
1033 return BlockInstRange.
lookup(P1.second).first <
1034 BlockInstRange.
lookup(P2.second).first;
1042 return isa<Constant>(V) || isa<Argument>(V);
1054 bool &OriginalOpsConstant)
const {
1055 unsigned NumOps = PHIOperands.
size();
1056 auto *
E =
new (ExpressionAllocator)
PHIExpression(NumOps, PHIBlock);
1058 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1059 E->setType(PHIOperands.
begin()->first->getType());
1060 E->setOpcode(Instruction::PHI);
1064 auto *BB =
P.second;
1065 if (
auto *PHIOp = dyn_cast<PHINode>(
I))
1068 if (!ReachableEdges.
count({BB, PHIBlock}))
1071 if (ValueToClass.
lookup(
P.first) == TOPClass)
1073 OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(
P.first);
1074 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
1075 return lookupOperandLeader(
P.first) !=
I;
1077 std::transform(Filtered.begin(), Filtered.end(),
op_inserter(
E),
1078 [&](
const ValPair &
P) ->
Value * {
1079 return lookupOperandLeader(
P.first);
1087 bool AllConstant =
true;
1088 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
I))
1089 E->setType(
GEP->getSourceElementType());
1091 E->setType(
I->getType());
1092 E->setOpcode(
I->getOpcode());
1093 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1098 auto Operand = lookupOperandLeader(O);
1099 AllConstant = AllConstant && isa<Constant>(Operand);
1106const Expression *NewGVN::createBinaryExpression(
unsigned Opcode,
Type *
T,
1115 E->setOpcode(Opcode);
1116 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1122 if (shouldSwapOperands(Arg1, Arg2))
1125 E->op_push_back(lookupOperandLeader(Arg1));
1126 E->op_push_back(lookupOperandLeader(Arg2));
1129 if (
auto Simplified = checkExprResults(
E,
I, V)) {
1130 addAdditionalUsers(Simplified,
I);
1142 return ExprResult::none();
1144 if (
auto *
C = dyn_cast<Constant>(V)) {
1147 <<
" constant " << *
C <<
"\n");
1148 NumGVNOpsSimplified++;
1149 assert(isa<BasicExpression>(
E) &&
1150 "We should always have had a basic expression here");
1151 deleteExpression(
E);
1152 return ExprResult::some(createConstantExpression(
C));
1153 }
else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1156 <<
" variable " << *V <<
"\n");
1157 deleteExpression(
E);
1158 return ExprResult::some(createVariableExpression(V));
1161 CongruenceClass *
CC = ValueToClass.
lookup(V);
1163 if (
CC->getLeader() &&
CC->getLeader() !=
I) {
1164 return ExprResult::some(createVariableOrConstant(
CC->getLeader()), V);
1166 if (
CC->getDefiningExpr()) {
1169 <<
" expression " << *
CC->getDefiningExpr() <<
"\n");
1170 NumGVNOpsSimplified++;
1171 deleteExpression(
E);
1172 return ExprResult::some(
CC->getDefiningExpr(), V);
1176 return ExprResult::none();
1182NewGVN::ExprResult NewGVN::createExpression(
Instruction *
I)
const {
1188 bool AllConstant = setBasicExpressionInfo(
I,
E);
1190 if (
I->isCommutative()) {
1195 assert(
I->getNumOperands() == 2 &&
"Unsupported commutative instruction!");
1196 if (shouldSwapOperands(
E->getOperand(0),
E->getOperand(1)))
1197 E->swapOperands(0, 1);
1200 if (
auto *CI = dyn_cast<CmpInst>(
I)) {
1204 if (shouldSwapOperands(
E->getOperand(0),
E->getOperand(1))) {
1205 E->swapOperands(0, 1);
1208 E->setOpcode((CI->getOpcode() << 8) | Predicate);
1210 assert(
I->getOperand(0)->getType() ==
I->getOperand(1)->getType() &&
1211 "Wrong types on cmp instruction");
1212 assert((
E->getOperand(0)->getType() ==
I->getOperand(0)->getType() &&
1213 E->getOperand(1)->getType() ==
I->getOperand(1)->getType()));
1216 if (
auto Simplified = checkExprResults(
E,
I, V))
1218 }
else if (isa<SelectInst>(
I)) {
1219 if (isa<Constant>(
E->getOperand(0)) ||
1220 E->getOperand(1) ==
E->getOperand(2)) {
1221 assert(
E->getOperand(1)->getType() ==
I->getOperand(1)->getType() &&
1222 E->getOperand(2)->getType() ==
I->getOperand(2)->getType());
1224 E->getOperand(2), Q);
1225 if (
auto Simplified = checkExprResults(
E,
I, V))
1228 }
else if (
I->isBinaryOp()) {
1231 if (
auto Simplified = checkExprResults(
E,
I, V))
1233 }
else if (
auto *CI = dyn_cast<CastInst>(
I)) {
1236 if (
auto Simplified = checkExprResults(
E,
I, V))
1238 }
else if (
auto *GEPI = dyn_cast<GetElementPtrInst>(
I)) {
1240 ArrayRef(std::next(
E->op_begin()),
E->op_end()),
1241 GEPI->getNoWrapFlags(), Q);
1242 if (
auto Simplified = checkExprResults(
E,
I, V))
1244 }
else if (AllConstant) {
1253 for (
Value *Arg :
E->operands())
1254 C.emplace_back(cast<Constant>(Arg));
1257 if (
auto Simplified = checkExprResults(
E,
I, V))
1260 return ExprResult::some(
E);
1264NewGVN::createAggregateValueExpression(
Instruction *
I)
const {
1265 if (
auto *
II = dyn_cast<InsertValueInst>(
I)) {
1266 auto *
E =
new (ExpressionAllocator)
1268 setBasicExpressionInfo(
I,
E);
1269 E->allocateIntOperands(ExpressionAllocator);
1272 }
else if (
auto *EI = dyn_cast<ExtractValueInst>(
I)) {
1273 auto *
E =
new (ExpressionAllocator)
1275 setBasicExpressionInfo(EI,
E);
1276 E->allocateIntOperands(ExpressionAllocator);
1286 return SingletonDeadExpression;
1291 E->setOpcode(
V->getValueID());
1296 if (
auto *
C = dyn_cast<Constant>(V))
1297 return createConstantExpression(
C);
1298 return createVariableExpression(V);
1303 E->setOpcode(
C->getValueID());
1309 E->setOpcode(
I->getOpcode());
1318 setBasicExpressionInfo(CI,
E);
1324 if (shouldSwapOperands(
E->getOperand(0),
E->getOperand(1)))
1325 E->swapOperands(0, 1);
1331bool NewGVN::someEquivalentDominates(
const Instruction *Inst,
1333 auto *
CC = ValueToClass.
lookup(Inst);
1354 if (DT->
dominates(cast<Instruction>(
CC->getLeader()), U))
1356 if (
CC->getNextLeader().first &&
1357 DT->
dominates(cast<Instruction>(
CC->getNextLeader().first), U))
1360 return Member !=
CC->getLeader() &&
1361 DT->
dominates(cast<Instruction>(Member), U);
1367Value *NewGVN::lookupOperandLeader(
Value *V)
const {
1368 CongruenceClass *
CC = ValueToClass.
lookup(V);
1375 return CC->getStoredValue() ?
CC->getStoredValue() :
CC->getLeader();
1382 auto *
CC = getMemoryClass(MA);
1384 "Every MemoryAccess should be mapped to a congruence class with a "
1385 "representative memory access");
1386 return CC->getMemoryLeader();
1392bool NewGVN::isMemoryAccessTOP(
const MemoryAccess *MA)
const {
1393 return getMemoryClass(MA) == TOPClass;
1400 new (ExpressionAllocator)
LoadExpression(1, LI, lookupMemoryLeader(MA));
1401 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1402 E->setType(LoadType);
1406 E->op_push_back(PointerOp);
1416 auto *StoredValueLeader = lookupOperandLeader(
SI->getValueOperand());
1417 auto *
E =
new (ExpressionAllocator)
1419 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1420 E->setType(
SI->getValueOperand()->getType());
1424 E->op_push_back(lookupOperandLeader(
SI->getPointerOperand()));
1435 auto *
SI = cast<StoreInst>(
I);
1436 auto *StoreAccess = getMemoryAccess(SI);
1438 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1442 StoreRHS = lookupMemoryLeader(StoreRHS);
1443 if (StoreRHS != StoreAccess->getDefiningAccess())
1444 addMemoryUsers(StoreRHS, StoreAccess);
1446 if (StoreRHS == StoreAccess)
1449 if (
SI->isSimple()) {
1453 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1454 const auto *LastCC = ExpressionToClass.lookup(LastStore);
1460 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
1466 if (
auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
1468 LastStore->getOperand(0)) &&
1469 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
1472 deleteExpression(LastStore);
1478 return createStoreExpression(SI, StoreAccess);
1484NewGVN::performSymbolicLoadCoercion(
Type *LoadType,
Value *LoadPtr,
1488 if (
auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1492 if (LI->
isAtomic() > DepSI->isAtomic() ||
1493 LoadType == DepSI->getValueOperand()->getType())
1497 if (
auto *
C = dyn_cast<Constant>(
1498 lookupOperandLeader(DepSI->getValueOperand()))) {
1501 <<
" to constant " << *Res <<
"\n");
1502 return createConstantExpression(Res);
1506 }
else if (
auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
1508 if (LI->
isAtomic() > DepLI->isAtomic())
1513 if (
auto *
C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1514 if (
auto *PossibleConstant =
1517 <<
" to constant " << *PossibleConstant <<
"\n");
1518 return createConstantExpression(PossibleConstant);
1521 }
else if (
auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1524 if (
auto *PossibleConstant =
1527 <<
" to constant " << *PossibleConstant <<
"\n");
1528 return createConstantExpression(PossibleConstant);
1535 if (LoadPtr != lookupOperandLeader(DepInst) &&
1542 if (isa<AllocaInst>(DepInst)) {
1547 else if (
auto *
II = dyn_cast<IntrinsicInst>(DepInst)) {
1548 if (
II->getIntrinsicID() == Intrinsic::lifetime_start)
1550 }
else if (
auto *InitVal =
1552 return createConstantExpression(InitVal);
1558 auto *LI = cast<LoadInst>(
I);
1567 if (isa<UndefValue>(LoadAddressLeader))
1574 if (
auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1583 if (
const auto *CoercionResult =
1584 performSymbolicLoadCoercion(LI->
getType(), LoadAddressLeader, LI,
1585 DefiningInst, DefiningAccess))
1586 return CoercionResult;
1590 const auto *
LE = createLoadExpression(LI->
getType(), LoadAddressLeader, LI,
1594 if (
LE->getMemoryLeader() != DefiningAccess)
1595 addMemoryUsers(
LE->getMemoryLeader(), OriginalAccess);
1600NewGVN::performSymbolicPredicateInfoEvaluation(
IntrinsicInst *
I)
const {
1601 auto *PI = PredInfo->getPredicateInfoFor(
I);
1603 return ExprResult::none();
1605 LLVM_DEBUG(
dbgs() <<
"Found predicate info from instruction !\n");
1607 const std::optional<PredicateConstraint> &Constraint = PI->getConstraint();
1609 return ExprResult::none();
1612 Value *CmpOp0 =
I->getOperand(0);
1613 Value *CmpOp1 = Constraint->OtherOp;
1615 Value *FirstOp = lookupOperandLeader(CmpOp0);
1616 Value *SecondOp = lookupOperandLeader(CmpOp1);
1617 Value *AdditionallyUsedValue = CmpOp0;
1620 if (shouldSwapOperandsForIntrinsic(FirstOp, SecondOp,
I)) {
1623 AdditionallyUsedValue = CmpOp1;
1627 return ExprResult::some(createVariableOrConstant(FirstOp),
1628 AdditionallyUsedValue, PI);
1632 !cast<ConstantFP>(FirstOp)->
isZero())
1633 return ExprResult::some(createConstantExpression(cast<Constant>(FirstOp)),
1634 AdditionallyUsedValue, PI);
1636 return ExprResult::none();
1640NewGVN::ExprResult NewGVN::performSymbolicCallEvaluation(
Instruction *
I)
const {
1641 auto *CI = cast<CallInst>(
I);
1642 if (
auto *
II = dyn_cast<IntrinsicInst>(
I)) {
1644 if (
auto *ReturnedValue =
II->getReturnedArgOperand()) {
1645 if (
II->getIntrinsicID() == Intrinsic::ssa_copy)
1646 if (
auto Res = performSymbolicPredicateInfoEvaluation(
II))
1648 return ExprResult::some(createVariableOrConstant(ReturnedValue));
1660 return ExprResult::none();
1666 return ExprResult::none();
1669 return ExprResult::some(
1670 createCallExpression(CI, TOPClass->getMemoryLeader()));
1674 return ExprResult::some(createCallExpression(CI, DefiningAccess));
1676 return ExprResult::some(
1677 createCallExpression(CI, TOPClass->getMemoryLeader()));
1679 return ExprResult::none();
1683CongruenceClass *NewGVN::getMemoryClass(
const MemoryAccess *MA)
const {
1685 assert(Result &&
"Should have found memory class");
1692 CongruenceClass *NewClass) {
1694 "Every MemoryAccess should be getting mapped to a non-null class");
1698 <<
" with current MemoryAccess leader ");
1702 bool Changed =
false;
1704 if (LookupResult != MemoryAccessToClass.
end()) {
1706 if (OldClass != NewClass) {
1708 if (
auto *MP = dyn_cast<MemoryPhi>(
From)) {
1709 OldClass->memory_erase(MP);
1710 NewClass->memory_insert(MP);
1712 if (OldClass->getMemoryLeader() ==
From) {
1713 if (OldClass->definesNoMemory()) {
1714 OldClass->setMemoryLeader(
nullptr);
1716 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1718 << OldClass->getID() <<
" to "
1719 << *OldClass->getMemoryLeader()
1720 <<
" due to removal of a memory member " << *
From
1722 markMemoryLeaderChangeTouched(OldClass);
1745 auto ICS = InstCycleState.
lookup(
I);
1746 if (ICS == ICS_Unknown) {
1748 auto &
SCC = SCCFinder.getComponentFor(
I);
1750 if (
SCC.size() == 1)
1751 InstCycleState.
insert({
I, ICS_CycleFree});
1756 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
1757 for (
const auto *Member : SCC)
1758 if (
auto *MemberPhi = dyn_cast<PHINode>(Member))
1759 InstCycleState.
insert({MemberPhi, ICS});
1762 if (ICS == ICS_Cycle)
1773 bool HasBackedge =
false;
1778 bool OriginalOpsConstant =
true;
1779 auto *
E = cast<PHIExpression>(createPHIExpression(
1780 PHIOps,
I, PHIBlock, HasBackedge, OriginalOpsConstant));
1784 bool HasUndef =
false, HasPoison =
false;
1786 if (isa<PoisonValue>(Arg)) {
1790 if (isa<UndefValue>(Arg)) {
1797 if (Filtered.empty()) {
1802 dbgs() <<
"PHI Node " << *
I
1803 <<
" has no non-undef arguments, valuing it as undef\n");
1808 dbgs() <<
"PHI Node " << *
I
1809 <<
" has no non-poison arguments, valuing it as poison\n");
1813 LLVM_DEBUG(
dbgs() <<
"No arguments of PHI node " << *
I <<
" are live\n");
1814 deleteExpression(
E);
1815 return createDeadExpression();
1817 Value *AllSameValue = *(Filtered.begin());
1835 if (HasPoison || HasUndef) {
1841 if (HasBackedge && !OriginalOpsConstant &&
1842 !isa<UndefValue>(AllSameValue) && !isCycleFree(
I))
1846 if (
auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1847 if (!someEquivalentDominates(AllSameInst,
I))
1853 if (isa<Instruction>(AllSameValue) &&
1854 InstrToDFSNum(AllSameValue) > InstrToDFSNum(
I))
1856 NumGVNPhisAllSame++;
1857 LLVM_DEBUG(
dbgs() <<
"Simplified PHI node " << *
I <<
" to " << *AllSameValue
1859 deleteExpression(
E);
1860 return createVariableOrConstant(AllSameValue);
1866NewGVN::performSymbolicAggrValueEvaluation(
Instruction *
I)
const {
1867 if (
auto *EI = dyn_cast<ExtractValueInst>(
I)) {
1868 auto *WO = dyn_cast<WithOverflowInst>(EI->getAggregateOperand());
1869 if (WO && EI->getNumIndices() == 1 && *EI->idx_begin() == 0)
1873 return createBinaryExpression(WO->getBinaryOp(), EI->getType(),
1874 WO->getLHS(), WO->getRHS(),
I);
1877 return createAggregateValueExpression(
I);
1880NewGVN::ExprResult NewGVN::performSymbolicCmpEvaluation(
Instruction *
I)
const {
1881 assert(isa<CmpInst>(
I) &&
"Expected a cmp instruction.");
1883 auto *CI = cast<CmpInst>(
I);
1886 auto Op0 = lookupOperandLeader(CI->
getOperand(0));
1887 auto Op1 = lookupOperandLeader(CI->
getOperand(1));
1888 auto OurPredicate = CI->getPredicate();
1889 if (shouldSwapOperands(Op0, Op1)) {
1891 OurPredicate = CI->getSwappedPredicate();
1898 auto *CmpPI = PredInfo->getPredicateInfoFor(
I);
1899 if (isa_and_nonnull<PredicateAssume>(CmpPI))
1900 return ExprResult::some(
1905 if (CI->isTrueWhenEqual())
1906 return ExprResult::some(
1908 else if (CI->isFalseWhenEqual())
1909 return ExprResult::some(
1939 auto *PI = PredInfo->getPredicateInfoFor(
Op);
1940 if (
const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1941 if (PI == LastPredInfo)
1946 if (!DT->
dominates(PBranch->To,
I->getParent()))
1953 auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1956 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1957 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1958 auto BranchPredicate = BranchCond->getPredicate();
1959 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1961 BranchPredicate = BranchCond->getSwappedPredicate();
1963 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1964 if (PBranch->TrueEdge) {
1970 return ExprResult::some(createConstantExpression(
C), PI);
1975 if (BranchPredicate == OurPredicate) {
1977 return ExprResult::some(
1980 }
else if (BranchPredicate ==
1983 return ExprResult::some(
1992 return createExpression(
I);
2004 switch (
I->getOpcode()) {
2005 case Instruction::ExtractValue:
2006 case Instruction::InsertValue:
2007 E = performSymbolicAggrValueEvaluation(
I);
2009 case Instruction::PHI: {
2011 auto *PN = cast<PHINode>(
I);
2012 for (
unsigned i = 0; i < PN->getNumOperands(); ++i)
2013 Ops.
push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
2016 E = performSymbolicPHIEvaluation(Ops,
I, getBlockForValue(
I));
2018 case Instruction::Call:
2019 return performSymbolicCallEvaluation(
I);
2021 case Instruction::Store:
2022 E = performSymbolicStoreEvaluation(
I);
2024 case Instruction::Load:
2025 E = performSymbolicLoadEvaluation(
I);
2027 case Instruction::BitCast:
2028 case Instruction::AddrSpaceCast:
2029 case Instruction::Freeze:
2030 return createExpression(
I);
2032 case Instruction::ICmp:
2033 case Instruction::FCmp:
2034 return performSymbolicCmpEvaluation(
I);
2036 case Instruction::FNeg:
2037 case Instruction::Add:
2038 case Instruction::FAdd:
2039 case Instruction::Sub:
2040 case Instruction::FSub:
2041 case Instruction::Mul:
2042 case Instruction::FMul:
2043 case Instruction::UDiv:
2044 case Instruction::SDiv:
2045 case Instruction::FDiv:
2046 case Instruction::URem:
2047 case Instruction::SRem:
2048 case Instruction::FRem:
2049 case Instruction::Shl:
2050 case Instruction::LShr:
2051 case Instruction::AShr:
2052 case Instruction::And:
2053 case Instruction::Or:
2054 case Instruction::Xor:
2055 case Instruction::Trunc:
2056 case Instruction::ZExt:
2057 case Instruction::SExt:
2058 case Instruction::FPToUI:
2059 case Instruction::FPToSI:
2060 case Instruction::UIToFP:
2061 case Instruction::SIToFP:
2062 case Instruction::FPTrunc:
2063 case Instruction::FPExt:
2064 case Instruction::PtrToInt:
2065 case Instruction::IntToPtr:
2066 case Instruction::Select:
2067 case Instruction::ExtractElement:
2068 case Instruction::InsertElement:
2069 case Instruction::GetElementPtr:
2070 return createExpression(
I);
2072 case Instruction::ShuffleVector:
2074 return ExprResult::none();
2076 return ExprResult::none();
2078 return ExprResult::some(
E);
2083template <
typename Map,
typename KeyType>
2084void NewGVN::touchAndErase(Map &M,
const KeyType &Key) {
2085 const auto Result =
M.find_as(Key);
2086 if (Result !=
M.end()) {
2087 for (
const typename Map::mapped_type::value_type Mapped :
Result->second)
2088 TouchedInstructions.
set(InstrToDFSNum(Mapped));
2095 if (isa<Instruction>(To))
2099void NewGVN::addAdditionalUsers(ExprResult &Res,
Instruction *
User)
const {
2100 if (Res.ExtraDep && Res.ExtraDep !=
User)
2101 addAdditionalUsers(Res.ExtraDep,
User);
2102 Res.ExtraDep =
nullptr;
2105 if (
const auto *PBranch = dyn_cast<PredicateBranch>(Res.PredDep))
2106 PredicateToUsers[PBranch->Condition].
insert(
User);
2107 else if (
const auto *PAssume = dyn_cast<PredicateAssume>(Res.PredDep))
2108 PredicateToUsers[PAssume->Condition].
insert(
User);
2110 Res.PredDep =
nullptr;
2113void NewGVN::markUsersTouched(
Value *V) {
2115 for (
auto *
User :
V->users()) {
2116 assert(isa<Instruction>(
User) &&
"Use of value not within an instruction?");
2117 TouchedInstructions.
set(InstrToDFSNum(
User));
2119 touchAndErase(AdditionalUsers, V);
2123 LLVM_DEBUG(
dbgs() <<
"Adding memory user " << *U <<
" to " << *To <<
"\n");
2124 MemoryToUsers[To].
insert(U);
2127void NewGVN::markMemoryDefTouched(
const MemoryAccess *MA) {
2128 TouchedInstructions.
set(MemoryToDFSNum(MA));
2131void NewGVN::markMemoryUsersTouched(
const MemoryAccess *MA) {
2132 if (isa<MemoryUse>(MA))
2134 for (
const auto *U : MA->
users())
2135 TouchedInstructions.
set(MemoryToDFSNum(U));
2136 touchAndErase(MemoryToUsers, MA);
2140void NewGVN::markPredicateUsersTouched(
Instruction *
I) {
2141 touchAndErase(PredicateToUsers,
I);
2145void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *
CC) {
2146 for (
const auto *M :
CC->memory())
2147 markMemoryDefTouched(M);
2152void NewGVN::markValueLeaderChangeTouched(CongruenceClass *
CC) {
2153 for (
auto *M : *
CC) {
2154 if (
auto *
I = dyn_cast<Instruction>(M))
2155 TouchedInstructions.
set(InstrToDFSNum(
I));
2162template <
class T,
class Range>
2163T *NewGVN::getMinDFSOfRange(
const Range &R)
const {
2164 std::pair<T *, unsigned> MinDFS = {
nullptr, ~0
U};
2165 for (
const auto X : R) {
2166 auto DFSNum = InstrToDFSNum(
X);
2167 if (DFSNum < MinDFS.second)
2168 MinDFS = {
X, DFSNum};
2170 return MinDFS.first;
2176const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *
CC)
const {
2180 assert(!
CC->definesNoMemory() &&
"Can't get next leader if there is none");
2181 if (
CC->getStoreCount() > 0) {
2182 if (
auto *NL = dyn_cast_or_null<StoreInst>(
CC->getNextLeader().first))
2183 return getMemoryAccess(NL);
2186 *
CC, [&](
const Value *V) {
return isa<StoreInst>(V); }));
2187 return getMemoryAccess(cast<StoreInst>(V));
2193 if (
CC->memory_size() == 1)
2194 return *
CC->memory_begin();
2195 return getMinDFSOfRange<const MemoryPhi>(
CC->memory());
2201Value *NewGVN::getNextValueLeader(CongruenceClass *
CC)
const {
2206 if (
CC->size() == 1 ||
CC == TOPClass) {
2207 return *(
CC->begin());
2208 }
else if (
CC->getNextLeader().first) {
2209 ++NumGVNAvoidedSortedLeaderChanges;
2210 return CC->getNextLeader().first;
2212 ++NumGVNSortedLeaderChanges;
2216 return getMinDFSOfRange<Value>(*
CC);
2229void NewGVN::moveMemoryToNewCongruenceClass(
Instruction *
I,
2231 CongruenceClass *OldClass,
2232 CongruenceClass *NewClass) {
2235 assert((!InstMA || !OldClass->getMemoryLeader() ||
2236 OldClass->getLeader() !=
I ||
2237 MemoryAccessToClass.
lookup(OldClass->getMemoryLeader()) ==
2238 MemoryAccessToClass.
lookup(InstMA)) &&
2239 "Representative MemoryAccess mismatch");
2241 if (!NewClass->getMemoryLeader()) {
2243 assert(NewClass->size() == 1 ||
2244 (isa<StoreInst>(
I) && NewClass->getStoreCount() == 1));
2245 NewClass->setMemoryLeader(InstMA);
2248 << NewClass->getID()
2249 <<
" due to new memory instruction becoming leader\n");
2250 markMemoryLeaderChangeTouched(NewClass);
2252 setMemoryClass(InstMA, NewClass);
2254 if (OldClass->getMemoryLeader() == InstMA) {
2255 if (!OldClass->definesNoMemory()) {
2256 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2258 << OldClass->getID() <<
" to "
2259 << *OldClass->getMemoryLeader()
2260 <<
" due to removal of old leader " << *InstMA <<
"\n");
2261 markMemoryLeaderChangeTouched(OldClass);
2263 OldClass->setMemoryLeader(
nullptr);
2270 CongruenceClass *OldClass,
2271 CongruenceClass *NewClass) {
2272 if (
I == OldClass->getNextLeader().first)
2273 OldClass->resetNextLeader();
2276 NewClass->insert(
I);
2280 if (NewClass->getLeader() !=
I &&
2281 NewClass->addPossibleLeader({I, InstrToDFSNum(I)})) {
2282 markValueLeaderChangeTouched(NewClass);
2286 if (
auto *SI = dyn_cast<StoreInst>(
I)) {
2287 OldClass->decStoreCount();
2295 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
2298 if (
auto *SE = dyn_cast<StoreExpression>(
E)) {
2299 NewClass->setStoredValue(SE->getStoredValue());
2300 markValueLeaderChangeTouched(NewClass);
2303 << NewClass->getID() <<
" from "
2304 << *NewClass->getLeader() <<
" to " << *SI
2305 <<
" because store joined class\n");
2308 NewClass->setLeader({
SI, InstrToDFSNum(SI)});
2312 NewClass->incStoreCount();
2318 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(
I));
2320 moveMemoryToNewCongruenceClass(
I, InstMA, OldClass, NewClass);
2321 ValueToClass[
I] = NewClass;
2323 if (OldClass->empty() && OldClass != TOPClass) {
2324 if (OldClass->getDefiningExpr()) {
2325 LLVM_DEBUG(
dbgs() <<
"Erasing expression " << *OldClass->getDefiningExpr()
2326 <<
" from table\n");
2329 auto Iter = ExpressionToClass.find_as(
2331 if (Iter != ExpressionToClass.end())
2332 ExpressionToClass.erase(Iter);
2333#ifdef EXPENSIVE_CHECKS
2335 (*OldClass->getDefiningExpr() != *
E || ExpressionToClass.lookup(
E)) &&
2336 "We erased the expression we just inserted, which should not happen");
2339 }
else if (OldClass->getLeader() ==
I) {
2344 << OldClass->getID() <<
"\n");
2345 ++NumGVNLeaderChanges;
2350 if (OldClass->getStoreCount() == 0) {
2351 if (OldClass->getStoredValue())
2352 OldClass->setStoredValue(
nullptr);
2354 OldClass->setLeader({getNextValueLeader(OldClass),
2355 InstrToDFSNum(getNextValueLeader(OldClass))});
2356 OldClass->resetNextLeader();
2357 markValueLeaderChangeTouched(OldClass);
2363void NewGVN::markPhiOfOpsChanged(
const Expression *
E) {
2364 touchAndErase(ExpressionToPhiOfOps,
E);
2372 CongruenceClass *IClass = ValueToClass.
lookup(
I);
2373 assert(IClass &&
"Should have found a IClass");
2375 assert(!IClass->isDead() &&
"Found a dead class");
2377 CongruenceClass *EClass =
nullptr;
2378 if (
const auto *VE = dyn_cast<VariableExpression>(
E)) {
2379 EClass = ValueToClass.
lookup(VE->getVariableValue());
2380 }
else if (isa<DeadExpression>(
E)) {
2384 auto lookupResult = ExpressionToClass.insert({
E,
nullptr});
2387 if (lookupResult.second) {
2388 CongruenceClass *NewClass = createCongruenceClass(
nullptr,
E);
2389 auto place = lookupResult.first;
2390 place->second = NewClass;
2393 if (
const auto *CE = dyn_cast<ConstantExpression>(
E)) {
2394 NewClass->setLeader({
CE->getConstantValue(), 0});
2395 }
else if (
const auto *SE = dyn_cast<StoreExpression>(
E)) {
2397 NewClass->setLeader({
SI, InstrToDFSNum(SI)});
2398 NewClass->setStoredValue(SE->getStoredValue());
2402 NewClass->setLeader({
I, InstrToDFSNum(
I)});
2404 assert(!isa<VariableExpression>(
E) &&
2405 "VariableExpression should have been handled already");
2409 <<
" using expression " << *
E <<
" at "
2410 << NewClass->getID() <<
" and leader "
2411 << *(NewClass->getLeader()));
2412 if (NewClass->getStoredValue())
2414 << *(NewClass->getStoredValue()));
2417 EClass = lookupResult.first->second;
2418 if (isa<ConstantExpression>(
E))
2419 assert((isa<Constant>(EClass->getLeader()) ||
2420 (EClass->getStoredValue() &&
2421 isa<Constant>(EClass->getStoredValue()))) &&
2422 "Any class with a constant expression should have a "
2425 assert(EClass &&
"Somehow don't have an eclass");
2427 assert(!EClass->isDead() &&
"We accidentally looked up a dead class");
2430 bool ClassChanged = IClass != EClass;
2431 bool LeaderChanged = LeaderChanges.
erase(
I);
2432 if (ClassChanged || LeaderChanged) {
2433 LLVM_DEBUG(
dbgs() <<
"New class " << EClass->getID() <<
" for expression "
2436 moveValueToNewCongruenceClass(
I,
E, IClass, EClass);
2437 markPhiOfOpsChanged(
E);
2440 markUsersTouched(
I);
2442 markMemoryUsersTouched(MA);
2443 if (
auto *CI = dyn_cast<CmpInst>(
I))
2444 markPredicateUsersTouched(CI);
2450 if (ClassChanged && isa<StoreInst>(
I)) {
2451 auto *OldE = ValueToExpression.
lookup(
I);
2454 if (OldE && isa<StoreExpression>(OldE) && *
E != *OldE) {
2458 if (Iter != ExpressionToClass.end())
2459 ExpressionToClass.erase(Iter);
2462 ValueToExpression[
I] =
E;
2469 if (ReachableEdges.
insert({From, To}).second) {
2471 if (ReachableBlocks.
insert(To).second) {
2473 <<
" marked reachable\n");
2474 const auto &InstRange = BlockInstRange.
lookup(To);
2475 TouchedInstructions.
set(InstRange.first, InstRange.second);
2478 <<
" was reachable, but new edge {"
2480 <<
"} to it found\n");
2487 TouchedInstructions.
set(InstrToDFSNum(MemPhi));
2492 for (
auto InstNum : RevisitOnReachabilityChange[To])
2493 TouchedInstructions.
set(InstNum);
2502 return isa<Constant>(Result) ?
Result :
nullptr;
2511 Value *CondEvaluated = findConditionEquivalence(
Cond);
2512 if (!CondEvaluated) {
2513 if (
auto *
I = dyn_cast<Instruction>(
Cond)) {
2515 auto Res = performSymbolicEvaluation(
I, Visited);
2516 if (
const auto *CE = dyn_cast_or_null<ConstantExpression>(Res.Expr)) {
2517 CondEvaluated =
CE->getConstantValue();
2518 addAdditionalUsers(Res,
I);
2522 Res.ExtraDep =
nullptr;
2524 }
else if (isa<ConstantInt>(
Cond)) {
2525 CondEvaluated =
Cond;
2529 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2532 <<
" evaluated to true\n");
2533 updateReachableEdge(
B, TrueSucc);
2534 }
else if (CI->
isZero()) {
2536 <<
" evaluated to false\n");
2537 updateReachableEdge(
B, FalseSucc);
2540 updateReachableEdge(
B, TrueSucc);
2541 updateReachableEdge(
B, FalseSucc);
2543 }
else if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
2547 Value *SwitchCond =
SI->getCondition();
2548 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
2550 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
2551 auto *CondVal = cast<ConstantInt>(CondEvaluated);
2553 auto Case = *
SI->findCaseValue(CondVal);
2554 if (Case.getCaseSuccessor() ==
SI->getDefaultDest()) {
2558 updateReachableEdge(
B,
SI->getDefaultDest());
2562 BasicBlock *TargetBlock = Case.getCaseSuccessor();
2563 updateReachableEdge(
B, TargetBlock);
2566 updateReachableEdge(
B, TargetBlock);
2572 updateReachableEdge(
B, TargetBlock);
2577 auto *MA = getMemoryAccess(TI);
2578 if (MA && !isa<MemoryUse>(MA)) {
2579 auto *
CC = ensureLeaderOfMemoryClass(MA);
2580 if (setMemoryClass(MA,
CC))
2581 markMemoryUsersTouched(MA);
2588 InstrDFS.
erase(PHITemp);
2591 TempToBlock.
erase(PHITemp);
2602 InstrDFS[
Op] = InstrToDFSNum(ExistingValue);
2604 TempToBlock[
Op] = BB;
2605 RealToTemp[ExistingValue] =
Op;
2608 for (
auto *U : ExistingValue->
users())
2609 if (
auto *UI = dyn_cast<Instruction>(U))
2616 return isa<BinaryOperator>(
I) || isa<SelectInst>(
I) || isa<CmpInst>(
I) ||
2631 while (!Worklist.
empty()) {
2633 if (!isa<Instruction>(
I))
2636 auto OISIt = OpSafeForPHIOfOps.
find({
I, CacheIdx});
2637 if (OISIt != OpSafeForPHIOfOps.
end())
2638 return OISIt->second;
2643 OpSafeForPHIOfOps.
insert({{
I, CacheIdx},
true});
2647 if (isa<PHINode>(
I) && getBlockForValue(
I) == PHIBlock) {
2648 OpSafeForPHIOfOps.
insert({{
I, CacheIdx},
false});
2652 auto *OrigI = cast<Instruction>(
I);
2659 if (OrigI->mayReadFromMemory())
2663 for (
auto *
Op : OrigI->operand_values()) {
2664 if (!isa<Instruction>(
Op))
2667 auto OISIt = OpSafeForPHIOfOps.
find({OrigI, CacheIdx});
2668 if (OISIt != OpSafeForPHIOfOps.
end()) {
2669 if (!OISIt->second) {
2670 OpSafeForPHIOfOps.
insert({{
I, CacheIdx},
false});
2680 OpSafeForPHIOfOps.
insert({{
V, CacheIdx},
true});
2693 unsigned IDFSNum = InstrToDFSNum(OrigInst);
2695 AllTempInstructions.
insert(TransInst);
2699 TempToBlock.
insert({TransInst, PredBB});
2700 InstrDFS.
insert({TransInst, IDFSNum});
2702 auto Res = performSymbolicEvaluation(TransInst, Visited);
2704 addAdditionalUsers(Res, OrigInst);
2705 InstrDFS.
erase(TransInst);
2706 AllTempInstructions.
erase(TransInst);
2707 TempToBlock.
erase(TransInst);
2709 TempToMemory.
erase(TransInst);
2712 auto *FoundVal = findPHIOfOpsLeader(
E, OrigInst, PredBB);
2714 ExpressionToPhiOfOps[
E].
insert(OrigInst);
2715 LLVM_DEBUG(
dbgs() <<
"Cannot find phi of ops operand for " << *TransInst
2719 if (
auto *SI = dyn_cast<StoreInst>(FoundVal))
2720 FoundVal =
SI->getValueOperand();
2732 if (!Visited.
insert(
I).second)
2738 if (!isCycleFree(
I))
2745 auto *MemAccess = getMemoryAccess(
I);
2749 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2750 MemAccess->getDefiningAccess()->
getBlock() ==
I->getParent())
2760 for (
auto *
Op : Ops) {
2761 if (!isa<PHINode>(
Op)) {
2762 auto *ValuePHI = RealToTemp.
lookup(
Op);
2768 OpPHI = cast<PHINode>(
Op);
2769 if (!SamePHIBlock) {
2770 SamePHIBlock = getBlockForValue(OpPHI);
2771 }
else if (SamePHIBlock != getBlockForValue(OpPHI)) {
2774 <<
"PHIs for operands are not all in the same block, aborting\n");
2789 auto *PHIBlock = getBlockForValue(OpPHI);
2790 RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(
I));
2791 for (
unsigned PredNum = 0; PredNum < OpPHI->
getNumOperands(); ++PredNum) {
2793 Value *FoundVal =
nullptr;
2797 if (ReachableEdges.
count({PredBB, PHIBlock})) {
2805 TempToMemory.
insert({ValueOp, MemAccess});
2806 bool SafeForPHIOfOps =
true;
2809 auto *OrigOp = &*
Op;
2812 if (isa<PHINode>(
Op)) {
2813 Op =
Op->DoPHITranslation(PHIBlock, PredBB);
2814 if (
Op != OrigOp &&
Op !=
I)
2816 }
else if (
auto *ValuePHI = RealToTemp.
lookup(
Op)) {
2817 if (getBlockForValue(ValuePHI) == PHIBlock)
2818 Op = ValuePHI->getIncomingValueForBlock(PredBB);
2823 (
Op != OrigOp || OpIsSafeForPHIOfOps(
Op, PHIBlock, VisitedOps));
2830 FoundVal = !SafeForPHIOfOps ? nullptr
2831 : findLeaderForInst(ValueOp, Visited,
2832 MemAccess,
I, PredBB);
2837 if (SafeForPHIOfOps)
2838 for (
auto *Dep : CurrentDeps)
2839 addAdditionalUsers(Dep,
I);
2845 LLVM_DEBUG(
dbgs() <<
"Skipping phi of ops operand for incoming block "
2847 <<
" because the block is unreachable\n");
2849 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(
I));
2853 LLVM_DEBUG(
dbgs() <<
"Found phi of ops operand " << *FoundVal <<
" in "
2856 for (
auto *Dep : Deps)
2857 addAdditionalUsers(Dep,
I);
2859 auto *
E = performSymbolicPHIEvaluation(PHIOps,
I, PHIBlock);
2860 if (isa<ConstantExpression>(
E) || isa<VariableExpression>(
E)) {
2863 <<
"Not creating real PHI of ops because it simplified to existing "
2864 "value or constant\n");
2870 for (
auto &O : PHIOps)
2871 addAdditionalUsers(
O.first,
I);
2875 auto *ValuePHI = RealToTemp.
lookup(
I);
2876 bool NewPHI =
false;
2880 addPhiOfOps(ValuePHI, PHIBlock,
I);
2882 NumGVNPHIOfOpsCreated++;
2885 for (
auto PHIOp : PHIOps)
2886 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2888 TempToBlock[ValuePHI] = PHIBlock;
2890 for (
auto PHIOp : PHIOps) {
2891 ValuePHI->setIncomingValue(i, PHIOp.first);
2892 ValuePHI->setIncomingBlock(i, PHIOp.second);
2896 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(
I));
2897 LLVM_DEBUG(
dbgs() <<
"Created phi of ops " << *ValuePHI <<
" for " << *
I
2906void NewGVN::initializeCongruenceClasses(
Function &
F) {
2907 NextCongruenceNum = 0;
2917 TOPClass = createCongruenceClass(
nullptr,
nullptr);
2923 for (
auto *DTN :
nodes(DT)) {
2930 if (MemoryBlockDefs)
2931 for (
const auto &Def : *MemoryBlockDefs) {
2932 MemoryAccessToClass[&
Def] = TOPClass;
2933 auto *MD = dyn_cast<MemoryDef>(&Def);
2936 const MemoryPhi *MP = cast<MemoryPhi>(&Def);
2937 TOPClass->memory_insert(MP);
2938 MemoryPhiState.
insert({MP, MPS_TOP});
2941 if (MD && isa<StoreInst>(MD->getMemoryInst()))
2942 TOPClass->incStoreCount();
2948 for (
auto &
I : *BB) {
2949 if (isa<PHINode>(&
I))
2950 for (
auto *U :
I.users())
2951 if (
auto *UInst = dyn_cast<Instruction>(U))
2953 PHINodeUses.
insert(UInst);
2956 if (
I.isTerminator() &&
I.getType()->isVoidTy())
2958 TOPClass->insert(&
I);
2959 ValueToClass[&
I] = TOPClass;
2964 for (
auto &FA :
F.args())
2965 createSingletonCongruenceClass(&FA);
2968void NewGVN::cleanupTables() {
2969 for (CongruenceClass *&
CC : CongruenceClasses) {
2971 <<
CC->size() <<
" members\n");
2980 AllTempInstructions.
end());
2981 AllTempInstructions.
clear();
2985 for (
auto *
I : TempInst) {
2986 I->dropAllReferences();
2989 while (!TempInst.empty()) {
2990 auto *
I = TempInst.pop_back_val();
2994 ValueToClass.
clear();
2995 ArgRecycler.
clear(ExpressionAllocator);
2996 ExpressionAllocator.
Reset();
2997 CongruenceClasses.clear();
2998 ExpressionToClass.clear();
2999 ValueToExpression.
clear();
3001 AdditionalUsers.
clear();
3002 ExpressionToPhiOfOps.
clear();
3003 TempToBlock.
clear();
3004 TempToMemory.
clear();
3005 PHINodeUses.
clear();
3006 OpSafeForPHIOfOps.
clear();
3007 ReachableBlocks.
clear();
3008 ReachableEdges.
clear();
3010 ProcessedCount.
clear();
3013 InstructionsToErase.
clear();
3015 BlockInstRange.
clear();
3016 TouchedInstructions.
clear();
3017 MemoryAccessToClass.
clear();
3018 PredicateToUsers.
clear();
3019 MemoryToUsers.
clear();
3020 RevisitOnReachabilityChange.
clear();
3021 IntrinsicInstPred.
clear();
3026std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(
BasicBlock *
B,
3028 unsigned End = Start;
3030 InstrDFS[MemPhi] =
End++;
3035 for (
auto &
I : *
B) {
3041 LLVM_DEBUG(
dbgs() <<
"Skipping trivially dead instruction " <<
I <<
"\n");
3042 markInstructionForDeletion(&
I);
3045 if (isa<PHINode>(&
I))
3046 RevisitOnReachabilityChange[
B].set(
End);
3047 InstrDFS[&
I] =
End++;
3054 return std::make_pair(Start,
End);
3057void NewGVN::updateProcessedCount(
const Value *V) {
3059 if (ProcessedCount.
count(V) == 0) {
3060 ProcessedCount.
insert({
V, 1});
3062 ++ProcessedCount[
V];
3063 assert(ProcessedCount[V] < 100 &&
3064 "Seem to have processed the same Value a lot");
3070void NewGVN::valueNumberMemoryPhi(
MemoryPhi *MP) {
3077 return cast<MemoryAccess>(U) != MP &&
3078 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
3079 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
3084 if (Filtered.begin() == Filtered.end()) {
3085 if (setMemoryClass(MP, TOPClass))
3086 markMemoryUsersTouched(MP);
3092 auto LookupFunc = [&](
const Use &
U) {
3093 return lookupMemoryLeader(cast<MemoryAccess>(U));
3095 auto MappedBegin =
map_iterator(Filtered.begin(), LookupFunc);
3096 auto MappedEnd =
map_iterator(Filtered.end(), LookupFunc);
3100 const auto *AllSameValue = *MappedBegin;
3102 bool AllEqual = std::all_of(
3103 MappedBegin, MappedEnd,
3104 [&AllSameValue](
const MemoryAccess *V) {
return V == AllSameValue; });
3107 LLVM_DEBUG(
dbgs() <<
"Memory Phi value numbered to " << *AllSameValue
3116 CongruenceClass *
CC =
3117 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
3118 auto OldState = MemoryPhiState.
lookup(MP);
3119 assert(OldState != MPS_Invalid &&
"Invalid memory phi state");
3120 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
3121 MemoryPhiState[MP] = NewState;
3122 if (setMemoryClass(MP,
CC) || OldState != NewState)
3123 markMemoryUsersTouched(MP);
3130 if (!
I->isTerminator()) {
3134 auto Res = performSymbolicEvaluation(
I, Visited);
3135 Symbolized = Res.Expr;
3136 addAdditionalUsers(Res,
I);
3139 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
3140 !isa<VariableExpression>(Symbolized) && PHINodeUses.
count(
I)) {
3141 auto *PHIE = makePossiblePHIOfOps(
I, Visited);
3146 }
else if (
auto *
Op = RealToTemp.
lookup(
I)) {
3147 removePhiOfOps(
I,
Op);
3156 if (Symbolized ==
nullptr)
3157 Symbolized = createUnknownExpression(
I);
3158 performCongruenceFinding(
I, Symbolized);
3163 if (!
I->getType()->isVoidTy()) {
3164 auto *Symbolized = createUnknownExpression(
I);
3165 performCongruenceFinding(
I, Symbolized);
3167 processOutgoingEdges(
I,
I->getParent());
3173bool NewGVN::singleReachablePHIPath(
3176 if (
First == Second)
3189 const auto *EndDef =
First;
3191 if (ChainDef == Second)
3197 auto *MP = cast<MemoryPhi>(EndDef);
3198 auto ReachableOperandPred = [&](
const Use &
U) {
3201 auto FilteredPhiArgs =
3204 llvm::copy(FilteredPhiArgs, std::back_inserter(OperandList));
3207 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
3216void NewGVN::verifyMemoryCongruency()
const {
3219 for (
const auto *
CC : CongruenceClasses) {
3220 if (
CC == TOPClass ||
CC->isDead())
3222 if (
CC->getStoreCount() != 0) {
3223 assert((
CC->getStoredValue() || !isa<StoreInst>(
CC->getLeader())) &&
3224 "Any class with a store as a leader should have a "
3225 "representative stored value");
3227 "Any congruence class with a store should have a "
3228 "representative access");
3231 if (
CC->getMemoryLeader())
3233 "Representative MemoryAccess does not appear to be reverse "
3235 for (
const auto *M :
CC->memory())
3237 "Memory member does not appear to be reverse mapped properly");
3245 auto ReachableAccessPred =
3246 [&](
const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
3247 bool Result = ReachableBlocks.
count(Pair.first->getBlock());
3249 MemoryToDFSNum(Pair.first) == 0)
3251 if (
auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3256 if (
auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3257 for (
const auto &U : MemPHI->incoming_values()) {
3258 if (
auto *
I = dyn_cast<Instruction>(&*U)) {
3270 for (
auto KV : Filtered) {
3271 if (
auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
3272 auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
3273 if (FirstMUD && SecondMUD) {
3275 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
3276 ValueToClass.
lookup(FirstMUD->getMemoryInst()) ==
3277 ValueToClass.
lookup(SecondMUD->getMemoryInst())) &&
3278 "The instructions for these memory operations should have "
3279 "been in the same congruence class or reachable through"
3280 "a single argument phi");
3282 }
else if (
auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
3285 auto ReachableOperandPred = [&](
const Use &
U) {
3286 return ReachableEdges.
count(
3287 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
3291 auto FilteredPhiArgs =
3294 std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
3295 std::back_inserter(PhiOpClasses), [&](
const Use &U) {
3296 const MemoryDef *MD = cast<MemoryDef>(U);
3297 return ValueToClass.lookup(MD->getMemoryInst());
3300 "All MemoryPhi arguments should be in the same class");
3309void NewGVN::verifyIterationSettled(
Function &
F) {
3319 std::map<const Value *, CongruenceClass> BeforeIteration;
3321 for (
auto &KV : ValueToClass) {
3322 if (
auto *
I = dyn_cast<Instruction>(KV.first))
3324 if (InstrToDFSNum(
I) == 0)
3326 BeforeIteration.insert({KV.first, *KV.second});
3329 TouchedInstructions.
set();
3330 TouchedInstructions.
reset(0);
3331 OpSafeForPHIOfOps.
clear();
3333 iterateTouchedInstructions();
3336 for (
const auto &KV : ValueToClass) {
3337 if (
auto *
I = dyn_cast<Instruction>(KV.first))
3339 if (InstrToDFSNum(
I) == 0)
3343 auto *BeforeCC = &BeforeIteration.
find(KV.first)->second;
3344 auto *AfterCC = KV.second;
3347 if (!EqualClasses.
count({BeforeCC, AfterCC})) {
3348 assert(BeforeCC->isEquivalentTo(AfterCC) &&
3349 "Value number changed after main loop completed!");
3350 EqualClasses.
insert({BeforeCC, AfterCC});
3361void NewGVN::verifyStoreExpressions()
const {
3366 std::pair<
const Value *,
3367 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3369 for (
const auto &KV : ExpressionToClass) {
3370 if (
auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3372 auto Res = StoreExpressionSet.insert(
3373 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3374 SE->getStoredValue())});
3375 bool Okay = Res.second;
3380 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3381 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3382 lookupOperandLeader(SE->getStoredValue()));
3383 assert(Okay &&
"Stored expression conflict exists in expression table");
3384 auto *ValueExpr = ValueToExpression.
lookup(SE->getStoreInst());
3385 assert(ValueExpr && ValueExpr->equals(*SE) &&
3386 "StoreExpression in ExpressionToClass is not latest "
3387 "StoreExpression for value");
3396void NewGVN::iterateTouchedInstructions() {
3399 int FirstInstr = TouchedInstructions.
find_first();
3401 if (FirstInstr == -1)
3403 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
3404 while (TouchedInstructions.
any()) {
3410 for (
unsigned InstrNum : TouchedInstructions.
set_bits()) {
3414 if (InstrNum == 0) {
3415 TouchedInstructions.
reset(InstrNum);
3419 Value *
V = InstrFromDFSNum(InstrNum);
3420 const BasicBlock *CurrBlock = getBlockForValue(V);
3423 if (CurrBlock != LastBlock) {
3424 LastBlock = CurrBlock;
3425 bool BlockReachable = ReachableBlocks.
count(CurrBlock);
3426 const auto &CurrInstRange = BlockInstRange.
lookup(CurrBlock);
3429 if (!BlockReachable) {
3430 TouchedInstructions.
reset(CurrInstRange.first, CurrInstRange.second);
3433 <<
" because it is unreachable\n");
3438 updateProcessedCount(CurrBlock);
3442 TouchedInstructions.
reset(InstrNum);
3444 if (
auto *MP = dyn_cast<MemoryPhi>(V)) {
3446 valueNumberMemoryPhi(MP);
3447 }
else if (
auto *
I = dyn_cast<Instruction>(V)) {
3448 valueNumberInstruction(
I);
3452 updateProcessedCount(V);
3455 NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
3459bool NewGVN::runGVN() {
3462 bool Changed =
false;
3463 NumFuncArgs =
F.arg_size();
3465 SingletonDeadExpression =
new (ExpressionAllocator)
DeadExpression();
3469 unsigned ICount = 1;
3481 unsigned Counter = 0;
3482 for (
auto &
B : RPOT) {
3484 assert(
Node &&
"RPO and Dominator tree should have same reachability");
3485 RPOOrdering[
Node] = ++Counter;
3488 for (
auto &
B : RPOT) {
3490 if (
Node->getNumChildren() > 1)
3492 return RPOOrdering[
A] < RPOOrdering[
B];
3499 const auto &BlockRange = assignDFSNumbers(
B, ICount);
3500 BlockInstRange.
insert({
B, BlockRange});
3501 ICount += BlockRange.second - BlockRange.first;
3503 initializeCongruenceClasses(
F);
3505 TouchedInstructions.
resize(ICount);
3509 ExpressionToClass.reserve(ICount);
3512 const auto &InstRange = BlockInstRange.
lookup(&
F.getEntryBlock());
3513 TouchedInstructions.
set(InstRange.first, InstRange.second);
3515 <<
" marked reachable\n");
3516 ReachableBlocks.
insert(&
F.getEntryBlock());
3520 iterateTouchedInstructions();
3521 verifyMemoryCongruency();
3522 verifyIterationSettled(
F);
3523 verifyStoreExpressions();
3525 Changed |= eliminateInstructions(
F);
3528 for (
Instruction *ToErase : InstructionsToErase) {
3529 if (!ToErase->use_empty())
3532 assert(ToErase->getParent() &&
3533 "BB containing ToErase deleted unexpectedly!");
3534 ToErase->eraseFromParent();
3536 Changed |= !InstructionsToErase.empty();
3539 auto UnreachableBlockPred = [&](
const BasicBlock &BB) {
3540 return !ReachableBlocks.
count(&BB);
3545 <<
" is unreachable\n");
3546 deleteInstructionsInBlock(&BB);
3604 return std::tie(DFSIn, DFSOut,
LocalNum, Def, U) <
3615void NewGVN::convertClassToDFSOrdered(
3624 assert(BB &&
"Should have figured out a basic block for value");
3632 if (
auto *SI = dyn_cast<StoreInst>(
D)) {
3633 auto Leader = lookupOperandLeader(SI->getValueOperand());
3635 VDDef.
Def.setPointer(Leader);
3637 VDDef.
Def.setPointer(
SI->getValueOperand());
3638 VDDef.
Def.setInt(
true);
3641 VDDef.
Def.setPointer(
D);
3644 "The dense set member should always be an instruction");
3649 if (
auto *PN = RealToTemp.
lookup(Def)) {
3651 dyn_cast_or_null<PHIExpression>(ValueToExpression.
lookup(Def));
3653 VDDef.
Def.setInt(
false);
3654 VDDef.
Def.setPointer(PN);
3660 unsigned int UseCount = 0;
3662 for (
auto &U :
Def->uses()) {
3663 if (
auto *
I = dyn_cast<Instruction>(
U.getUser())) {
3665 if (InstructionsToErase.count(
I))
3670 if (
auto *
P = dyn_cast<PHINode>(
I)) {
3671 IBlock =
P->getIncomingBlock(U);
3676 IBlock = getBlockForValue(
I);
3682 if (!ReachableBlocks.
contains(IBlock))
3698 ProbablyDead.
insert(Def);
3700 UseCounts[
Def] = UseCount;
3706void NewGVN::convertClassToLoadsAndStores(
3707 const CongruenceClass &
Dense,
3710 if (!isa<LoadInst>(
D) && !isa<StoreInst>(
D))
3718 VD.
Def.setPointer(
D);
3721 if (
auto *
I = dyn_cast<Instruction>(
D))
3732 I->replaceAllUsesWith(Repl);
3735void NewGVN::deleteInstructionsInBlock(
BasicBlock *BB) {
3737 ++NumGVNBlocksDeleted;
3741 auto StartPoint = BB->
rbegin();
3749 if (isa<LandingPadInst>(Inst))
3754 ++NumGVNInstrDeleted;
3764void NewGVN::markInstructionForDeletion(
Instruction *
I) {
3766 InstructionsToErase.insert(
I);
3774 markInstructionForDeletion(
I);
3781class ValueDFSStack {
3783 Value *back()
const {
return ValueStack.back(); }
3784 std::pair<int, int> dfs_back()
const {
return DFSStack.back(); }
3786 void push_back(
Value *V,
int DFSIn,
int DFSOut) {
3787 ValueStack.emplace_back(V);
3788 DFSStack.emplace_back(DFSIn, DFSOut);
3791 bool empty()
const {
return DFSStack.empty(); }
3793 bool isInScope(
int DFSIn,
int DFSOut)
const {
3796 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3799 void popUntilDFSScope(
int DFSIn,
int DFSOut) {
3802 assert(ValueStack.size() == DFSStack.size() &&
3803 "Mismatch between ValueStack and DFSStack");
3805 !DFSStack.empty() &&
3806 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3807 DFSStack.pop_back();
3808 ValueStack.pop_back();
3820CongruenceClass *NewGVN::getClassForExpression(
const Expression *E)
const {
3821 if (
auto *VE = dyn_cast<VariableExpression>(E))
3822 return ValueToClass.lookup(VE->getVariableValue());
3823 else if (isa<DeadExpression>(E))
3825 return ExpressionToClass.lookup(E);
3834 if (
auto *CE = dyn_cast<ConstantExpression>(E))
3835 return CE->getConstantValue();
3836 if (
auto *VE = dyn_cast<VariableExpression>(E)) {
3837 auto *
V = VE->getVariableValue();
3839 return VE->getVariableValue();
3842 auto *
CC = getClassForExpression(E);
3846 return CC->getLeader();
3848 for (
auto *Member : *
CC) {
3849 auto *MemberInst = dyn_cast<Instruction>(Member);
3850 if (MemberInst == OrigInst)
3855 if (DT->
dominates(getBlockForValue(MemberInst), BB))
3861bool NewGVN::eliminateInstructions(
Function &
F) {
3885 bool AnythingReplaced =
false;
3894 for (
auto &Operand :
PHI->incoming_values())
3895 if (!ReachableEdges.
count({PHI->getIncomingBlock(Operand), BB})) {
3899 <<
" with poison due to it being unreachable\n");
3913 for (
auto &KV : ReachableEdges)
3914 ReachablePredCount[KV.getEnd()]++;
3915 for (
auto &BBPair : RevisitOnReachabilityChange) {
3916 for (
auto InstNum : BBPair.second) {
3917 auto *Inst = InstrFromDFSNum(InstNum);
3918 auto *
PHI = dyn_cast<PHINode>(Inst);
3922 auto *BB = BBPair.first;
3923 if (ReachablePredCount.
lookup(BB) !=
PHI->getNumIncomingValues())
3924 ReplaceUnreachablePHIArgs(
PHI, BB);
3930 for (
auto *
CC :
reverse(CongruenceClasses)) {
3937 if (
CC->isDead() ||
CC->empty())
3940 if (
CC == TOPClass) {
3941 for (
auto *M : *
CC) {
3942 auto *VTE = ValueToExpression.
lookup(M);
3943 if (VTE && isa<DeadExpression>(VTE))
3944 markInstructionForDeletion(cast<Instruction>(M));
3945 assert((!ReachableBlocks.
count(cast<Instruction>(M)->getParent()) ||
3946 InstructionsToErase.count(cast<Instruction>(M))) &&
3947 "Everything in TOP should be unreachable or dead at this "
3953 assert(
CC->getLeader() &&
"We should have had a leader");
3959 CC->getStoredValue() ?
CC->getStoredValue() :
CC->getLeader();
3962 for (
auto *M : *
CC) {
3965 if (Member == Leader || !isa<Instruction>(Member) ||
3966 Member->getType()->isVoidTy()) {
3967 MembersLeft.
insert(Member);
3971 LLVM_DEBUG(
dbgs() <<
"Found replacement " << *(Leader) <<
" for "
3972 << *Member <<
"\n");
3973 auto *
I = cast<Instruction>(Member);
3974 assert(Leader !=
I &&
"About to accidentally remove our leader");
3975 replaceInstruction(
I, Leader);
3976 AnythingReplaced =
true;
3978 CC->swap(MembersLeft);
3981 if (
CC->size() != 1 || RealToTemp.
count(Leader)) {
3986 ValueDFSStack EliminationStack;
3990 convertClassToDFSOrdered(*
CC, DFSOrderedSet, UseCounts, ProbablyDead);
3994 for (
auto &VD : DFSOrderedSet) {
3995 int MemberDFSIn = VD.
DFSIn;
3996 int MemberDFSOut = VD.
DFSOut;
3998 bool FromStore = VD.
Def.getInt();
4001 if (Def &&
Def->getType()->isVoidTy())
4003 auto *DefInst = dyn_cast_or_null<Instruction>(Def);
4004 if (DefInst && AllTempInstructions.
count(DefInst)) {
4005 auto *PN = cast<PHINode>(DefInst);
4010 AllTempInstructions.
erase(PN);
4011 auto *DefBlock = getBlockForValue(Def);
4015 PN->insertBefore(&DefBlock->front());
4017 NumGVNPHIOfOpsEliminations++;
4020 if (EliminationStack.empty()) {
4024 << EliminationStack.dfs_back().first <<
","
4025 << EliminationStack.dfs_back().second <<
")\n");
4028 LLVM_DEBUG(
dbgs() <<
"Current DFS numbers are (" << MemberDFSIn <<
","
4029 << MemberDFSOut <<
")\n");
4043 bool ShouldPush =
Def && EliminationStack.empty();
4045 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
4047 if (OutOfScope || ShouldPush) {
4049 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
4050 bool ShouldPush =
Def && EliminationStack.empty();
4052 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
4071 auto *DefI = dyn_cast<Instruction>(Def);
4072 if (!EliminationStack.empty() && DefI && !FromStore) {
4073 Value *DominatingLeader = EliminationStack.back();
4074 if (DominatingLeader != Def) {
4077 if (!
match(DefI, m_Intrinsic<Intrinsic::ssa_copy>()))
4080 markInstructionForDeletion(DefI);
4088 assert(isa<Instruction>(
U->get()) &&
4089 "Current def should have been an instruction");
4090 assert(isa<Instruction>(
U->getUser()) &&
4091 "Current user should have been an instruction");
4097 Instruction *InstUse = cast<Instruction>(
U->getUser());
4098 if (InstructionsToErase.count(InstUse)) {
4099 auto &UseCount = UseCounts[
U->get()];
4100 if (--UseCount == 0) {
4101 ProbablyDead.
insert(cast<Instruction>(
U->get()));
4107 if (EliminationStack.empty())
4110 Value *DominatingLeader = EliminationStack.back();
4112 auto *
II = dyn_cast<IntrinsicInst>(DominatingLeader);
4113 bool isSSACopy =
II &&
II->getIntrinsicID() == Intrinsic::ssa_copy;
4115 DominatingLeader =
II->getOperand(0);
4118 if (
U->get() == DominatingLeader)
4124 auto *ReplacedInst = cast<Instruction>(
U->get());
4125 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
4126 if (!PI || DominatingLeader != PI->OriginalOp)
4130 <<
"Found replacement " << *DominatingLeader <<
" for "
4131 << *
U->get() <<
" in " << *(
U->getUser()) <<
"\n");
4132 U->set(DominatingLeader);
4135 auto &LeaderUseCount = UseCounts[DominatingLeader];
4137 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
4138 ProbablyDead.
erase(cast<Instruction>(DominatingLeader));
4142 auto It = UseCounts.
find(
II);
4143 if (It != UseCounts.
end()) {
4144 unsigned &IIUseCount = It->second;
4145 if (--IIUseCount == 0)
4150 AnythingReplaced =
true;
4157 for (
auto *
I : ProbablyDead)
4159 markInstructionForDeletion(
I);
4163 for (
auto *Member : *
CC)
4164 if (!isa<Instruction>(Member) ||
4165 !InstructionsToErase.count(cast<Instruction>(Member)))
4166 MembersLeft.
insert(Member);
4167 CC->swap(MembersLeft);
4170 if (
CC->getStoreCount() > 0) {
4171 convertClassToLoadsAndStores(*
CC, PossibleDeadStores);
4173 ValueDFSStack EliminationStack;
4174 for (
auto &VD : PossibleDeadStores) {
4175 int MemberDFSIn = VD.
DFSIn;
4176 int MemberDFSOut = VD.
DFSOut;
4178 if (EliminationStack.empty() ||
4179 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
4181 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
4182 if (EliminationStack.empty()) {
4183 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
4188 if (isa<LoadInst>(Member))
4190 assert(!EliminationStack.empty());
4191 Instruction *Leader = cast<Instruction>(EliminationStack.back());
4196 <<
" that is dominated by " << *Leader <<
"\n");
4197 markInstructionForDeletion(Member);
4203 return AnythingReplaced;
4211unsigned int NewGVN::getRank(
const Value *V)
const {
4217 if (isa<ConstantExpr>(V))
4219 if (isa<PoisonValue>(V))
4221 if (isa<UndefValue>(V))
4223 if (isa<Constant>(V))
4225 if (
auto *
A = dyn_cast<Argument>(V))
4226 return 4 +
A->getArgNo();
4230 unsigned Result = InstrToDFSNum(V);
4232 return 5 + NumFuncArgs +
Result;
4239bool NewGVN::shouldSwapOperands(
const Value *
A,
const Value *
B)
const {
4243 return std::make_pair(getRank(
A),
A) > std::make_pair(getRank(
B),
B);
4246bool NewGVN::shouldSwapOperandsForIntrinsic(
const Value *
A,
const Value *
B,
4249 if (shouldSwapOperands(
A,
B)) {
4250 if (LookupResult == IntrinsicInstPred.
end())
4257 if (LookupResult != IntrinsicInstPred.
end()) {
4259 if (SeenPredicate) {
4260 if (SeenPredicate ==
B)
4279 NewGVN(
F, &DT, &AC, &TLI, &AA, &MSSA,
F.getDataLayout())
Unify divergent function exit nodes
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file defines the BumpPtrAllocator interface.
This file implements the BitVector class.
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file provides an implementation of debug counters.
#define DEBUG_COUNTER(VARNAME, COUNTERNAME, DESC)
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
std::optional< std::vector< StOtherPiece > > Other
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
The header file for the GVN pass that contains expression handling classes.
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
This is the interface for a simple mod/ref and alias analysis over globals.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
This defines the Use class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static bool alwaysAvailable(Value *V)
static Value * getCopyOf(const Value *V)
static bool isCopyOfPHI(const Value *V, const PHINode *PN)
static bool isCopyOfAPHI(const Value *V)
static bool okayForPHIOfOps(const Instruction *I)
static cl::opt< bool > EnableStoreRefinement("enable-store-refinement", cl::init(false), cl::Hidden)
static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS)
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.
This file provides the interface for LLVM's Global Value Numbering pass.
This file defines the PointerIntPair class.
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isDead(const MachineInstr &MI, const MachineRegisterInfo &MRI)
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
A manager for alias analyses.
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are must-alias.
bool doesNotAccessMemory(const CallBase *Call)
Checks if the specified call is known to never read or write memory.
bool onlyReadsMemory(const CallBase *Call)
Checks if the specified call is known to only read from non-volatile memory (or not access memory at ...
A container for analyses that lazily runs them and caches their results.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Recycle small arrays allocated from a BumpPtrAllocator.
void clear(AllocatorType &Allocator)
Release all the tracked allocations to the allocator.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
std::optional< AttributeList > intersectWith(LLVMContext &C, AttributeList Other) const
Try to intersect this AttributeList with Other.
LLVM Basic Block Representation.
reverse_iterator rbegin()
InstListType::reverse_iterator reverse_iterator
LLVMContext & getContext() const
Get the context in which this basic block lives.
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...
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
void clear()
clear - Removes all bits from the bitvector.
bool any() const
any - Returns true if any bit is set.
iterator_range< const_set_bits_iterator > set_bits() const
Allocate memory in an ever growing pool, as if by bump-pointer.
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
void Deallocate(const void *Ptr, size_t Size, size_t)
bool isConvergent() const
Determine if the invoke is convergent.
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
This is the shared class of boolean and integer constants.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
static ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
static ConstantInt * getFalse(LLVMContext &Context)
static ConstantInt * getBool(LLVMContext &Context, bool V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
static CounterState getCounterState(unsigned ID)
static bool isCounterSet(unsigned ID)
static bool shouldExecute(unsigned CounterName)
static void setCounterState(unsigned ID, CounterState State)
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...
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree.
unsigned getDFSNumOut() const
Analysis pass which computes a DominatorTree.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void updateDFSNumbers() const
updateDFSNumbers - Assign In and Out numbers to the nodes while walking dominator tree in dfs order.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Class representing an expression and its matching format.
bool isPresplitCoroutine() const
Determine if the function is presplit coroutine.
~AggregateValueExpression() override
~BasicExpression() override
bool equals(const Expression &Other) const override
~CallExpression() override
bool equals(const Expression &Other) const override
~LoadExpression() override
bool equals(const Expression &Other) const override
~PHIExpression() override
bool equals(const Expression &Other) const override
~StoreExpression() override
Value * getStoredValue() const
static std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
const Function * getFunction() const
Return the function this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
Value * getPointerOperand()
BasicBlock * getBlock() const
Represents phi nodes for memory accesses.
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
An analysis that produces MemorySSA for a function.
This is the generic walker interface for walkers of MemorySSA.
MemoryAccess * getClobberingMemoryAccess(const Instruction *I, BatchAAResults &AA)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Encapsulates MemorySSA, including all data associated with memory accesses.
MemorySSAWalker * getWalker()
MemoryUseOrDef * getMemoryAccess(const Instruction *I) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
MemoryAccess * getLiveOnEntryDef() const
const DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
Class that has the common methods + fields of memory uses/defs.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
PreservedAnalyses run(Function &F, AnalysisManager< Function > &AM)
Run the pass over the function.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Encapsulates PredicateInfo, including all data associated with memory accesses.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void preserve()
Mark an analysis as preserved.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallPtrSetIterator< PtrType > const_iterator
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
static IntegerType * getInt8Ty(LLVMContext &C)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVMContext & getContext() const
All values hold a context through their type.
std::pair< iterator, bool > insert(const ValueT &V)
iterator find(const_arg_type_t< ValueT > V)
bool erase(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
An opaque object representing a hash code.
const ParentTy * getParent() const
self_iterator getIterator()
A range adaptor for a pair of iterators.
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
friend const_iterator end(StringRef path)
Get end iterator over path.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
bool match(Val *V, const Pattern &P)
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
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...
Constant * getConstantValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
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...
Constant * getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, const DataLayout &DL)
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...
@ CE
Windows NT (Windows on ARM)
initializer< Ty > init(const Ty &Val)
std::vector< ExecutorSymbolDef > LookupResult
NodeAddr< DefNode * > Def
const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Value * simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef< Value * > Indices, GEPNoWrapFlags NW, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
auto successors(const MachineBasicBlock *BB)
SDValue getStoredValue(SDValue Op)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
mapped_iterator< ItTy, FuncTy > map_iterator(ItTy I, FuncTy F)
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool wouldInstructionBeTriviallyDead(const 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.
void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
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...
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
bool salvageKnowledge(Instruction *I, AssumptionCache *AC=nullptr, DominatorTree *DT=nullptr)
Calls BuildAssumeFromInst and if the resulting llvm.assume is valid insert if before I.
Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
OutputIt copy(R &&Range, OutputIt Out)
iterator_range< df_iterator< T > > depth_first(const T &G)
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
Value * simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q)
Given operands for a SelectInst, fold the result or return null.
iterator_range< def_chain_iterator< T, true > > optimized_def_chain(T MA)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
PointerIntPair< Value *, 1, bool > Def
bool operator<(const ValueDFS &Other) const
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
static unsigned getHashValue(const ExactEqualsExpression &E)
static unsigned getHashValue(const Expression *E)
static const Expression * getTombstoneKey()
static bool isEqual(const Expression *LHS, const Expression *RHS)
static const Expression * getEmptyKey()
static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
ExactEqualsExpression(const Expression &E)
hash_code getComputedHash() const
bool operator==(const Expression &Other) const
SimplifyQuery getWithInstruction(const Instruction *I) const