48 #define DEBUG_TYPE "attributor" 51 "Number of function with exact definitions");
53 "Number of function without exact definitions");
55 "Number of abstract attributes timed out before fixpoint");
57 "Number of abstract attributes in a valid fixpoint state");
59 "Number of abstract attributes manifested in IR");
60 STATISTIC(NumAttributesFixedDueToRequiredDependences,
61 "Number of abstract attributes fixed due to required dependences");
76 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \ 77 ("Number of " #TYPE " marked '" #NAME "'") 78 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME 79 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG); 80 #define STATS_DECL(NAME, TYPE, MSG) \ 81 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG); 82 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE)); 83 #define STATS_DECLTRACK(NAME, TYPE, MSG) \ 85 STATS_DECL(NAME, TYPE, MSG) \ 86 STATS_TRACK(NAME, TYPE) \ 88 #define STATS_DECLTRACK_ARG_ATTR(NAME) \ 89 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME)) 90 #define STATS_DECLTRACK_CSARG_ATTR(NAME) \ 91 STATS_DECLTRACK(NAME, CSArguments, \ 92 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME)) 93 #define STATS_DECLTRACK_FN_ATTR(NAME) \ 94 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME)) 95 #define STATS_DECLTRACK_CS_ATTR(NAME) \ 96 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME)) 97 #define STATS_DECLTRACK_FNRET_ATTR(NAME) \ 98 STATS_DECLTRACK(NAME, FunctionReturn, \ 99 BUILD_STAT_MSG_IR_ATTR(function returns, NAME)) 100 #define STATS_DECLTRACK_CSRET_ATTR(NAME) \ 101 STATS_DECLTRACK(NAME, CSReturn, \ 102 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME)) 103 #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \ 104 STATS_DECLTRACK(NAME, Floating, \ 105 ("Number of floating values known to be '" #NAME "'")) 110 #define PIPE_OPERATOR(CLASS) \ 111 raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) { \ 112 return OS << static_cast<const AbstractAttribute &>(AA); \ 147 cl::desc(
"Maximal number of fixpoint iterations."),
150 "attributor-max-iterations-verify",
cl::Hidden,
151 cl::desc(
"Verify that max-iterations is a tight bound for a fixpoint"),
156 cl::desc(
"Disable the attributor inter-procedural deduction pass."),
161 cl::desc(
"Annotate call sites of function declarations."),
cl::init(
false));
165 cl::desc(
"Manifest Attributor internal string attributes."),
169 "attributor-dependence-recompute-interval",
cl::Hidden,
170 cl::desc(
"Number of iterations until dependences are recomputed."),
208 for (
const Use *U : CBUses) {
222 "ACS mapped into var-args arguments!");
224 CBCandidateArg =
nullptr;
239 return Callee->
getArg(ArgNo);
248 if (!isa<CallBase>(Old))
252 if (isa<Instruction>(U.getUser()))
265 template <
typename AAType,
typename StateTy>
271 const AAIsDead *LivenessAA =
nullptr;
276 bool AnyDead =
false;
289 if (!Visited.
insert(V).second)
293 if (Iteration++ >= MaxValues)
298 Value *NewV =
nullptr;
305 if (
Arg.hasReturnedAttr()) {
311 if (NewV && NewV != V) {
317 if (
auto *
SI = dyn_cast<SelectInst>(V)) {
324 if (
auto *PHI = dyn_cast<PHINode>(V)) {
326 "Expected liveness in the presence of instructions!");
327 for (
unsigned u = 0,
e = PHI->getNumIncomingValues(); u <
e; u++) {
328 const BasicBlock *IncomingBB = PHI->getIncomingBlock(u);
333 Worklist.
push_back(PHI->getIncomingValue(u));
339 if (!VisitValueCB(*V, State, Iteration > 1))
341 }
while (!Worklist.
empty());
397 bool AllowNonInbounds =
false) {
409 if (getState().isAtFixpoint())
414 HasChanged = updateImpl(A);
416 LLVM_DEBUG(
dbgs() <<
"[Attributor] Update " << HasChanged <<
" " << *
this 451 for (
const Attribute &Attr : DeducedAttrs) {
484 IRPositions.emplace_back(IRP);
494 IRPositions.emplace_back(
498 assert(ICS &&
"Expected call site!");
501 if (!ICS.hasOperandBundles())
506 assert(ICS &&
"Expected call site!");
509 if (!ICS.hasOperandBundles()) {
515 IRPositions.emplace_back(
520 assert(ICS && ArgNo >= 0 &&
"Expected call site!");
523 if (!ICS.hasOperandBundles()) {
537 bool IgnoreSubsumingPositions)
const {
540 if (EquivIRP.getAttr(AK).getKindAsEnum() == AK)
545 if (IgnoreSubsumingPositions)
553 bool IgnoreSubsumingPositions)
const {
556 const Attribute &Attr = EquivIRP.getAttr(AK);
563 if (IgnoreSubsumingPositions)
568 void IRPosition::verify() {
573 "Expected call base or argument for positive attribute index!");
576 "Argument number mismatch!");
578 "Associated value mismatch!");
581 "Call site argument number mismatch!");
584 "Associated value mismatch!");
593 "Expected specialized kind for call base and argument values!");
597 "Expected function for a 'returned' position!");
602 "Expected call base for 'call site returned' position!");
607 "Expected call base for 'call site function' position!");
612 "Expected function for a 'function' position!");
622 template <
typename StateType>
623 ChangeStatus clampStateAndIndicateChange(StateType &S,
const StateType &R) {
624 auto Assumed = S.getAssumed();
632 template <
typename AAType,
typename StateType =
typename AAType::StateType>
633 static void clampReturnedValueStates(
Attributor &A,
const AAType &QueryingAA,
635 LLVM_DEBUG(
dbgs() <<
"[Attributor] Clamp return value states for " 636 << QueryingAA <<
" into " << S <<
"\n");
638 assert((QueryingAA.getIRPosition().getPositionKind() ==
640 QueryingAA.getIRPosition().getPositionKind() ==
642 "Can only clamp returned value states for a function returned or call " 643 "site returned position!");
650 auto CheckReturnValue = [&](
Value &RV) ->
bool {
652 const AAType &AA = A.
getAAFor<AAType>(QueryingAA, RVPos);
653 LLVM_DEBUG(
dbgs() <<
"[Attributor] RV: " << RV <<
" AA: " << AA.getAsStr()
654 <<
" @ " << RVPos <<
"\n");
655 const StateType &AAS =
static_cast<const StateType &
>(AA.getState());
660 LLVM_DEBUG(
dbgs() <<
"[Attributor] AA State: " << AAS <<
" RV State: " << T
662 return T->isValidState();
666 S.indicatePessimisticFixpoint();
672 template <
typename AAType,
typename Base,
typename StateType,
673 template <
typename...>
class F,
template <
typename...>
class G>
674 struct AAComposeTwoGenericDeduction
675 :
public F<AAType, G<AAType, Base, StateType>, StateType> {
676 AAComposeTwoGenericDeduction(
const IRPosition &IRP)
677 : F<AAType, G<AAType, Base, StateType>, StateType>(IRP) {}
682 F<AAType, G<AAType, Base, StateType>, StateType>::updateImpl(A);
683 ChangeStatus ChangedG = G<AAType, Base, StateType>::updateImpl(A);
684 return ChangedF | ChangedG;
689 template <
typename AAType,
typename Base,
690 typename StateType =
typename AAType::StateType>
691 struct AAReturnedFromReturnedValues :
public Base {
692 AAReturnedFromReturnedValues(
const IRPosition &IRP) : Base(IRP) {}
697 clampReturnedValueStates<AAType, StateType>(A, *
this, S);
700 return clampStateAndIndicateChange<StateType>(this->getState(), S);
706 template <
typename AAType,
typename StateType =
typename AAType::StateType>
707 static void clampCallSiteArgumentStates(
Attributor &A,
const AAType &QueryingAA,
709 LLVM_DEBUG(
dbgs() <<
"[Attributor] Clamp call site argument states for " 710 << QueryingAA <<
" into " << S <<
"\n");
712 assert(QueryingAA.getIRPosition().getPositionKind() ==
714 "Can only clamp call site argument states for an argument position!");
721 unsigned ArgNo = QueryingAA.getIRPosition().getArgNo();
730 const AAType &AA = A.
getAAFor<AAType>(QueryingAA, ACSArgPos);
731 LLVM_DEBUG(
dbgs() <<
"[Attributor] ACS: " << *ACS.getInstruction()
732 <<
" AA: " << AA.getAsStr() <<
" @" << ACSArgPos <<
"\n");
733 const StateType &AAS =
static_cast<const StateType &
>(AA.getState());
738 LLVM_DEBUG(
dbgs() <<
"[Attributor] AA State: " << AAS <<
" CSA State: " << T
740 return T->isValidState();
744 S.indicatePessimisticFixpoint();
745 else if (T.hasValue())
750 template <
typename AAType,
typename Base,
751 typename StateType =
typename AAType::StateType>
752 struct AAArgumentFromCallSiteArguments :
public Base {
753 AAArgumentFromCallSiteArguments(
const IRPosition &IRP) : Base(IRP) {}
758 clampCallSiteArgumentStates<AAType, StateType>(A, *
this, S);
761 return clampStateAndIndicateChange<StateType>(this->getState(), S);
766 template <
typename AAType,
typename Base,
767 typename StateType =
typename AAType::StateType>
768 struct AACallSiteReturnedFromReturned :
public Base {
769 AACallSiteReturnedFromReturned(
const IRPosition &IRP) : Base(IRP) {}
775 "Can only wrap function returned positions for call site returned " 777 auto &S = this->getState();
779 const Function *AssociatedFunction =
780 this->getIRPosition().getAssociatedFunction();
781 if (!AssociatedFunction)
782 return S.indicatePessimisticFixpoint();
785 const AAType &AA = A.
getAAFor<AAType>(*
this, FnPos);
786 return clampStateAndIndicateChange(
787 S, static_cast<const typename AAType::StateType &>(AA.getState()));
799 template <
typename AAType,
typename Base,
800 typename StateType =
typename AAType::StateType>
801 struct AAFromMustBeExecutedContext :
public Base {
802 AAFromMustBeExecutedContext(
const IRPosition &IRP) : Base(IRP) {}
806 const IRPosition &IRP = this->getIRPosition();
818 auto BeforeState = this->getState();
819 auto &S = this->getState();
820 Instruction *CtxI = this->getIRPosition().getCtxI();
827 auto EIt = Explorer.
begin(CtxI), EEnd = Explorer.
end(CtxI);
828 for (
unsigned u = 0; u < Uses.size(); ++u) {
829 const Use *U = Uses[u];
830 if (
const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) {
832 if (Found && Base::followUse(A, U, UserI))
833 for (
const Use &Us : UserI->
uses())
846 template <
typename AAType,
typename Base,
847 typename StateType =
typename AAType::StateType>
848 using AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext =
849 AAComposeTwoGenericDeduction<AAType, Base, StateType,
850 AAFromMustBeExecutedContext,
851 AAArgumentFromCallSiteArguments>;
853 template <
typename AAType,
typename Base,
854 typename StateType =
typename AAType::StateType>
855 using AACallSiteReturnedFromReturnedAndMustBeExecutedContext =
856 AAComposeTwoGenericDeduction<AAType, Base, StateType,
857 AAFromMustBeExecutedContext,
858 AACallSiteReturnedFromReturned>;
865 const std::string getAsStr()
const override {
866 return getAssumed() ?
"nounwind" :
"may-unwind";
872 (
unsigned)Instruction::Invoke, (
unsigned)Instruction::CallBr,
874 (
unsigned)Instruction::CatchSwitch, (
unsigned)Instruction::Resume};
881 const auto &NoUnwindAA =
889 return indicatePessimisticFixpoint();
895 struct AANoUnwindFunction final :
public AANoUnwindImpl {
896 AANoUnwindFunction(
const IRPosition &IRP) : AANoUnwindImpl(IRP) {}
903 struct AANoUnwindCallSite final : AANoUnwindImpl {
904 AANoUnwindCallSite(
const IRPosition &IRP) : AANoUnwindImpl(IRP) {}
911 indicatePessimisticFixpoint();
923 return clampStateAndIndicateChange(
925 static_cast<const AANoUnwind::StateType &>(FnAA.getState()));
955 bool IsFixed =
false;
956 bool IsValidState =
true;
967 ReturnedValues.
clear();
971 indicatePessimisticFixpoint();
980 if (
Arg.hasReturnedAttr()) {
981 auto &ReturnInstSet = ReturnedValues[&
Arg];
983 ReturnInstSet.
insert(cast<ReturnInst>(RI));
985 indicateOptimisticFixpoint();
991 indicatePessimisticFixpoint();
1001 const AbstractState &getState()
const override {
return *
this; }
1015 return UnresolvedCalls;
1019 size_t getNumReturnValues()
const override {
1020 return isValidState() ? ReturnedValues.
size() : -1;
1029 bool checkForAllReturnedValuesAndReturnInsts(
1031 &Pred)
const override;
1034 const std::string getAsStr()
const override;
1037 bool isAtFixpoint()
const override {
return IsFixed; }
1040 bool isValidState()
const override {
return IsValidState; }
1050 IsValidState =
false;
1061 "Number of function with known return values");
1071 "Number of function with unique return");
1082 if (
auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.
getValue())) {
1087 }
else if (
auto *RVC = dyn_cast<Constant>(UniqueRV.
getValue())) {
1090 if (
Function *
F = dyn_cast<Function>(&AnchorValue)) {
1091 for (
const Use &U :
F->uses())
1092 if (
CallBase *CB = dyn_cast<CallBase>(U.getUser()))
1095 CB->
getType() == RVC->getType()
1098 Changed = ReplaceCallSiteUsersWith(*CB, *RVCCast) | Changed;
1101 assert(isa<CallBase>(AnchorValue) &&
1102 "Expcected a function or call base anchor!");
1104 AnchorValue.
getType() == RVC->getType()
1107 Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVCCast);
1111 "Number of function returns replaced by constant return");
1117 const std::string AAReturnedValuesImpl::getAsStr()
const {
1118 return (isAtFixpoint() ?
"returns(#" :
"may-return(#") +
1124 AAReturnedValuesImpl::getAssumedUniqueReturnValue(
Attributor &A)
const {
1132 auto Pred = [&](
Value &RV) ->
bool {
1136 if (UniqueRV.
hasValue() && UniqueRV != &RV &&
1137 !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.
getValue()))) {
1143 if (!UniqueRV.
hasValue() || !isa<UndefValue>(RV))
1155 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts(
1158 if (!isValidState())
1163 for (
auto &It : ReturnedValues) {
1164 Value *RV = It.first;
1167 if (CB && !UnresolvedCalls.count(CB))
1170 if (!Pred(*RV, It.second))
1178 size_t NumUnresolvedCalls = UnresolvedCalls.size();
1179 bool Changed =
false;
1184 decltype(ReturnedValues) &RetValsMap;
1192 auto VisitValueCB = [](
Value &Val, RVState &RVS,
bool) ->
bool {
1193 auto Size = RVS.RetValsMap[&Val].size();
1194 RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end());
1195 bool Inserted = RVS.RetValsMap[&Val].size() !=
Size;
1196 RVS.Changed |= Inserted;
1199 dbgs() <<
"[AAReturnedValues] 1 Add new returned value " << Val
1200 <<
" => " << RVS.RetInsts.size() <<
"\n";
1206 auto VisitReturnedValue = [&](
Value &RV, RVState &RVS) {
1208 return genericValueTraversal<AAReturnedValues, RVState>(A, RetValPos, *
this,
1213 auto CheckReturnInst = [
this, &VisitReturnedValue, &Changed](
Instruction &
I) {
1215 RVState RVS({ReturnedValues, Changed, {}});
1216 RVS.RetInsts.insert(&Ret);
1223 return indicatePessimisticFixpoint();
1227 decltype(ReturnedValues) NewRVsMap;
1228 for (
auto &It : ReturnedValues) {
1229 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] Returned value: " << *It.first
1230 <<
" by #" << It.second.size() <<
" RIs\n");
1232 if (!CB || UnresolvedCalls.count(CB))
1235 if (!CB->getCalledFunction()) {
1236 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] Unresolved call: " << *CB
1238 UnresolvedCalls.insert(CB);
1245 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] Found another AAReturnedValues: " 1246 << RetValAA <<
"\n");
1250 if (!RetValAA.getState().isValidState()) {
1251 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] Unresolved call: " << *CB
1253 UnresolvedCalls.insert(CB);
1259 auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls();
1260 if (!RetValAAUnresolvedCalls.empty()) {
1261 UnresolvedCalls.insert(CB);
1267 bool Unresolved =
false;
1268 for (
auto &RetValAAIt : RetValAA.returned_values()) {
1269 Value *RetVal = RetValAAIt.first;
1270 if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) ||
1271 isa<Constant>(RetVal))
1275 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] transitively returned value " 1276 "cannot be translated: " 1277 << *RetVal <<
"\n");
1278 UnresolvedCalls.insert(CB);
1287 unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB];
1288 if (NumRetAA == RetValAA.getNumReturnValues()) {
1289 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] Skip call as it has not " 1290 "changed since it was seen last\n");
1293 NumRetAA = RetValAA.getNumReturnValues();
1295 for (
auto &RetValAAIt : RetValAA.returned_values()) {
1296 Value *RetVal = RetValAAIt.first;
1300 bool Unused =
false;
1301 RVState RVS({NewRVsMap, Unused, RetValAAIt.second});
1302 VisitReturnedValue(*CB->getArgOperand(
Arg->getArgNo()), RVS);
1304 }
else if (isa<CallBase>(RetVal)) {
1308 }
else if (isa<Constant>(RetVal)) {
1310 NewRVsMap[RetVal].insert(It.second.begin(), It.second.end());
1318 for (
auto &It : NewRVsMap) {
1319 assert(!It.second.empty() &&
"Entry does not add anything.");
1320 auto &ReturnInsts = ReturnedValues[It.first];
1322 if (ReturnInsts.insert(RI)) {
1323 LLVM_DEBUG(
dbgs() <<
"[AAReturnedValues] Add new returned value " 1324 << *It.first <<
" => " << *RI <<
"\n");
1329 Changed |= (NumUnresolvedCalls != UnresolvedCalls.size());
1333 struct AAReturnedValuesFunction final :
public AAReturnedValuesImpl {
1334 AAReturnedValuesFunction(
const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {}
1341 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl {
1342 AAReturnedValuesCallSite(
const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {}
1351 "supported for call sites yet!");
1356 return indicatePessimisticFixpoint();
1360 void trackStatistics()
const override {}
1368 const std::string getAsStr()
const override {
1369 return getAssumed() ?
"nosync" :
"may-sync";
1388 bool AANoSyncImpl::isNonRelaxedAtomic(
Instruction *
I) {
1394 case Instruction::AtomicRMW:
1395 Ordering = cast<AtomicRMWInst>(
I)->getOrdering();
1398 Ordering = cast<StoreInst>(
I)->getOrdering();
1401 Ordering = cast<LoadInst>(
I)->getOrdering();
1403 case Instruction::Fence: {
1404 auto *FI = cast<FenceInst>(
I);
1407 Ordering = FI->getOrdering();
1410 case Instruction::AtomicCmpXchg: {
1412 AtomicOrdering Failure = cast<AtomicCmpXchgInst>(
I)->getFailureOrdering();
1425 "New atomic operations need to be known in the attributor.");
1437 bool AANoSyncImpl::isNoSyncIntrinsic(
Instruction *I) {
1438 if (
auto *II = dyn_cast<IntrinsicInst>(I)) {
1439 switch (II->getIntrinsicID()) {
1442 case Intrinsic::memset_element_unordered_atomic:
1443 case Intrinsic::memmove_element_unordered_atomic:
1444 case Intrinsic::memcpy_element_unordered_atomic:
1446 case Intrinsic::memset:
1447 case Intrinsic::memmove:
1448 case Intrinsic::memcpy:
1449 if (!cast<MemIntrinsic>(II)->isVolatile())
1461 "Calls should not be checked here");
1464 case Instruction::AtomicRMW:
1470 case Instruction::AtomicCmpXchg:
1483 if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I))
1487 if (ICS.hasFnAttr(Attribute::NoSync))
1490 const auto &NoSyncAA =
1492 if (NoSyncAA.isAssumedNoSync())
1497 if (!
isVolatile(&I) && !isNonRelaxedAtomic(&I))
1515 return indicatePessimisticFixpoint();
1520 struct AANoSyncFunction final :
public AANoSyncImpl {
1521 AANoSyncFunction(
const IRPosition &IRP) : AANoSyncImpl(IRP) {}
1528 struct AANoSyncCallSite final : AANoSyncImpl {
1529 AANoSyncCallSite(
const IRPosition &IRP) : AANoSyncImpl(IRP) {}
1536 indicatePessimisticFixpoint();
1548 return clampStateAndIndicateChange(
1549 getState(), static_cast<const AANoSync::StateType &>(FnAA.getState()));
1558 struct AANoFreeImpl :
public AANoFree {
1568 const auto &NoFreeAA =
1574 return indicatePessimisticFixpoint();
1579 const std::string getAsStr()
const override {
1580 return getAssumed() ?
"nofree" :
"may-free";
1584 struct AANoFreeFunction final :
public AANoFreeImpl {
1585 AANoFreeFunction(
const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1592 struct AANoFreeCallSite final : AANoFreeImpl {
1593 AANoFreeCallSite(
const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1600 indicatePessimisticFixpoint();
1612 return clampStateAndIndicateChange(
1613 getState(), static_cast<const AANoFree::StateType &>(FnAA.getState()));
1621 struct AANoFreeFloating : AANoFreeImpl {
1622 AANoFreeFloating(
const IRPosition &IRP) : AANoFreeImpl(IRP) {}
1631 const auto &NoFreeAA =
1633 if (NoFreeAA.isAssumedNoFree())
1636 Value &AssociatedValue = getIRPosition().getAssociatedValue();
1637 auto Pred = [&](
const Use &U,
bool &Follow) ->
bool {
1639 if (
auto *CB = dyn_cast<CallBase>(UserI)) {
1640 if (CB->isBundleOperand(&U))
1642 if (!CB->isArgOperand(&U))
1644 unsigned ArgNo = CB->getArgOperandNo(&U);
1651 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
1652 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
1661 return indicatePessimisticFixpoint();
1668 struct AANoFreeArgument final : AANoFreeFloating {
1669 AANoFreeArgument(
const IRPosition &IRP) : AANoFreeFloating(IRP) {}
1676 struct AANoFreeCallSiteArgument final : AANoFreeFloating {
1677 AANoFreeCallSiteArgument(
const IRPosition &IRP) : AANoFreeFloating(IRP) {}
1687 return indicatePessimisticFixpoint();
1690 return clampStateAndIndicateChange(
1691 getState(), static_cast<const AANoFree::StateType &>(ArgAA.getState()));
1699 struct AANoFreeReturned final : AANoFreeFloating {
1700 AANoFreeReturned(
const IRPosition &IRP) : AANoFreeFloating(IRP) {
1715 void trackStatistics()
const override {}
1719 struct AANoFreeCallSiteReturned final : AANoFreeFloating {
1720 AANoFreeCallSiteReturned(
const IRPosition &IRP) : AANoFreeFloating(IRP) {}
1730 static int64_t getKnownNonNullAndDerefBytesForUse(
1732 const Use *U,
const Instruction *I,
bool &IsNonNull,
bool &TrackUse) {
1735 const Value *UseV = U->get();
1745 if (ICS.isBundleOperand(U))
1748 if (ICS.isCallee(U)) {
1753 unsigned ArgNo = ICS.getArgumentNo(U);
1759 IsNonNull |= DerefAA.isKnownNonNull();
1760 return DerefAA.getKnownDereferenceableBytes();
1766 if (isa<CastInst>(I)) {
1770 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I))
1771 if (
GEP->hasAllConstantIndices()) {
1778 if (Base == &AssociatedValue &&
1780 int64_t DerefBytes =
1784 return std::max(int64_t(0), DerefBytes);
1790 I, Offset, DL,
true)) {
1791 if (Offset == 0 && Base == &AssociatedValue &&
1793 int64_t DerefBytes =
1796 return std::max(int64_t(0), DerefBytes);
1812 if (!NullIsDefined &&
1813 hasAttr({Attribute::NonNull, Attribute::Dereferenceable}))
1814 indicateOptimisticFixpoint();
1816 indicatePessimisticFixpoint();
1823 bool IsNonNull =
false;
1824 bool TrackUse =
false;
1826 IsNonNull, TrackUse);
1827 setKnown(IsNonNull);
1832 const std::string getAsStr()
const override {
1833 return getAssumed() ?
"nonnull" :
"may-null";
1838 const bool NullIsDefined;
1842 struct AANonNullFloating
1843 : AAFromMustBeExecutedContext<AANonNull, AANonNullImpl> {
1844 using Base = AAFromMustBeExecutedContext<AANonNull, AANonNullImpl>;
1845 AANonNullFloating(
const IRPosition &IRP) : Base(IRP) {}
1850 if (isKnownNonNull())
1853 if (!NullIsDefined) {
1854 const auto &DerefAA =
1856 if (DerefAA.getAssumedDereferenceableBytes())
1868 bool Stripped) ->
bool {
1870 if (!Stripped &&
this == &AA) {
1883 if (!genericValueTraversal<AANonNull, StateType>(A, getIRPosition(), *
this,
1885 return indicatePessimisticFixpoint();
1887 return clampStateAndIndicateChange(getState(), T);
1895 struct AANonNullReturned final
1896 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> {
1898 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP) {}
1905 struct AANonNullArgument final
1906 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AANonNull,
1909 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
AANonNull,
1917 struct AANonNullCallSiteArgument final : AANonNullFloating {
1918 AANonNullCallSiteArgument(
const IRPosition &IRP) : AANonNullFloating(IRP) {}
1925 struct AANonNullCallSiteReturned final
1926 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AANonNull,
1928 AANonNullCallSiteReturned(
const IRPosition &IRP)
1929 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
AANonNull,
1943 const std::string getAsStr()
const override {
1944 return getAssumed() ?
"norecurse" :
"may-recurse";
1948 struct AANoRecurseFunction final : AANoRecurseImpl {
1949 AANoRecurseFunction(
const IRPosition &IRP) : AANoRecurseImpl(IRP) {}
1957 indicatePessimisticFixpoint();
1965 if (ICS.
hasFnAttr(Attribute::NoRecurse))
1968 const auto &NoRecurseAA =
1970 if (!NoRecurseAA.isAssumedNoRecurse())
1981 return indicatePessimisticFixpoint();
1989 struct AANoRecurseCallSite final : AANoRecurseImpl {
1990 AANoRecurseCallSite(
const IRPosition &IRP) : AANoRecurseImpl(IRP) {}
1997 indicatePessimisticFixpoint();
2009 return clampStateAndIndicateChange(
2011 static_cast<const AANoRecurse::StateType &>(FnAA.getState()));
2026 const size_t UBPrevSize = KnownUBInsts.size();
2027 const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2031 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2037 const Value *PtrOp =
2040 "Expected pointer operand of memory accessing instruction");
2045 if (!isa<ConstantPointerNull>(PtrOp)) {
2046 AssumedNoUBInsts.insert(&I);
2058 AssumedNoUBInsts.insert(&I);
2060 KnownUBInsts.insert(&I);
2069 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I))
2073 auto BrInst = cast<BranchInst>(&
I);
2076 if (BrInst->isUnconditional())
2082 stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst);
2085 AssumedNoUBInsts.insert(&I);
2091 Instruction::AtomicCmpXchg,
2092 Instruction::AtomicRMW});
2094 if (NoUBPrevSize != AssumedNoUBInsts.size() ||
2095 UBPrevSize != KnownUBInsts.size())
2100 bool isKnownToCauseUB(
Instruction *I)
const override {
2101 return KnownUBInsts.count(I);
2104 bool isAssumedToCauseUB(
Instruction *I)
const override {
2114 case Instruction::AtomicCmpXchg:
2115 case Instruction::AtomicRMW:
2116 return !AssumedNoUBInsts.count(I);
2117 case Instruction::Br: {
2118 auto BrInst = cast<BranchInst>(
I);
2119 if (BrInst->isUnconditional())
2121 return !AssumedNoUBInsts.count(I);
2130 if (KnownUBInsts.empty())
2138 const std::string getAsStr()
const override {
2139 return getAssumed() ?
"undefined-behavior" :
"no-ub";
2184 const auto &ValueSimplifyAA =
2187 ValueSimplifyAA.getAssumedSimplifiedValue(A);
2188 if (!ValueSimplifyAA.isKnown()) {
2192 if (!SimplifiedV.hasValue()) {
2198 Value *Val = SimplifiedV.getValue();
2199 if (isa<UndefValue>(Val)) {
2207 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
2208 AAUndefinedBehaviorFunction(
const IRPosition &IRP)
2209 : AAUndefinedBehaviorImpl(IRP) {}
2212 void trackStatistics()
const override {
2214 "Number of instructions known to have UB");
2216 KnownUBInsts.size();
2224 static bool containsCycle(
Function &
F) {
2231 if (Visited.
count(SuccBB))
2242 static bool containsPossiblyEndlessLoop(
Function *F) {
2254 if (containsPossiblyEndlessLoop(F))
2255 indicatePessimisticFixpoint();
2263 if (WillReturnAA.isKnownWillReturn())
2265 if (!WillReturnAA.isAssumedWillReturn())
2272 return indicatePessimisticFixpoint();
2278 const std::string getAsStr()
const override {
2279 return getAssumed() ?
"willreturn" :
"may-noreturn";
2283 struct AAWillReturnFunction final : AAWillReturnImpl {
2284 AAWillReturnFunction(
const IRPosition &IRP) : AAWillReturnImpl(IRP) {}
2291 struct AAWillReturnCallSite final : AAWillReturnImpl {
2292 AAWillReturnCallSite(
const IRPosition &IRP) : AAWillReturnImpl(IRP) {}
2299 indicatePessimisticFixpoint();
2311 return clampStateAndIndicateChange(
2313 static_cast<const AAWillReturn::StateType &>(FnAA.getState()));
2325 const std::string getAsStr()
const override {
2335 return indicatePessimisticFixpoint();
2339 struct AAReachabilityFunction final :
public AAReachabilityImpl {
2340 AAReachabilityFunction(
const IRPosition &IRP) : AAReachabilityImpl(IRP) {}
2351 const std::string getAsStr()
const override {
2352 return getAssumed() ?
"noalias" :
"may-alias";
2357 struct AANoAliasFloating final : AANoAliasImpl {
2358 AANoAliasFloating(
const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2364 if (isa<AllocaInst>(Val))
2365 indicateOptimisticFixpoint();
2366 if (isa<ConstantPointerNull>(Val) &&
2368 indicateOptimisticFixpoint();
2374 return indicatePessimisticFixpoint();
2378 void trackStatistics()
const override {
2384 struct AANoAliasArgument final
2385 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
2386 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
2387 AANoAliasArgument(
const IRPosition &IRP) : Base(IRP) {}
2399 if (NoSyncAA.isAssumedNoSync())
2400 return Base::updateImpl(A);
2403 const auto &MemBehaviorAA =
2405 if (MemBehaviorAA.isAssumedReadOnly())
2406 return Base::updateImpl(A);
2413 return Base::updateImpl(A);
2421 return indicatePessimisticFixpoint();
2428 struct AANoAliasCallSiteArgument final : AANoAliasImpl {
2429 AANoAliasCallSiteArgument(
const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2436 indicateOptimisticFixpoint();
2454 LLVM_DEBUG(
dbgs() <<
"[Attributor][AANoAliasCSArg] check definition: " << V
2455 <<
" :: " << NoAliasAA <<
"\n");
2457 if (!NoAliasAA.isAssumedNoAlias())
2458 return indicatePessimisticFixpoint();
2461 <<
" is assumed NoAlias in the definition\n");
2468 if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
2470 dbgs() <<
"[Attributor][AANoAliasCSArg] " << V
2471 <<
" cannot be noalias as it is potentially captured\n");
2472 return indicatePessimisticFixpoint();
2490 <<
"[Attributor][NoAliasCSArg] Check alias between " 2491 "callsite arguments " 2494 << (IsAliasing ?
"" :
"no-") <<
"alias \n");
2500 return indicatePessimisticFixpoint();
2511 struct AANoAliasReturned final : AANoAliasImpl {
2512 AANoAliasReturned(
const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2517 auto CheckReturnValue = [&](
Value &RV) ->
bool {
2518 if (
Constant *
C = dyn_cast<Constant>(&RV))
2519 if (
C->isNullValue() || isa<UndefValue>(
C))
2530 if (!NoAliasAA.isAssumedNoAlias())
2538 return indicatePessimisticFixpoint();
2548 struct AANoAliasCallSiteReturned final : AANoAliasImpl {
2549 AANoAliasCallSiteReturned(
const IRPosition &IRP) : AANoAliasImpl(IRP) {}
2556 indicatePessimisticFixpoint();
2568 return clampStateAndIndicateChange(
2569 getState(), static_cast<const AANoAlias::StateType &>(FnAA.getState()));
2578 struct AAIsDeadValueImpl :
public AAIsDead {
2582 bool isAssumedDead()
const override {
return getAssumed(); }
2585 bool isAssumedDead(
const BasicBlock *BB)
const override {
return false; }
2588 bool isKnownDead(
const BasicBlock *BB)
const override {
return false; }
2591 bool isAssumedDead(
const Instruction *I)
const override {
2592 return I ==
getCtxI() && isAssumedDead();
2596 bool isKnownDead(
const Instruction *I)
const override {
2597 return I ==
getCtxI() && getKnown();
2601 const std::string getAsStr()
const override {
2602 return isAssumedDead() ?
"assumed-dead" :
"assumed-live";
2606 struct AAIsDeadFloating :
public AAIsDeadValueImpl {
2607 AAIsDeadFloating(
const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {}
2613 indicatePessimisticFixpoint();
2615 indicatePessimisticFixpoint();
2620 auto UsePred = [&](
const Use &U,
bool &Follow) {
2623 if (!CS.isArgOperand(&U))
2630 if (
ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
2640 return indicatePessimisticFixpoint();
2647 if (
auto *I = dyn_cast<Instruction>(&V))
2662 void trackStatistics()
const override {
2667 struct AAIsDeadArgument :
public AAIsDeadFloating {
2668 AAIsDeadArgument(
const IRPosition &IRP) : AAIsDeadFloating(IRP) {}
2673 indicatePessimisticFixpoint();
2693 struct AAIsDeadCallSiteArgument :
public AAIsDeadValueImpl {
2694 AAIsDeadCallSiteArgument(
const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {}
2699 indicatePessimisticFixpoint();
2710 return indicatePessimisticFixpoint();
2713 return clampStateAndIndicateChange(
2714 getState(), static_cast<const AAIsDead::StateType &>(ArgAA.getState()));
2721 assert(!isa<UndefValue>(U.get()) &&
2722 "Expected undef values to be filtered out!");
2733 struct AAIsDeadReturned :
public AAIsDeadValueImpl {
2734 AAIsDeadReturned(
const IRPosition &IRP) : AAIsDeadValueImpl(IRP) {}
2740 if (ACS.isCallbackCall())
2749 return indicatePessimisticFixpoint();
2757 bool AnyChange =
false;
2773 struct AAIsDeadCallSiteReturned :
public AAIsDeadFloating {
2774 AAIsDeadCallSiteReturned(
const IRPosition &IRP) : AAIsDeadFloating(IRP) {}
2783 struct AAIsDeadFunction :
public AAIsDead {
2796 const std::string getAsStr()
const override {
2797 return "Live[#BB " +
std::to_string(AssumedLiveBlocks.size()) +
"/" +
2805 assert(getState().isValidState() &&
2806 "Attempted to manifest an invalid state!");
2811 if (AssumedLiveBlocks.empty()) {
2819 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F);
2821 KnownDeadEnds.set_union(ToBeExploredFrom);
2822 for (
const Instruction *DeadEndI : KnownDeadEnds) {
2826 const auto &NoReturnAA =
2829 if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB)))
2832 if (
auto *II = dyn_cast<InvokeInst>(DeadEndI))
2836 const_cast<Instruction *>(DeadEndI->getNextNode()));
2841 if (!AssumedLiveBlocks.count(&BB))
2851 void trackStatistics()
const override {}
2854 bool isAssumedDead()
const override {
return false; }
2857 bool isAssumedDead(
const BasicBlock *BB)
const override {
2859 "BB must be in the same anchor scope function.");
2863 return !AssumedLiveBlocks.count(BB);
2867 bool isKnownDead(
const BasicBlock *BB)
const override {
2868 return getKnown() && isAssumedDead(BB);
2872 bool isAssumedDead(
const Instruction *I)
const override {
2874 "Instruction must be in the same anchor scope function.");
2881 if (!AssumedLiveBlocks.count(I->
getParent()))
2887 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
2895 bool isKnownDead(
const Instruction *I)
const override {
2896 return getKnown() && isAssumedDead(I);
2900 static bool mayCatchAsynchronousExceptions(
const Function &F) {
2907 if (!AssumedLiveBlocks.insert(&BB).second)
2916 if (
const Function *F = ICS.getCalledFunction())
2940 if (NoReturnAA.isAssumedNoReturn())
2953 bool UsedAssumedInformation =
2954 identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors);
2959 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.
getFunction())) {
2964 if (AANoUnw.isAssumedNoUnwind()) {
2965 UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind();
2970 return UsedAssumedInformation;
2975 bool &UsedAssumedInformation) {
2976 const auto &ValueSimplifyAA =
2979 UsedAssumedInformation |= !ValueSimplifyAA.isKnown();
2980 if (!SimplifiedV.hasValue())
2982 if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue()))
2984 return dyn_cast_or_null<ConstantInt>(SimplifiedV.getValue());
2991 bool UsedAssumedInformation =
false;
2996 getAssumedConstant(A, *BI.
getCondition(), AA, UsedAssumedInformation);
3006 UsedAssumedInformation =
false;
3009 return UsedAssumedInformation;
3016 bool UsedAssumedInformation =
false;
3018 getAssumedConstant(A, *SI.
getCondition(), AA, UsedAssumedInformation);
3022 for (
auto &CaseIt : SI.
cases()) {
3023 if (CaseIt.getCaseValue() == CI.
getValue()) {
3024 AliveSuccessors.
push_back(&CaseIt.getCaseSuccessor()->front());
3025 return UsedAssumedInformation;
3029 return UsedAssumedInformation;
3032 AliveSuccessors.
push_back(&SuccBB->front());
3034 return UsedAssumedInformation;
3040 LLVM_DEBUG(
dbgs() <<
"[AAIsDead] Live [" << AssumedLiveBlocks.size() <<
"/" 3042 << ToBeExploredFrom.size() <<
" exploration points and " 3043 << KnownDeadEnds.size() <<
" known dead ends\n");
3048 ToBeExploredFrom.end());
3049 decltype(ToBeExploredFrom) NewToBeExploredFrom;
3052 while (!Worklist.empty()) {
3054 LLVM_DEBUG(
dbgs() <<
"[AAIsDead] Exploration inst: " << *I <<
"\n");
3056 AliveSuccessors.
clear();
3058 bool UsedAssumedInformation =
false;
3064 AliveSuccessors.
push_back(&SuccBB->front());
3070 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I),
3071 *
this, AliveSuccessors);
3073 case Instruction::Invoke:
3074 UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I),
3075 *
this, AliveSuccessors);
3077 case Instruction::Br:
3078 UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I),
3079 *
this, AliveSuccessors);
3081 case Instruction::Switch:
3082 UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I),
3083 *
this, AliveSuccessors);
3087 if (UsedAssumedInformation) {
3088 NewToBeExploredFrom.insert(I);
3091 if (AliveSuccessors.
empty() ||
3093 KnownDeadEnds.insert(I);
3097 << AliveSuccessors.
size() <<
" UsedAssumedInformation: " 3098 << UsedAssumedInformation <<
"\n");
3100 for (
const Instruction *AliveSuccessor : AliveSuccessors) {
3102 assert(AliveSuccessors.size() == 1 &&
3103 "Non-terminator expected to have a single successor!");
3104 Worklist.push_back(AliveSuccessor);
3106 if (assumeLive(A, *AliveSuccessor->getParent()))
3107 Worklist.push_back(AliveSuccessor);
3112 ToBeExploredFrom = std::move(NewToBeExploredFrom);
3120 if (ToBeExploredFrom.empty() &&
3125 return indicatePessimisticFixpoint();
3130 struct AAIsDeadCallSite final : AAIsDeadFunction {
3131 AAIsDeadCallSite(
const IRPosition &IRP) : AAIsDeadFunction(IRP) {}
3140 "supported for call sites yet!");
3145 return indicatePessimisticFixpoint();
3149 void trackStatistics()
const override {}
3158 clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState);
3159 ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState);
3169 getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
3172 takeKnownDerefBytesMaximum(Attr.getValueAsInt());
3176 const IRPosition &IRP = this->getIRPosition();
3177 bool IsFnInterface = IRP.isFnInterfaceKind();
3178 const Function *FnScope = IRP.getAnchorScope();
3180 indicatePessimisticFixpoint();
3185 StateType &getState()
override {
return *
this; }
3186 const StateType &getState()
const override {
return *
this; }
3192 const Value *UseV = U->get();
3200 I, Offset, DL,
true)) {
3204 addAccessedBytes(Offset, Size);
3212 bool IsNonNull =
false;
3213 bool TrackUse =
false;
3214 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
3217 addAccessedBytesForUse(A, U, I);
3218 takeKnownDerefBytesMaximum(DerefBytes);
3225 if (isAssumedNonNull() &&
hasAttr(Attribute::DereferenceableOrNull)) {
3235 if (isAssumedNonNull())
3237 Ctx, getAssumedDereferenceableBytes()));
3240 Ctx, getAssumedDereferenceableBytes()));
3244 const std::string getAsStr()
const override {
3245 if (!getAssumedDereferenceableBytes())
3246 return "unknown-dereferenceable";
3247 return std::string(
"dereferenceable") +
3248 (isAssumedNonNull() ?
"" :
"_or_null") +
3249 (isAssumedGlobal() ?
"_globally" :
"") +
"<" +
3256 struct AADereferenceableFloating
3257 : AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl> {
3259 AAFromMustBeExecutedContext<AADereferenceable, AADereferenceableImpl>;
3260 AADereferenceableFloating(
const IRPosition &IRP) : Base(IRP) {}
3277 int64_t DerefBytes = 0;
3278 if (!Stripped &&
this == &AA) {
3283 T.GlobalState.indicatePessimisticFixpoint();
3287 T.GlobalState &= DS.GlobalState;
3299 T.takeAssumedDerefBytesMinimum(
3300 std::max(int64_t(0), DerefBytes - OffsetSExt));
3305 T.takeKnownDerefBytesMaximum(
3306 std::max(int64_t(0), DerefBytes - OffsetSExt));
3307 T.indicatePessimisticFixpoint();
3308 }
else if (OffsetSExt > 0) {
3314 T.indicatePessimisticFixpoint();
3318 return T.isValidState();
3322 if (!genericValueTraversal<AADereferenceable, DerefState>(
3323 A, getIRPosition(), *
this, T, VisitValueCB))
3324 return indicatePessimisticFixpoint();
3326 return Change | clampStateAndIndicateChange(getState(), T);
3330 void trackStatistics()
const override {
3336 struct AADereferenceableReturned final
3337 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl,
3339 AADereferenceableReturned(
const IRPosition &IRP)
3344 void trackStatistics()
const override {
3350 struct AADereferenceableArgument final
3351 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
3352 AADereferenceable, AADereferenceableImpl, DerefState> {
3353 using Base = AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
3355 AADereferenceableArgument(
const IRPosition &IRP) : Base(IRP) {}
3358 void trackStatistics()
const override {
3364 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
3365 AADereferenceableCallSiteArgument(
const IRPosition &IRP)
3366 : AADereferenceableFloating(IRP) {}
3369 void trackStatistics()
const override {
3375 struct AADereferenceableCallSiteReturned final
3376 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
3377 AADereferenceable, AADereferenceableImpl> {
3378 using Base = AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
3380 AADereferenceableCallSiteReturned(
const IRPosition &IRP) : Base(IRP) {}
3383 void trackStatistics()
const override {
3390 static unsigned int getKnownAlignForUse(
Attributor &A,
3392 Value &AssociatedValue,
const Use *U,
3396 if (isa<CastInst>(I)) {
3398 TrackUse = !isa<PtrToIntInst>(
I);
3401 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I)) {
3402 if (
GEP->hasAllConstantIndices()) {
3408 unsigned Alignment = 0;
3410 if (ICS.isBundleOperand(U) || ICS.isCallee(U))
3413 unsigned ArgNo = ICS.getArgumentNo(U);
3419 Alignment = AlignAA.getKnownAlign();
3422 const Value *UseV = U->get();
3423 if (
auto *SI = dyn_cast<StoreInst>(I))
3424 Alignment = SI->getAlignment();
3425 else if (
auto *LI = dyn_cast<LoadInst>(I))
3426 Alignment = LI->getAlignment();
3435 if (Base == &AssociatedValue) {
3448 struct AAAlignImpl :
AAAlign {
3456 takeKnownMaximum(Attr.getValueAsInt());
3458 if (getIRPosition().isFnInterfaceKind() &&
3461 indicatePessimisticFixpoint();
3470 for (
const Use &U : AnchorVal.
uses()) {
3471 if (
auto *SI = dyn_cast<StoreInst>(U.
getUser())) {
3472 if (SI->getPointerOperand() == &
AnchorVal)
3473 if (SI->getAlignment() < getAssumedAlign()) {
3475 "Number of times alignment added to a store");
3476 SI->setAlignment(
Align(getAssumedAlign()));
3479 }
else if (
auto *LI = dyn_cast<LoadInst>(U.
getUser())) {
3480 if (LI->getPointerOperand() == &
AnchorVal)
3481 if (LI->getAlignment() < getAssumedAlign()) {
3482 LI->setAlignment(
Align(getAssumedAlign()));
3484 "Number of times alignment added to a load");
3501 if (getAssumedAlign() > 1)
3507 bool TrackUse =
false;
3509 unsigned int KnownAlign =
3511 takeKnownMaximum(KnownAlign);
3517 const std::string getAsStr()
const override {
3518 return getAssumedAlign() ? (
"align<" +
std::to_string(getKnownAlign()) +
3525 struct AAAlignFloating : AAFromMustBeExecutedContext<AAAlign, AAAlignImpl> {
3526 using Base = AAFromMustBeExecutedContext<AAAlign, AAAlignImpl>;
3527 AAAlignFloating(
const IRPosition &IRP) : Base(IRP) {}
3531 Base::updateImpl(A);
3536 bool Stripped) ->
bool {
3538 if (!Stripped &&
this == &AA) {
3541 T.takeKnownMaximum(PA ? PA->value() : 0);
3542 T.indicatePessimisticFixpoint();
3549 return T.isValidState();
3553 if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *
this, T,
3555 return indicatePessimisticFixpoint();
3559 return clampStateAndIndicateChange(getState(), T);
3567 struct AAAlignReturned final
3568 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
3570 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP) {}
3577 struct AAAlignArgument final
3578 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<AAAlign,
3581 : AAArgumentFromCallSiteArgumentsAndMustBeExecutedContext<
AAAlign,
3589 struct AAAlignCallSiteArgument final : AAAlignFloating {
3590 AAAlignCallSiteArgument(
const IRPosition &IRP) : AAAlignFloating(IRP) {}
3594 return AAAlignImpl::manifest(A);
3604 takeKnownMaximum(ArgAlignAA.getKnownAlign());
3614 struct AAAlignCallSiteReturned final
3615 : AACallSiteReturnedFromReturnedAndMustBeExecutedContext<AAAlign,
3618 AACallSiteReturnedFromReturnedAndMustBeExecutedContext<
AAAlign,
3620 AAAlignCallSiteReturned(
const IRPosition &IRP) : Base(IRP) {}
3627 indicatePessimisticFixpoint();
3643 indicatePessimisticFixpoint();
3647 const std::string getAsStr()
const override {
3648 return getAssumed() ?
"noreturn" :
"may-return";
3653 auto CheckForNoReturn = [](
Instruction &) {
return false; };
3655 {(unsigned)Instruction::Ret}))
3656 return indicatePessimisticFixpoint();
3661 struct AANoReturnFunction final : AANoReturnImpl {
3662 AANoReturnFunction(
const IRPosition &IRP) : AANoReturnImpl(IRP) {}
3669 struct AANoReturnCallSite final : AANoReturnImpl {
3670 AANoReturnCallSite(
const IRPosition &IRP) : AANoReturnImpl(IRP) {}
3681 return clampStateAndIndicateChange(
3683 static_cast<const AANoReturn::StateType &>(FnAA.getState()));
3698 if (
hasAttr(getAttrKind(),
true)) {
3699 indicateOptimisticFixpoint();
3705 indicatePessimisticFixpoint();
3712 indicateOptimisticFixpoint();
3720 determineFunctionCaptureCapabilities(getIRPosition(), *F, *
this);
3722 indicatePessimisticFixpoint();
3732 if (!isAssumedNoCaptureMaybeReturned())
3736 if (isAssumedNoCapture())
3746 static void determineFunctionCaptureCapabilities(
const IRPosition &IRP,
3773 for (
unsigned u = 0,
e = F.
arg_size(); u <
e; ++u)
3775 if (u ==
unsigned(ArgNo))
3787 const std::string getAsStr()
const override {
3788 if (isKnownNoCapture())
3789 return "known not-captured";
3790 if (isAssumedNoCapture())
3791 return "assumed not-captured";
3792 if (isKnownNoCaptureMaybeReturned())
3793 return "known not-captured-maybe-returned";
3794 if (isAssumedNoCaptureMaybeReturned())
3795 return "assumed not-captured-maybe-returned";
3796 return "assumed-captured";
3819 unsigned &RemainingUsesToExplore)
3820 : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State),
3821 PotentialCopies(PotentialCopies),
3822 RemainingUsesToExplore(RemainingUsesToExplore) {}
3825 bool valueMayBeCaptured(
const Value *V) {
3835 void tooManyUses()
override {
3842 const auto &DerefAA =
3848 bool captured(
const Use *U)
override {
3849 Instruction *UInst = cast<Instruction>(U->getUser());
3850 LLVM_DEBUG(
dbgs() <<
"Check use: " << *U->get() <<
" in " << *UInst
3855 if (RemainingUsesToExplore-- == 0) {
3857 return isCapturedIn(
true,
true,
3862 if (isa<PtrToIntInst>(UInst)) {
3864 return valueMayBeCaptured(UInst);
3868 if (isa<ReturnInst>(UInst))
3869 return isCapturedIn(
false,
false,
3876 return isCapturedIn(
true,
true,
3884 if (ArgNoCaptureAA.isAssumedNoCapture())
3885 return isCapturedIn(
false,
false,
3887 if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
3888 addPotentialCopy(CS);
3889 return isCapturedIn(
false,
false,
3894 return isCapturedIn(
true,
true,
3899 void addPotentialCopy(
CallSite CS) {
3904 bool shouldExplore(
const Use *U)
override {
3906 return !IsDeadAA.
isAssumedDead(cast<Instruction>(U->getUser()));
3912 bool isCapturedIn(
bool CapturedInMem,
bool CapturedInInt,
3913 bool CapturedInRet) {
3914 LLVM_DEBUG(
dbgs() <<
" - captures [Mem " << CapturedInMem <<
"|Int " 3915 << CapturedInInt <<
"|Ret " << CapturedInRet <<
"]\n");
3942 unsigned &RemainingUsesToExplore;
3950 return indicatePessimisticFixpoint();
3954 assert(F &&
"Expected a function!");
3962 if (FnMemAA.isAssumedReadOnly()) {
3964 if (FnMemAA.isKnownReadOnly())
3965 addKnownBits(NOT_CAPTURED_IN_MEM);
3973 bool SeenConstant =
false;
3974 for (
auto &It : RVAA.returned_values()) {
3975 if (isa<Constant>(It.first)) {
3978 SeenConstant =
true;
3979 }
else if (!isa<Argument>(It.first) ||
3987 if (NoUnwindAA.isAssumedNoUnwind()) {
3991 if (IsVoidTy || CheckReturnedArgs(*RVAA)) {
3992 T.addKnownBits(NOT_CAPTURED_IN_RET);
3993 if (T.isKnown(NOT_CAPTURED_IN_MEM))
3995 if (NoUnwindAA.isKnownNoUnwind() &&
3997 addKnownBits(NOT_CAPTURED_IN_RET);
3998 if (isKnown(NOT_CAPTURED_IN_MEM))
3999 return indicateOptimisticFixpoint();
4009 AACaptureUseTracker Tracker(A, *
this, IsDeadAA, T, PotentialCopies,
4010 RemainingUsesToExplore);
4016 while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.
size())
4017 Tracker.valueMayBeCaptured(PotentialCopies[Idx++]);
4020 auto Assumed = S.getAssumed();
4021 S.intersectAssumedBits(T.getAssumed());
4022 if (!isAssumedNoCaptureMaybeReturned())
4023 return indicatePessimisticFixpoint();
4029 struct AANoCaptureArgument final : AANoCaptureImpl {
4030 AANoCaptureArgument(
const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4037 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
4038 AANoCaptureCallSiteArgument(
const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4043 if (
Arg->hasByValAttr())
4044 indicateOptimisticFixpoint();
4056 return indicatePessimisticFixpoint();
4059 return clampStateAndIndicateChange(
4061 static_cast<const AANoCapture::StateType &>(ArgAA.getState()));
4069 struct AANoCaptureFloating final : AANoCaptureImpl {
4070 AANoCaptureFloating(
const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4073 void trackStatistics()
const override {
4079 struct AANoCaptureReturned final : AANoCaptureImpl {
4080 AANoCaptureReturned(
const IRPosition &IRP) : AANoCaptureImpl(IRP) {
4095 void trackStatistics()
const override {}
4099 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
4100 AANoCaptureCallSiteReturned(
const IRPosition &IRP) : AANoCaptureImpl(IRP) {}
4103 void trackStatistics()
const override {
4113 const std::string getAsStr()
const override {
4114 return getAssumed() ? (getKnown() ?
"simplified" :
"maybe-simple")
4119 void trackStatistics()
const override {}
4125 return SimplifiedAssociatedValue;
4133 Value &QueryingValue,
4141 ValueSimpifyAA.getAssumedSimplifiedValue(A);
4143 if (!QueryingValueSimplified.hasValue())
4146 if (!QueryingValueSimplified.getValue())
4149 Value &QueryingValueSimplifiedUnwrapped =
4150 *QueryingValueSimplified.getValue();
4152 if (isa<UndefValue>(QueryingValueSimplifiedUnwrapped))
4155 if (AccumulatedSimplifiedValue.
hasValue())
4156 return AccumulatedSimplifiedValue == QueryingValueSimplified;
4158 LLVM_DEBUG(
dbgs() <<
"[Attributor][ValueSimplify] " << QueryingValue
4159 <<
" is assumed to be " 4160 << QueryingValueSimplifiedUnwrapped <<
"\n");
4162 AccumulatedSimplifiedValue = QueryingValueSimplified;
4166 bool askSimplifiedValueForAAValueConstantRange(
Attributor &A) {
4170 const auto &ValueConstantRangeAA =
4174 ValueConstantRangeAA.getAssumedConstantInt(A);
4175 if (COpt.hasValue()) {
4176 if (
auto *
C = COpt.getValue())
4177 SimplifiedAssociatedValue =
C;
4192 if (!SimplifiedAssociatedValue.hasValue() ||
4193 !SimplifiedAssociatedValue.getValue())
4196 if (
auto *
C = dyn_cast<Constant>(SimplifiedAssociatedValue.getValue())) {
4200 LLVM_DEBUG(
dbgs() <<
"[Attributor][ValueSimplify] " << V <<
" -> " << *
C 4215 indicateOptimisticFixpoint();
4227 struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
4228 AAValueSimplifyArgument(
const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4233 indicatePessimisticFixpoint();
4234 if (
hasAttr({Attribute::InAlloca, Attribute::StructRet, Attribute::Nest},
4236 indicatePessimisticFixpoint();
4246 if (!MemAA.isAssumedReadOnly())
4247 return indicatePessimisticFixpoint();
4250 bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4263 if (ACS.isCallbackCall())
4264 if (
auto *
C = dyn_cast<Constant>(ArgOp))
4265 if (
C->isThreadDependent())
4267 return checkAndUpdate(A, *
this, *ArgOp, SimplifiedAssociatedValue);
4271 if (!askSimplifiedValueForAAValueConstantRange(A))
4272 return indicatePessimisticFixpoint();
4275 return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4281 void trackStatistics()
const override {
4286 struct AAValueSimplifyReturned : AAValueSimplifyImpl {
4287 AAValueSimplifyReturned(
const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4291 bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4293 auto PredForReturned = [&](
Value &V) {
4294 return checkAndUpdate(A, *
this, V, SimplifiedAssociatedValue);
4298 if (!askSimplifiedValueForAAValueConstantRange(A))
4299 return indicatePessimisticFixpoint();
4302 return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4307 void trackStatistics()
const override {
4312 struct AAValueSimplifyFloating : AAValueSimplifyImpl {
4313 AAValueSimplifyFloating(
const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4320 if (isa<Constant>(V))
4321 indicatePessimisticFixpoint();
4326 bool HasValueBefore = SimplifiedAssociatedValue.hasValue();
4330 if (!Stripped &&
this == &AA) {
4334 dbgs() <<
"[Attributor][ValueSimplify] Can't be stripped more : " 4338 return checkAndUpdate(A, *
this, V, SimplifiedAssociatedValue);
4341 if (!genericValueTraversal<AAValueSimplify, BooleanState>(
4342 A, getIRPosition(), *
this, static_cast<BooleanState &>(*
this),
4344 if (!askSimplifiedValueForAAValueConstantRange(A))
4345 return indicatePessimisticFixpoint();
4349 return HasValueBefore == SimplifiedAssociatedValue.hasValue()
4355 void trackStatistics()
const override {
4360 struct AAValueSimplifyFunction : AAValueSimplifyImpl {
4361 AAValueSimplifyFunction(
const IRPosition &IRP) : AAValueSimplifyImpl(IRP) {}
4366 indicateOptimisticFixpoint();
4371 "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
4374 void trackStatistics()
const override {
4379 struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
4380 AAValueSimplifyCallSite(
const IRPosition &IRP)
4381 : AAValueSimplifyFunction(IRP) {}
4383 void trackStatistics()
const override {
4388 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned {
4389 AAValueSimplifyCallSiteReturned(
const IRPosition &IRP)
4390 : AAValueSimplifyReturned(IRP) {}
4392 void trackStatistics()
const override {
4396 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
4397 AAValueSimplifyCallSiteArgument(
const IRPosition &IRP)
4398 : AAValueSimplifyFloating(IRP) {}
4400 void trackStatistics()
const override {
4409 const std::string getAsStr()
const override {
4414 assert(getState().isValidState() &&
4415 "Attempted to manifest an invalid state!");
4423 if (BadMallocCalls.count(MallocCall))
4426 for (
Instruction *FreeCall : FreesForMalloc[MallocCall]) {
4427 LLVM_DEBUG(
dbgs() <<
"H2S: Removing free call: " << *FreeCall <<
"\n");
4432 LLVM_DEBUG(
dbgs() <<
"H2S: Removing malloc call: " << *MallocCall
4437 auto *Num = cast<ConstantInt>(MallocCall->getOperand(0));
4439 APInt TotalSize = SizeT->getValue() * Num->getValue();
4443 Size = cast<ConstantInt>(MallocCall->getOperand(0));
4446 unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace();
4448 Size,
"", MallocCall->getNextNode());
4450 if (AI->
getType() != MallocCall->getType())
4456 if (
auto *II = dyn_cast<InvokeInst>(MallocCall)) {
4471 Type *Tys[] = {BI->
getType(), MallocCall->getOperand(0)->getType()};
4502 const auto &Frees = FreesForMalloc.lookup(&I);
4503 if (Frees.size() != 1)
4510 bool ValidUsesOnly =
true;
4511 bool MustUse =
true;
4512 auto Pred = [&](
const Use &U,
bool &Follow) ->
bool {
4514 if (isa<LoadInst>(UserI))
4516 if (
auto *SI = dyn_cast<StoreInst>(UserI)) {
4517 if (SI->getValueOperand() == U.
get()) {
4519 <<
"[H2S] escaping store to memory: " << *UserI <<
"\n");
4520 ValidUsesOnly =
false;
4526 if (
auto *CB = dyn_cast<CallBase>(UserI)) {
4532 FreesForMalloc[&
I].insert(UserI);
4534 LLVM_DEBUG(
dbgs() <<
"[H2S] free potentially on different mallocs: " 4536 ValidUsesOnly =
false;
4550 if (!NoCaptureAA.isAssumedNoCapture() ||
4551 !ArgNoFreeAA.isAssumedNoFree()) {
4553 ValidUsesOnly =
false;
4558 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) ||
4559 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) {
4560 MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI));
4567 ValidUsesOnly =
false;
4571 return ValidUsesOnly;
4575 if (BadMallocCalls.count(&I))
4580 if (!IsMalloc && !IsCalloc) {
4581 BadMallocCalls.insert(&I);
4588 if (UsesCheck(I) || FreeCheck(I)) {
4589 MallocCalls.insert(&I);
4592 }
else if (IsCalloc) {
4593 bool Overflow =
false;
4594 if (
auto *Num = dyn_cast<ConstantInt>(I.
getOperand(0)))
4596 if ((
Size->getValue().umul_ov(Num->getValue(), Overflow))
4598 if (!Overflow && (UsesCheck(I) || FreeCheck(I))) {
4599 MallocCalls.insert(&I);
4604 BadMallocCalls.insert(&I);
4608 size_t NumBadMallocs = BadMallocCalls.size();
4612 if (NumBadMallocs != BadMallocCalls.size())
4618 struct AAHeapToStackFunction final :
public AAHeapToStackImpl {
4619 AAHeapToStackFunction(
const IRPosition &IRP) : AAHeapToStackImpl(IRP) {}
4622 void trackStatistics()
const override {
4624 "Number of malloc calls converted to allocas");
4625 for (
auto *
C : MallocCalls)
4626 if (!BadMallocCalls.count(
C))
4639 intersectAssumedBits(BEST_STATE);
4640 getKnownStateFromValue(getIRPosition(), getState());
4645 static void getKnownStateFromValue(
const IRPosition &IRP,
4647 bool IgnoreSubsumingPositions =
false) {
4649 IRP.
getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions);
4651 switch (Attr.getKindAsEnum()) {
4652 case Attribute::ReadNone:
4655 case Attribute::ReadOnly:
4658 case Attribute::WriteOnly:
4678 if (isAssumedReadNone())
4680 else if (isAssumedReadOnly())
4682 else if (isAssumedWriteOnly())
4708 const std::string getAsStr()
const override {
4709 if (isAssumedReadNone())
4711 if (isAssumedReadOnly())
4713 if (isAssumedWriteOnly())
4715 return "may-read/write";
4723 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
4726 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
4727 AAMemoryBehaviorFloating(
const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {}
4741 void trackStatistics()
const override {
4742 if (isAssumedReadNone())
4744 else if (isAssumedReadOnly())
4746 else if (isAssumedWriteOnly())
4765 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
4766 AAMemoryBehaviorArgument(
const IRPosition &IRP)
4767 : AAMemoryBehaviorFloating(IRP) {}
4771 intersectAssumedBits(BEST_STATE);
4777 IRP.
hasAttr({Attribute::ByVal},
true);
4778 getKnownStateFromValue(IRP, getState(),
4784 indicatePessimisticFixpoint();
4787 for (
const Use &U : Arg->
uses())
4795 if (
hasAttr({Attribute::InAlloca})) {
4796 removeKnownBits(NO_WRITES);
4797 removeAssumedBits(NO_WRITES);
4799 return AAMemoryBehaviorFloating::manifest(A);
4803 void trackStatistics()
const override {
4804 if (isAssumedReadNone())
4806 else if (isAssumedReadOnly())
4808 else if (isAssumedWriteOnly())
4813 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
4814 AAMemoryBehaviorCallSiteArgument(
const IRPosition &IRP)
4815 : AAMemoryBehaviorArgument(IRP) {}
4820 if (
Arg->hasByValAttr()) {
4821 addKnownBits(NO_WRITES);
4822 removeKnownBits(NO_READS);
4823 removeAssumedBits(NO_READS);
4839 return clampStateAndIndicateChange(
4841 static_cast<const AAMemoryBehavior::StateType &>(ArgAA.getState()));
4845 void trackStatistics()
const override {
4846 if (isAssumedReadNone())
4848 else if (isAssumedReadOnly())
4850 else if (isAssumedWriteOnly())
4856 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
4857 AAMemoryBehaviorCallSiteReturned(
const IRPosition &IRP)
4858 : AAMemoryBehaviorFloating(IRP) {}
4867 void trackStatistics()
const override {}
4871 struct AAMemoryBehaviorFunction final :
public AAMemoryBehaviorImpl {
4872 AAMemoryBehaviorFunction(
const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {}
4880 if (isAssumedReadNone()) {
4883 F.
removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly);
4885 return AAMemoryBehaviorImpl::manifest(A);
4889 void trackStatistics()
const override {
4890 if (isAssumedReadNone())
4892 else if (isAssumedReadOnly())
4894 else if (isAssumedWriteOnly())
4900 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl {
4901 AAMemoryBehaviorCallSite(
const IRPosition &IRP) : AAMemoryBehaviorImpl(IRP) {}
4908 indicatePessimisticFixpoint();
4920 return clampStateAndIndicateChange(
4922 static_cast<const AAMemoryBehavior::StateType &>(FnAA.getState()));
4926 void trackStatistics()
const override {
4927 if (isAssumedReadNone())
4929 else if (isAssumedReadOnly())
4931 else if (isAssumedWriteOnly())
4940 auto AssumedState = getAssumed();
4949 intersectAssumedBits(MemBehaviorAA.getAssumed());
4950 return !isAtFixpoint();
4954 if (
I.mayReadFromMemory())
4955 removeAssumedBits(NO_READS);
4956 if (
I.mayWriteToMemory())
4957 removeAssumedBits(NO_WRITES);
4958 return !isAtFixpoint();
4962 return indicatePessimisticFixpoint();
4979 AAMemoryBehavior::StateType::getWorstState();
4983 S.addKnownBits(FnMemAA.getKnown());
4984 if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed())
4994 if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) {
4995 S.intersectAssumedBits(FnMemAssumedState);
5000 auto AssumedState = S.getAssumed();
5008 for (
unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) {
5009 const Use *U = Uses[i];
5010 Instruction *UserI = cast<Instruction>(U->getUser());
5011 LLVM_DEBUG(
dbgs() <<
"[AAMemoryBehavior] Use: " << **U <<
" in " << *UserI
5012 <<
" [Dead: " << (LivenessAA.isAssumedDead(UserI))
5014 if (LivenessAA.isAssumedDead(UserI))
5018 if (followUsersOfUseIn(A, U, UserI))
5019 for (
const Use &UserIUse : UserI->
uses())
5020 Uses.insert(&UserIUse);
5024 analyzeUseIn(A, U, UserI);
5031 bool AAMemoryBehaviorFloating::followUsersOfUseIn(
Attributor &A,
const Use *U,
5035 if (isa<LoadInst>(UserI))
5051 const auto &ArgNoCaptureAA =
5056 void AAMemoryBehaviorFloating::analyzeUseIn(
Attributor &A,
const Use *U,
5066 removeAssumedBits(NO_READS);
5074 removeAssumedBits(NO_WRITES);
5078 case Instruction::CallBr:
5079 case Instruction::Invoke: {
5086 indicatePessimisticFixpoint();
5093 removeAssumedBits(NO_READS);
5104 intersectAssumedBits(MemBehaviorAA.getAssumed());
5112 removeAssumedBits(NO_READS);
5114 removeAssumedBits(NO_WRITES);
5127 getKnown().print(OS);
5129 getAssumed().print(OS);
5168 const SCEV *S = getSCEV(A,
I);
5190 const_cast<BasicBlock *>(CtxI->getParent()),
5191 const_cast<Instruction *>(CtxI));
5197 const Instruction *CtxI =
nullptr)
const override {
5198 if (!CtxI || CtxI ==
getCtxI())
5203 return getKnown().intersectWith(SCEVR).intersectWith(LVIR);
5209 const Instruction *CtxI =
nullptr)
const override {
5215 if (!CtxI || CtxI ==
getCtxI())
5216 return getAssumed();
5220 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
5226 intersectKnown(getConstantRangeFromSCEV(A,
getCtxI()));
5229 intersectKnown(getConstantRangeFromLVI(A,
getCtxI()));
5237 Ty, AssumedConstantRange.
getLower())),
5239 Ty, AssumedConstantRange.
getUpper()))};
5261 mdconst::extract<ConstantInt>(KnownRanges->
getOperand(0));
5263 mdconst::extract<ConstantInt>(KnownRanges->
getOperand(1));
5266 return Known.
contains(Assumed) && Known != Assumed;
5273 auto *OldRangeMD = I->
getMetadata(LLVMContext::MD_range);
5274 if (isBetterRange(AssumedConstantRange, OldRangeMD)) {
5278 AssumedConstantRange));
5288 ConstantRange AssumedConstantRange = getAssumedConstantRange(A);
5295 if (isa<CallInst>(
I) || isa<LoadInst>(
I))
5296 if (setRangeMetadataIfisBetterRange(
I, AssumedConstantRange))
5314 clampCallSiteArgumentStates<AAValueConstantRange, IntegerRangeState>(
5319 return clampStateAndIndicateChange<IntegerRangeState>(this->getState(), S);
5341 clampReturnedValueStates<AAValueConstantRange, IntegerRangeState>(A, *
this,
5343 return clampStateAndIndicateChange<StateType>(this->getState(), S);
5361 if (
auto *
C = dyn_cast<ConstantInt>(&V)) {
5363 indicateOptimisticFixpoint();
5367 if (isa<UndefValue>(&V)) {
5368 indicateOptimisticFixpoint();
5372 if (
auto *
I = dyn_cast<Instruction>(&V))
5373 if (isa<BinaryOperator>(
I) || isa<CmpInst>(
I)) {
5374 Value *LHS =
I->getOperand(0);
5375 Value *RHS =
I->getOperand(1);
5382 if (
LoadInst *LI = dyn_cast<LoadInst>(&V))
5383 if (
auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
5389 indicatePessimisticFixpoint();
5391 LLVM_DEBUG(
dbgs() <<
"[Attributor][AAValueConstantRange] We give up: " 5408 auto AssumedRange = LHSAARange.binaryOp(BinOp->
getOpcode(), RHSAARange);
5431 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
5434 bool MustTrue =
false, MustFalse =
false;
5436 auto AllowedRegion =
5442 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
5445 if (SatisfyingRegion.contains(LHSAARange))
5448 assert((!MustTrue || !MustFalse) &&
5449 "Either MustTrue or MustFalse should be false!");
5458 LLVM_DEBUG(
dbgs() <<
"[AAValueConstantRange] " << *CmpI <<
" " << LHSAA
5459 <<
" " << RHSAA <<
"\n");
5469 bool Stripped) ->
bool {
5480 return T.isValidState();
5483 if (
auto *BinOp = dyn_cast<BinaryOperator>(I))
5484 return calculateBinaryOperator(A, BinOp, T, CtxI);
5485 else if (
auto *CmpI = dyn_cast<CmpInst>(I))
5486 return calculateCmpInst(A, CmpI, T, CtxI);
5491 T.indicatePessimisticFixpoint();
5498 if (!genericValueTraversal<AAValueConstantRange, IntegerRangeState>(
5499 A, getIRPosition(), *
this, T, VisitValueCB))
5500 return indicatePessimisticFixpoint();
5502 return clampStateAndIndicateChange(getState(), T);
5517 llvm_unreachable(
"AAValueConstantRange(Function|CallSite)::updateImpl will " 5541 if (
auto *RangeMD = CI->getMetadata(LLVMContext::MD_range))
5579 if (&AA == LivenessAA)
5602 <<
" initial uses to check\n");
5604 if (Worklist.
empty())
5607 bool AnyDead =
false;
5609 const auto *LivenessAA =
5614 while (!Worklist.
empty()) {
5616 if (!Visited.
insert(U).second)
5619 if (
Instruction *UserI = dyn_cast<Instruction>(U->getUser()))
5620 if (LivenessAA && LivenessAA->isAssumedDead(UserI)) {
5621 LLVM_DEBUG(
dbgs() <<
"[Attributor] Dead user: " << *UserI <<
": " 5622 << *LivenessAA <<
"\n");
5627 bool Follow =
false;
5628 if (!Pred(*U, Follow))
5632 for (
const Use &UU : U->getUser()->
uses())
5650 if (!AssociatedFunction) {
5651 LLVM_DEBUG(
dbgs() <<
"[Attributor] No function associated with " << IRP
5656 return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
5666 <<
"[Attributor] Function " << Fn.
getName()
5667 <<
" has no internal linkage, hence not all call sites are known\n");
5671 for (
const Use &U : Fn.
uses()) {
5675 <<
" has non call site use " << *U.
get() <<
" in " 5678 if (isa<BlockAddress>(U.
getUser()))
5686 const auto *LivenessAA =
5691 if (LivenessAA && LivenessAA->isAssumedDead(I)) {
5699 const Use *EffectiveUse =
5702 if (!RequireAllCallSites)
5704 LLVM_DEBUG(
dbgs() <<
"[Attributor] User " << EffectiveUse->getUser()
5705 <<
" is an invalid use of " << Fn.
getName() <<
"\n");
5712 LLVM_DEBUG(
dbgs() <<
"[Attributor] Call site callback failed for " 5729 if (!AssociatedFunction)
5736 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
5737 if (!AARetVal.getState().isValidState())
5740 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
5749 if (!AssociatedFunction)
5754 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP);
5755 if (!AARetVal.getState().isValidState())
5758 return AARetVal.checkForAllReturnedValuesAndReturnInsts(
5767 const AAIsDead *LivenessAA,
bool &AnyDead,
5769 for (
unsigned Opcode : Opcodes) {
5791 if (!AssociatedFunction)
5796 const auto &LivenessAA =
5797 getAAFor<AAIsDead>(QueryingAA, QueryIRP,
false);
5798 bool AnyDead =
false;
5800 auto &OpcodeInstMap =
5801 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction);
5817 const Function *AssociatedFunction =
5819 if (!AssociatedFunction)
5824 const auto &LivenessAA =
5825 getAAFor<AAIsDead>(QueryingAA, QueryIRP,
false);
5826 bool AnyDead =
false;
5829 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
5831 if (LivenessAA.isAssumedDead(
I)) {
5849 << AllAbstractAttributes.size()
5850 <<
" abstract attributes.\n");
5855 unsigned IterationCounter = 1;
5859 Worklist.
insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end());
5861 bool RecomputeDependences =
false;
5865 size_t NumAAs = AllAbstractAttributes.size();
5866 LLVM_DEBUG(
dbgs() <<
"\n\n[Attributor] #Iteration: " << IterationCounter
5867 <<
", Worklist size: " << Worklist.
size() <<
"\n");
5872 for (
unsigned u = 0; u < InvalidAAs.
size(); ++u) {
5874 auto &QuerriedAAs = QueryMap[InvalidAA];
5875 LLVM_DEBUG(
dbgs() <<
"[Attributor] InvalidAA: " << *InvalidAA <<
" has " 5876 << QuerriedAAs.RequiredAAs.size() <<
"/" 5877 << QuerriedAAs.OptionalAAs.size()
5878 <<
" required/optional dependences\n");
5882 ++NumAttributesFixedDueToRequiredDependences;
5885 InvalidAAs.
insert(DepOnInvalidAA);
5887 if (!RecomputeDependences)
5888 Worklist.
insert(QuerriedAAs.OptionalAAs.begin(),
5889 QuerriedAAs.OptionalAAs.end());
5894 if (RecomputeDependences) {
5896 dbgs() <<
"[Attributor] Run all AAs to recompute dependences\n");
5899 Worklist.
insert(AllAbstractAttributes.begin(),
5900 AllAbstractAttributes.end());
5906 auto &QuerriedAAs = QueryMap[ChangedAA];
5907 Worklist.
insert(QuerriedAAs.OptionalAAs.begin(),
5908 QuerriedAAs.OptionalAAs.end());
5909 Worklist.
insert(QuerriedAAs.RequiredAAs.begin(),
5910 QuerriedAAs.RequiredAAs.end());
5913 LLVM_DEBUG(
dbgs() <<
"[Attributor] #Iteration: " << IterationCounter
5914 <<
", Worklist+Dependent size: " << Worklist.
size()
5924 if (!AA->getState().isAtFixpoint() && !isAssumedDead(*AA,
nullptr)) {
5925 QueriedNonFixAA =
false;
5927 ChangedAAs.push_back(AA);
5928 if (!AA->getState().isValidState())
5930 }
else if (!QueriedNonFixAA) {
5933 AA->getState().indicateOptimisticFixpoint();
5938 RecomputeDependences = (DepRecomputeInterval > 0 &&
5939 IterationCounter % DepRecomputeInterval == 0);
5943 ChangedAAs.append(AllAbstractAttributes.begin() + NumAAs,
5944 AllAbstractAttributes.end());
5949 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
5954 LLVM_DEBUG(
dbgs() <<
"\n[Attributor] Fixpoint iteration done after: " 5956 <<
" iterations\n");
5958 size_t NumFinalAAs = AllAbstractAttributes.size();
5966 for (
unsigned u = 0; u < ChangedAAs.
size(); u++) {
5968 if (!Visited.
insert(ChangedAA).second)
5975 NumAttributesTimedOut++;
5978 auto &QuerriedAAs = QueryMap[ChangedAA];
5979 ChangedAAs.
append(QuerriedAAs.OptionalAAs.begin(),
5980 QuerriedAAs.OptionalAAs.end());
5981 ChangedAAs.
append(QuerriedAAs.RequiredAAs.begin(),
5982 QuerriedAAs.RequiredAAs.end());
5986 if (!Visited.
empty())
5987 dbgs() <<
"\n[Attributor] Finalized " << Visited.
size()
5988 <<
" abstract attributes.\n";
5991 unsigned NumManifested = 0;
5992 unsigned NumAtFixpoint = 0;
6009 if (isAssumedDead(*AA,
nullptr))
6014 AA->trackStatistics();
6016 ManifestChange = ManifestChange | LocalChange;
6022 (void)NumManifested;
6023 (void)NumAtFixpoint;
6024 LLVM_DEBUG(
dbgs() <<
"\n[Attributor] Manifested " << NumManifested
6025 <<
" arguments while " << NumAtFixpoint
6026 <<
" were in a valid fixpoint state\n");
6028 NumAttributesManifested += NumManifested;
6029 NumAttributesValidFixpoint += NumAtFixpoint;
6033 NumFinalAAs == AllAbstractAttributes.size() &&
6034 "Expected the final number of abstract attributes to remain unchanged!");
6039 << ToBeDeletedFunctions.size() <<
" functions and " 6040 << ToBeDeletedBlocks.size() <<
" blocks and " 6041 << ToBeDeletedInsts.size() <<
" instructions and " 6042 << ToBeChangedUses.size() <<
" uses\n");
6047 for (
auto &It : ToBeChangedUses) {
6049 Value *NewV = It.second;
6050 Value *OldV = U->get();
6052 <<
" instead of " << *OldV <<
"\n");
6055 if (!isa<PHINode>(
I) && !ToBeDeletedInsts.count(
I) &&
6057 DeadInsts.push_back(
I);
6059 if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) {
6060 Instruction *UserI = cast<Instruction>(U->getUser());
6061 if (isa<UndefValue>(NewV)) {
6062 ToBeChangedToUnreachableInsts.insert(UserI);
6068 for (
auto &V : InvokeWithDeadSuccessor)
6069 if (
InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
6070 bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
6071 bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
6072 bool Invoke2CallAllowed =
6073 !AAIsDeadFunction::mayCatchAsynchronousExceptions(
6074 *II->getFunction());
6075 assert((UnwindBBIsDead || NormalBBIsDead) &&
6076 "Invoke does not have dead successors!");
6078 BasicBlock *NormalDestBB = II->getNormalDest();
6079 if (UnwindBBIsDead) {
6081 if (Invoke2CallAllowed) {
6086 ToBeChangedToUnreachableInsts.insert(NormalNextIP);
6088 assert(NormalBBIsDead &&
"Broken invariant!");
6091 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->
front());
6094 for (
auto &V : ToBeChangedToUnreachableInsts)
6103 DeadInsts.push_back(
I);
6105 I->eraseFromParent();
6110 if (
unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
6112 ToBeDeletedBBs.
reserve(NumDeadBlocks);
6113 ToBeDeletedBBs.
append(ToBeDeletedBlocks.begin(), ToBeDeletedBlocks.end());
6128 if (
F.hasLocalLinkage())
6131 bool FoundDeadFn =
true;
6132 while (FoundDeadFn) {
6133 FoundDeadFn =
false;
6134 for (
unsigned u = 0,
e = InternalFns.
size(); u <
e; ++u) {
6139 if (!checkForAllCallSites(
6141 return ToBeDeletedFunctions.count(
6147 ToBeDeletedFunctions.
insert(F);
6148 InternalFns[u] =
nullptr;
6158 ManifestChange = ManifestChange | rewriteFunctionSignatures();
6160 for (
Function *Fn : ToBeDeletedFunctions) {
6168 errs() <<
"\n[Attributor] Fixpoint iteration done after: " 6171 llvm_unreachable(
"The fixpoint was not reached with exactly the number of " 6172 "specified iterations!");
6175 return ManifestChange;
6185 return !ACS.isCallbackCall() && !ACS.getCallSite().isMustTailCall();
6191 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite var-args functions\n");
6201 dbgs() <<
"[Attributor] Cannot rewrite due to complex attribute\n");
6206 if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn,
true,
nullptr)) {
6207 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite all call sites\n");
6212 if (
auto *CI = dyn_cast<CallInst>(&
I))
6213 return !CI->isMustTailCall();
6220 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
6223 LLVM_DEBUG(
dbgs() <<
"[Attributor] Cannot rewrite due to instructions\n");
6228 if (ARIs.
size() == 0)
6235 LLVM_DEBUG(
dbgs() <<
"[Attributor] Existing rewrite is preferred\n");
6246 std::move(CalleeRepairCB),
6247 std::move(ACSRepairCB));
6255 for (
auto &It : ArgumentReplacementMap) {
6259 if (ToBeDeletedFunctions.count(OldFn))
6272 NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
6273 ARI->ReplacementTypes.end());
6274 NewArgumentAttributes.
append(ARI->getNumReplacementArgs(),
6277 NewArgumentTypes.push_back(
Arg.getType());
6292 << *NewFnTy <<
"\n");
6298 NewFn->takeName(OldFn);
6299 NewFn->copyAttributesFrom(OldFn);
6315 NewFn->getBasicBlockList().splice(NewFn->begin(),
6324 CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
6330 for (
unsigned OldArgNum = 0; OldArgNum < ARIs.
size(); ++OldArgNum) {
6331 unsigned NewFirstArgNum = NewArgOperands.
size();
6332 (void)NewFirstArgNum;
6334 if (ARI->ACSRepairCB)
6335 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
6336 assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
6337 NewArgOperands.
size() &&
6338 "ACS repair callback did not provide as many operand as new " 6339 "types were registered!");
6341 NewArgOperandAttributes.
append(ARI->ReplacementTypes.size(),
6344 NewArgOperands.
push_back(ACS.getCallArgOperand(OldArgNum));
6346 OldCallAttributeList.getParamAttributes(OldArgNum));
6350 assert(NewArgOperands.
size() == NewArgOperandAttributes.
size() &&
6351 "Mismatch # argument operands vs. # argument operand attributes!");
6352 assert(NewArgOperands.
size() == NewFn->arg_size() &&
6353 "Mismatch # argument operands vs. # function arguments!");
6360 if (
InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
6363 NewArgOperands, OperandBundleDefs,
"", OldCB);
6367 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
6379 Ctx, OldCallAttributeList.getFnAttributes(),
6380 OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes));
6382 CallSitePairs.
push_back({OldCB, NewCB});
6388 checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
true,
nullptr);
6390 assert(Success &&
"Assumed call site replacement to succeed!");
6394 auto NewFnArgIt = NewFn->arg_begin();
6395 for (
unsigned OldArgNum = 0; OldArgNum < ARIs.
size();
6396 ++OldArgNum, ++OldFnArgIt) {
6398 if (ARI->CalleeRepairCB)
6399 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
6400 NewFnArgIt += ARI->ReplacementTypes.size();
6402 NewFnArgIt->
takeName(&*OldFnArgIt);
6403 OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
6409 for (
auto &CallSitePair : CallSitePairs) {
6410 CallBase &OldCB = *CallSitePair.first;
6411 CallBase &NewCB = *CallSitePair.second;
6416 ToBeDeletedFunctions.
insert(OldFn);
6429 auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&
F];
6430 auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&
F];
6433 bool IsInterestingOpcode =
false;
6440 switch (
I.getOpcode()) {
6443 "New call site/base instruction type needs to be known int the " 6451 case Instruction::CallBr:
6452 case Instruction::Invoke:
6453 case Instruction::CleanupRet:
6454 case Instruction::CatchSwitch:
6455 case Instruction::AtomicRMW:
6456 case Instruction::AtomicCmpXchg:
6457 case Instruction::Br:
6458 case Instruction::Resume:
6460 IsInterestingOpcode =
true;
6462 if (IsInterestingOpcode)
6463 InstOpcodeMap[
I.getOpcode()].push_back(&
I);
6464 if (
I.mayReadOrWriteMemory())
6465 ReadOrWriteInsts.push_back(&
I);
6476 QueryMap[&FromAA].RequiredAAs.insert(
6477 const_cast<AbstractAttribute *>(&ToAA));
6479 QueryMap[&FromAA].OptionalAAs.insert(
6480 const_cast<AbstractAttribute *>(&ToAA));
6481 QueriedNonFixAA =
true;
6485 if (!VisitedFunctions.insert(&F).second)
6495 getOrCreateAAFor<AAIsDead>(FPos);
6498 getOrCreateAAFor<AAWillReturn>(FPos);
6501 getOrCreateAAFor<AAUndefinedBehavior>(FPos);
6504 getOrCreateAAFor<AANoUnwind>(FPos);
6507 getOrCreateAAFor<AANoSync>(FPos);
6510 getOrCreateAAFor<AANoFree>(FPos);
6513 getOrCreateAAFor<AANoReturn>(FPos);
6516 getOrCreateAAFor<AANoRecurse>(FPos);
6519 getOrCreateAAFor<AAMemoryBehavior>(FPos);
6523 getOrCreateAAFor<AAHeapToStack>(FPos);
6527 if (!ReturnType->isVoidTy()) {
6530 getOrCreateAAFor<AAReturnedValues>(FPos);
6535 getOrCreateAAFor<AAIsDead>(RetPos);
6538 getOrCreateAAFor<AAValueSimplify>(RetPos);
6540 if (ReturnType->isPointerTy()) {
6543 getOrCreateAAFor<AAAlign>(RetPos);
6546 getOrCreateAAFor<AANonNull>(RetPos);
6549 getOrCreateAAFor<AANoAlias>(RetPos);
6553 getOrCreateAAFor<AADereferenceable>(RetPos);
6561 getOrCreateAAFor<AAValueSimplify>(ArgPos);
6563 if (
Arg.getType()->isPointerTy()) {
6565 getOrCreateAAFor<AANonNull>(ArgPos);
6568 getOrCreateAAFor<AANoAlias>(ArgPos);
6571 getOrCreateAAFor<AADereferenceable>(ArgPos);
6574 getOrCreateAAFor<AAAlign>(ArgPos);
6577 getOrCreateAAFor<AANoCapture>(ArgPos);
6581 getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
6584 getOrCreateAAFor<AANoFree>(ArgPos);
6594 !
Callee->hasMetadata(LLVMContext::MD_callback))
6597 if (!
Callee->getReturnType()->isVoidTy() && !CS->use_empty()) {
6602 getOrCreateAAFor<AAIsDead>(CSRetPos);
6605 if (
Callee->getReturnType()->isIntegerTy()) {
6606 getOrCreateAAFor<AAValueConstantRange>(CSRetPos);
6615 getOrCreateAAFor<AAIsDead>(CSArgPos);
6618 getOrCreateAAFor<AAValueSimplify>(CSArgPos);
6624 getOrCreateAAFor<AANonNull>(CSArgPos);
6627 getOrCreateAAFor<AANoAlias>(CSArgPos);
6630 getOrCreateAAFor<AADereferenceable>(CSArgPos);
6633 getOrCreateAAFor<AAAlign>(CSArgPos);
6637 getOrCreateAAFor<AAMemoryBehavior>(CSArgPos);
6640 getOrCreateAAFor<AANoFree>(CSArgPos);
6646 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
6647 bool Success, AnyDead =
false;
6649 OpcodeInstMap, CallSitePred,
nullptr, AnyDead,
6650 {(
unsigned)Instruction::Invoke, (
unsigned)Instruction::CallBr,
6653 assert(Success && !AnyDead &&
"Expected the check call to be successful!");
6656 if (isa<LoadInst>(
I))
6657 getOrCreateAAFor<AAAlign>(
6660 getOrCreateAAFor<AAAlign>(
6665 OpcodeInstMap, LoadStorePred,
nullptr, AnyDead,
6668 assert(Success && !AnyDead &&
"Expected the check call to be successful!");
6685 return OS <<
"fn_ret";
6687 return OS <<
"cs_ret";
6695 return OS <<
"cs_arg";
6706 template <
typename base_ty, base_ty BestState, base_ty WorstState>
6721 return OS << static_cast<const AbstractState &>(S);
6734 OS <<
"[P: " << getIRPosition() <<
"][" << getAsStr() <<
"][S: " << getState()
6748 <<
" functions.\n");
6759 if (
F.hasExactDefinition())
6760 NumFnWithExactDefinition++;
6762 NumFnWithoutExactDefinition++;
6766 if (
F.hasLocalLinkage()) {
6795 struct AttributorLegacyPass :
public ModulePass {
6802 bool runOnModule(
Module &M)
override {
6845 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 6846 case IRPosition::PK: \ 6847 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 6849 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 6850 case IRPosition::PK: \ 6851 AA = new CLASS##SUFFIX(IRP); \ 6854 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 6855 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 6856 CLASS *AA = nullptr; \ 6857 switch (IRP.getPositionKind()) { \ 6858 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 6859 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 6860 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 6861 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 6862 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 6863 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 6864 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 6865 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 6870 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 6871 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 6872 CLASS *AA = nullptr; \ 6873 switch (IRP.getPositionKind()) { \ 6874 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 6875 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 6876 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 6877 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 6878 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 6879 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 6880 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 6881 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 6886 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 6887 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 6888 CLASS *AA = nullptr; \ 6889 switch (IRP.getPositionKind()) { \ 6890 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 6891 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 6892 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 6893 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 6894 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 6895 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 6896 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 6897 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 6902 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 6903 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 6904 CLASS *AA = nullptr; \ 6905 switch (IRP.getPositionKind()) { \ 6906 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 6907 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 6908 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 6909 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 6910 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 6911 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 6912 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 6913 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 6918 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 6919 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 6920 CLASS *AA = nullptr; \ 6921 switch (IRP.getPositionKind()) { \ 6922 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 6923 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 6924 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 6925 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 6926 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 6927 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 6928 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 6929 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 6958 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION 6959 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 6960 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION 6961 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 6962 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION 6963 #undef SWITCH_PK_CREATE 6964 #undef SWITCH_PK_INV 6967 "Deduce and propagate attributes",
false,
false)
An attribute for a call site return value.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Pass interface - Implemented by all 'passes'.
Instruction * getCtxI() const
Return the context instruction, if any.
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
bool onlyReadsMemory() const
Determine if the function does not access or only reads memory.
static const char ID
Unique ID (due to the unique address)
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
reference emplace_back(ArgTypes &&... Args)
This class is the base class for the comparison instructions.
AAValueConstantRangeCallSiteArgument(const IRPosition &IRP)
iterator_range< use_iterator > uses()
StringRef getKindAsString() const
Return the attribute's kind as a string.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static IntegerType * getInt1Ty(LLVMContext &C)
unsigned getIndexSizeInBits(unsigned AS) const
Size in bits of index used for address calculation in getelementptr.
static bool isEqualOrWorse(const Attribute &New, const Attribute &Old)
Return true if New is equal or worse than Old.
bool hasLocalLinkage() const
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset...
static const Value * getPointerOperand(const Instruction *I, bool AllowVolatile)
Get pointer operand of memory accessing instruction.
int getCallArgOperandNo(Argument &Arg) const
Return the operand index of the underlying instruction associated with Arg.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
This class represents an incoming formal argument to a Function.
ConstantRange getConstantRange(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
Return the ConstantRange constraint that is known to hold for the specified value at the end of the s...
This callback is used in conjunction with PointerMayBeCaptured.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
std::function< void(const ArgumentReplacementInfo &, Function &, Function::arg_iterator)> CalleeRepairCBTy
Callee repair callback type.
This class represents lattice values for constants.
bool isValidState() const override
See AbstractState::isValidState()
BinaryOps getOpcode() const
const APInt & getUpper() const
Return the upper value for this range.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
size_type size() const
Determine the number of elements in the SetVector.
This is the interface for a simple mod/ref and alias analysis over globals.
SubsumingPositionIterator(const IRPosition &IRP)
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
ChangeStatus updateImpl(Attributor &A) override
See AbstractAttribute::updateImpl(...).
static Attribute getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes)
ChangeStatus
Simple enum classes that forces properties to be spelled out explicitly.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Specialization of the integer state for a bit-wise encoding.
virtual void print(raw_ostream &OS) const
Helper functions, for debug purposes only.
A position that is not associated with a spot suitable for attributes.
ChangeStatus updateImpl(Attributor &A) override
See AbstractAttribute::updateImpl(...).
void initialize(Attributor &A) override
See AbstractAttribute::initialize(..).
Implements a dense probed hash-table based set.
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
AAValueConstantRangeFloating(const IRPosition &IRP)
void push_back(const T &Elt)
void setProfWeight(uint64_t W)
Sets the branch_weights metadata to W for CallInst.
static const char ID
Unique ID (due to the unique address)
bool isArgOperand(const Use *U) const
The main scalar evolution driver.
static const char ID
Unique ID (due to the unique address)
An abstract interface for all nocapture attributes.
This class represents a function call, abstracting a target machine's calling convention.
iterator & end()
Return an universal end iterator.
ConstantRange getAssumed() const
Return the assumed state encoding.
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
unsigned constexpr DefaultMaxUsesToExplore
The default value for MaxUsesToExplore argument.
Abstract Attribute Classes
Value * getCondition() const
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
The two locations do not alias at all.
static cl::opt< bool > VerifyMaxFixpointIterations("attributor-max-iterations-verify", cl::Hidden, cl::desc("Verify that max-iterations is a tight bound for a fixpoint"), cl::init(false))
An efficient, type-erasing, non-owning reference to a callable.
static MDNode * getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx, const ConstantRange &AssumedConstantRange)
Helper function to create MDNode for range metadata.
static const char ID
Unique ID (due to the unique address)
An attribute for a call site argument.
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
bool isAssumedNoReturn() const
Return true if the underlying object is assumed to never return.
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
virtual const IRPosition & getIRPosition() const =0
Return an IR position, see struct IRPosition.
AAValueConstantRangeImpl(const IRPosition &IRP)
const Use & getOperandUse(unsigned i) const
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
bool isAssumedNoRecurse() const
Return true if "norecurse" is assumed.
An abstract attribute for willreturn.
STATISTIC(NumFunctions, "Total number of functions")
APInt operator &(APInt a, const APInt &b)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Analysis pass which computes a DominatorTree.
const MDOperand & getOperand(unsigned I) const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
bool registerFunctionSignatureRewrite(Argument &Arg, ArrayRef< Type *> ReplacementTypes, ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB)
Register a rewrite for a function signature.
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
void reserve(size_type N)
Synchronized with respect to signal handlers executing in the same thread.
Kind
The positions we distinguish in the IR.
Wrapper for FunctoinAnalysisManager.
bool hasByValAttr() const
Return true if this argument has the byval attribute.
void print(raw_ostream &OS) const
Print out the bounds to a stream.
void initialize(Attributor &A) override
See AbstractAttribute::initialize(...).
bool checkForAllUses(const function_ref< bool(const Use &, bool &)> &Pred, const AbstractAttribute &QueryingAA, const Value &V)
Check Pred on all (transitive) uses of V.
virtual ChangeStatus indicatePessimisticFixpoint()=0
Indicate that the abstract state should converge to the pessimistic state.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
ConstantRange getConstantRangeFromLVI(Attributor &A, const Instruction *CtxI=nullptr) const
Helper function to get a range from LVI for the associated value at program point I...
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
bool checkForAllCallSites(const function_ref< bool(AbstractCallSite)> &Pred, const AbstractAttribute &QueryingAA, bool RequireAllCallSites)
Check Pred on all function call sites.
static bool setRangeMetadataIfisBetterRange(Instruction *I, const ConstantRange &AssumedConstantRange)
Helper function to set range metadata.
virtual bool isDereferenceableOrNull(Value *O, const DataLayout &DL)
isDereferenceableOrNull - Overload to allow clients with additional knowledge about pointer dereferen...
AAValueConstantRangeReturned(const IRPosition &IRP)
void initializeInformationCache(Function &F)
Initialize the information cache for queries regarding function F.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static const IRPosition function_scope(const IRPosition &IRP)
Create a position with function scope matching the "context" of IRP.
bool isAssumedDead(const AbstractAttribute &AA, const AAIsDead *LivenessAA)
Return true if AA (or its context instruction) is assumed dead.
BitIntegerState & removeAssumedBits(base_t BitsEncoding)
Remove the bits in BitsEncoding from the "assumed bits" if not known.
Type * getPointerElementType() const
An AbstractAttribute for noreturn.
uint64_t getValueAsInt() const
Return the attribute's value as an integer.
A visitor class for IR positions.
bool isStringAttribute() const
Return true if the attribute is a string (target-dependent) attribute.
base_t getAssumed() const
Return the assumed state encoding.
'undef' values are things that do not have specified contents.
bool isKnownNoReturn() const
Return true if the underlying object is known to never return.
unsigned getNumSuccessors() const
static const char ID
Unique ID (due to the unique address)
A Use represents the edge between a Value definition and its users.
static Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
An abstract attribute for norecurse.
static Attribute getWithDereferenceableOrNullBytes(LLVMContext &Context, uint64_t Bytes)
#define STATS_DECLTRACK_ARG_ATTR(NAME)
unsigned getArgumentNo(Value::const_user_iterator I) const
Given a value use iterator, returns the argument that corresponds to it.
This file contains the simple types necessary to represent the attributes associated with functions a...
bool isAssumedNoUnwind() const
Returns true if nounwind is assumed.
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
check if an attributes is in the list of attributes.
#define STATS_DECLTRACK_CSARG_ATTR(NAME)
bool canSimplifyInvokeNoUnwind(const Function *F)
Analysis pass that exposes the LoopInfo for a function.
static cl::opt< unsigned > MaxFixpointIterations("attributor-max-iterations", cl::Hidden, cl::desc("Maximal number of fixpoint iterations."), cl::init(32))
static const char ID
Unique ID (due to the unique address)
An abstract interface for all noalias attributes.
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
bool checkForAllReadWriteInstructions(const llvm::function_ref< bool(Instruction &)> &Pred, AbstractAttribute &QueryingAA)
Check Pred on all Read/Write instructions.
AtomicOrdering
Atomic ordering for LLVM's memory model.
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
An attribute for the function return value.
InstrTy * getInstruction() const
uint32_t getAssumedDereferenceableBytes() const
Return assumed dereferenceable bytes.
State for an integer range.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
int64_t getSExtValue() const
Get sign extended value.
int getArgNo() const
Return the argument number of the associated value if it is an argument or call site argument...
Type * getType() const
All values are typed, get the type of this value.
static cl::opt< bool > ManifestInternal("attributor-manifest-internal", cl::Hidden, cl::desc("Manifest Attributor internal string attributes."), cl::init(false))
bool insert(const value_type &X)
Insert a new element into the SetVector.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
An abstract interface for liveness abstract attribute.
bool checkForAllReturnedValuesAndReturnInsts(const function_ref< bool(Value &, const SmallSetVector< ReturnInst *, 4 > &)> &Pred, const AbstractAttribute &QueryingAA)
Check Pred on all values potentially returned by F.
const T & getValue() const LLVM_LVALUE_FUNCTION
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
bool isAssumedNoFree() const
Return true if "nofree" is assumed.
This class represents a no-op cast from one type to another.
void initializeAttributorLegacyPassPass(PassRegistry &)
ChangeStatus run(Module &M)
Run the analyses until a fixpoint is reached or enforced (timeout).
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringLiteral > StandardNames)
Initialize the set of available library functions based on the specified target triple.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the call or the callee has the given attribute.
AttributeList getAttributes() const
Return the attribute list for this Function.
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
bool hasPersonalityFn() const
Check whether this function has a personality function.
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LinkageTypes getLinkage() const
void initialize(Attributor &A) override
See AbstractAttribute::initialize(...).
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
An abstract interface for all nonnull attributes.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
ChangeStatus manifest(Attributor &A) override
See AbstractAttribute::manifest(...).
void removeAttrs(ArrayRef< Attribute::AttrKind > AKs) const
Remove the attribute of kind AKs existing in the IR at this position.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
ChangeStatus update(Attributor &A)
Hook for the Attributor to trigger an update of the internal state.
#define STATS_DECLTRACK_CS_ATTR(NAME)
static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the largest range such that all values in the returned range satisfy the given predicate with...
unsigned getAttrIdx() const
Return the index in the attribute list for this position.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
virtual bool isAtFixpoint() const =0
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
virtual bool isValidState() const =0
Return if this abstract state is in a valid state.
std::function< void(const ArgumentReplacementInfo &, AbstractCallSite, SmallVectorImpl< Value * > &)> ACSRepairCBTy
Abstract call site (ACS) repair callback type.
static const char ID
Unique ID (due to the unique address)
const std::string getAsStr() const override
See AbstractAttribute::getAsStr().
#define BUILD_STAT_NAME(NAME, TYPE)
static void getCallbackUses(ImmutableCallSite ICS, SmallVectorImpl< const Use *> &CBUses)
Add operand uses of ICS that represent callback uses into CBUses.
ConstantRange getKnownConstantRange(Attributor &A, const Instruction *CtxI=nullptr) const override
See AAValueConstantRange::getKnownConstantRange(..).
bool isVoidTy() const
Return true if this is 'void'.
T greatestCommonDivisor(T A, T B)
Return the greatest common divisor of the values using Euclid's algorithm.
const BasicBlock & getEntryBlock() const
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
Type * getReturnType() const
Returns the type of the ret val.
static const char ID
Unique ID (due to the unique address)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
#define STATS_DECLTRACK_FN_ATTR(NAME)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool checkForAllCallLikeInstructions(const function_ref< bool(Instruction &)> &Pred, const AbstractAttribute &QueryingAA)
Check Pred on all call-like instructions (=CallBased derived).
static const char ID
Unique ID (due to the unique address)
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
unsigned getNumArgOperands() const
#define PIPE_OPERATOR(CLASS)
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
LLVM Basic Block Representation.
Instruction * getInstruction() const
Return the underlying instruction.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
DISubprogram * getSubprogram() const
Get the attached subprogram.
Conditional or Unconditional Branch instruction.
static const char ID
Unique ID (due to the unique address)
void deleteBody()
deleteBody - This method deletes the body of the function, and converts the linkage to external...
size_t size() const
size - Get the array size.
An abstract interface for all dereferenceable attribute.
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
ConstantRange getAssumedConstantRange(Attributor &A, const Instruction *CtxI=nullptr) const override
See AAValueConstantRange::getAssumedConstantRange(..).
void unionAssumed(const ConstantRange &R)
Unite assumed range with the passed state.
bool isPointerTy() const
True if this is an instance of PointerType.
void registerInvokeWithDeadSuccessor(InvokeInst &II)
Record that II has at least one dead successor block.
const Instruction & front() const
ValTy * getArgument(unsigned ArgNo) const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
MaybeAlign getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
ChangeStatus updateImpl(Attributor &A) override
See AbstractAttribute::initialize(...).
static void replaceAllInstructionUsesWith(Value &Old, Value &New)
For calls (and invokes) we will only replace instruction uses to not disturb the old style call graph...
void changeToUnreachableAfterManifest(Instruction *I)
Record that I is to be replaced with unreachable after information was manifested.
BasicBlock * getDefaultDest() const
Function * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it. ...
Represent the analysis usage information of a pass.
static const IRPosition returned(const Function &F)
Create a position describing the returned value of F.
bool isLifetimeStartOrEnd() const
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
An attribute for a function (scope).
virtual void initialize(Attributor &A)
Initialize the state with the information in the Attributor A.
ConstantRange getKnown() const
Return the known state encoding.
static ChangeStatus manifestAttrs(Attributor &A, const IRPosition &IRP, const ArrayRef< Attribute > &DeducedAttrs)
unsigned getAddressSpace() const
bool isAssumedNoCaptureMaybeReturned() const
Return true if we assume that the underlying value is not captured in its respective scope but we all...
void setCallingConv(CallingConv::ID CC)
Attribute::AttrKind getKindAsEnum() const
Return the attribute's kind as an enum (Attribute::AttrKind).
An attribute for a function argument.
bool isFnInterfaceKind() const
Return true if the position refers to a function interface, that is the function scope, the function return, or an argument.
ChangeStatus updateImpl(Attributor &A) override
See AbstractAttribute::updateImpl(...).
static const Value * getBasePointerOfAccessPointerOperand(const Instruction *I, int64_t &BytesOffset, const DataLayout &DL, bool AllowNonInbounds=false)
bool isEnumAttribute() const
Return true if the attribute is an Attribute::AttrKind type.
The fixpoint analysis framework that orchestrates the attribute deduction.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
bool isCallee(Value::const_user_iterator UI) const
Return true if UI is the use that defines the callee of this ACS.
Argument * getArg(unsigned i) const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type. ...
#define STATS_DECL(NAME, TYPE, MSG)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
BitIntegerState & addKnownBits(base_t Bits)
Add the bits in BitsEncoding to the "known bits".
const DataLayout & getDataLayout() const
Return the data layout associated with the anchor scope.
const Function * getFunction() const
Return the function this instruction belongs to.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
Simple state with integers encoding.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return the attribute object that exists at the given index.
unsigned getNumArgOperands() const
Return the number of parameters of the callee.
Base struct for all "concrete attribute" deductions.
static wasm::ValType getType(const TargetRegisterClass *RC)
static const char ID
Unique ID (due to the unique address)
unsigned getNumReplacementArgs() const
Value * AnchorVal
The value this position is anchored at.
static cl::opt< int > MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128), cl::Hidden)
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
static const char ID
Unique ID (due to the unique address)
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
ChangeStatus indicatePessimisticFixpoint() override
See AbstractState::indicatePessimisticFixpoint(...)
An abstract interface for all memory related attributes.
bool doesNotThrow() const
Determine if the function cannot unwind.
bool isEmptySet() const
Return true if this set contains no members.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
const AAType & getAAFor(const AbstractAttribute &QueryingAA, const IRPosition &IRP, bool TrackDependence=true, DepClassTy DepClass=DepClassTy::REQUIRED)
Lookup an abstract attribute of type AAType at position IRP.
BasicBlock * getNormalDest() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
virtual StateType & getState()=0
Return the internal abstract state for inspection.
static const char ID
Unique ID (due to the unique address)
An AbstractAttribute for nofree.
A SetVector that performs no allocations if smaller than a certain size.
bool isArgOperand(Value::const_user_iterator UI) const
Determine whether the passed iterator points to an argument operand.
void changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoek into a normall call.
static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2)
bool calculateBinaryOperator(Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T, Instruction *CtxI)
AAValueConstantRangeFunction(const IRPosition &IRP)
---------------— Value Constant Range Attribute ----------------------—
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
This is the shared class of boolean and integer constants.
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
An abstract attribute for undefined behavior.
bool isAssumedNoCapture() const
Return true if we assume that the underlying value is not captured in its respective scope...
static cl::opt< unsigned > DepRecInterval("attributor-dependence-recompute-interval", cl::Hidden, cl::desc("Number of iterations until dependences are recomputed."), cl::init(4))
void deleteAfterManifest(Instruction &I)
Record that I is deleted after information was manifested.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
base_t getKnown() const
Return the known state encoding.
bool isConvergent() const
Determine if the call is convergent.
uint32_t getBitWidth() const
Return associated values' bit width.
This class represents a range of values.
void markLiveInternalFunction(const Function &F)
Mark the internal function F as live.
Type * getReturnType() const
uint64_t getPointerDereferenceableBytes(const DataLayout &DL, bool &CanBeNull) const
Returns the number of bytes known to be dereferenceable for the pointer value.
LLVM_NODISCARD T pop_back_val()
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isCallbackCall() const
Return true if this ACS represents a callback call.
static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges)
Return true if Assumed is included in KnownRanges.
virtual void initialize(Attributor &A) override
See AbstractAttribute::initialize(...).
AttributeList getAttributes() const
Return the parameter attributes for this call.
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
#define STATS_DECLTRACK(NAME, TYPE, MSG)
An abstract interface to determine reachability of point A to B.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void clear()
Completely clear the SetVector.
A range adaptor for a pair of iterators.
static cl::opt< bool > EnableHeapToStack("enable-heap-to-stack-conversion", cl::init(true), cl::Hidden)
Class for arbitrary precision integers.
#define STATS_DECLTRACK_CSRET_ATTR(NAME)
Argument * getAssociatedArgument() const
Return the associated argument, if any.
static const char ID
Unique ID (due to the unique address)
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if this function has the given attribute.
amdgpu Simplify well known AMD library false FunctionCallee Callee
#define STATS_DECLTRACK_FNRET_ATTR(NAME)
#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
static const char ID
Unique ID (due to the unique address)
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
static const char ID
Unique ID (due to the unique address)
bool checkForAllReturnedValues(const function_ref< bool(Value &)> &Pred, const AbstractAttribute &QueryingAA)
Check Pred on all values potentially returned by the function associated with QueryingAA.
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 ...
iterator insert(iterator I, T &&Elt)
virtual ConstantRange getAssumedConstantRange(Attributor &A, const Instruction *CtxI=nullptr) const =0
Return an assumed range for the assocaited value a program point CtxI.
static const IRPosition value(const Value &V)
Create a position describing the value of V.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static void propagate(InstantiatedValue From, InstantiatedValue To, MatchState State, ReachabilitySet &ReachSet, std::vector< WorkListItem > &WorkList)
bool isBundleOperand(Value::const_user_iterator UI) const
Determine whether the passed iterator points to a bundle operand.
bool calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T, Instruction *CtxI)
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", "Deduce and propagate attributes", false, false) INITIALIZE_PASS_END(AttributorLegacyPass
A "must be executed context" for a given program point PP is the set of instructions, potentially before and after PP, that are executed always when PP is reached.
bool isIntAttribute() const
Return true if the attribute is an integer attribute.
Analysis pass that exposes the ScalarEvolution for a function.
bool findInContextOf(const Instruction *I, const Instruction *PP)
}
static Constant * getTruncOrBitCast(Constant *C, Type *Ty)
An interface to query the internal state of an abstract attribute.
If we do not capture the value in memory or through integers we can only communicate it back as a der...
IncIntegerState DerefBytesState
State representing for dereferenceable bytes.
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
bool checkForAllInstructions(const function_ref< bool(Instruction &)> &Pred, const AbstractAttribute &QueryingAA, const ArrayRef< unsigned > &Opcodes)
Check Pred on all instructions with an opcode present in Opcodes.
An abstract interface for all align attributes.
unsigned getNumUses() const
This method computes the number of uses of this Value.
LLVM_NODISCARD AttributeList addAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Add an attribute to the attribute set at the given index.
static const IRPosition argument(const Argument &Arg)
Create a position describing the argument Arg.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
const Function * getParent() const
bool changeValueAfterManifest(Value &V, Value &NV)
Helper function to replace all uses of V with NV.
AAValueConstantRangeCallSiteReturned(const IRPosition &IRP)
void identifyDefaultAbstractAttributes(Function &F)
Determine opportunities to derive 'default' attributes in F and create abstract attribute objects for...
This class represents an analyzed expression in the program.
Pass * createAttributorLegacyPass()
InformationCache & getInfoCache()
Return the internal information cache.
LLVM_NODISCARD bool empty() const
static bool checkForAllInstructionsImpl(InformationCache::OpcodeInstMapTy &OpcodeInstMap, const function_ref< bool(Instruction &)> &Pred, const AAIsDead *LivenessAA, bool &AnyDead, const ArrayRef< unsigned > &Opcodes)
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
CallingConv::ID getCallingConv() const
StringRef getName() const
Return a constant reference to the value's name.
bool hasExactDefinition() const
Return true if this global has an exact defintion.
Establish a view to a call site for examination.
Helper struct used in the communication between an abstract attribute (AA) that wants to change the s...
LLVM_NODISCARD AttributeList removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
void getAttrs(ArrayRef< Attribute::AttrKind > AKs, SmallVectorImpl< Attribute > &Attrs, bool IgnoreSubsumingPositions=false) const
Return the attributes of any kind in AKs existing in the IR at a position that will affect this one...
const Function * getParent() const
Return the enclosing method, or null if none.
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...
const APInt & getLower() const
Return the lower value for this range.
bool isMustTailCall() const
Tests if this call site must be tail call optimized.
bool empty() const
Determine if the SetVector is empty or not.
APFloat abs(APFloat X)
Returns the absolute value of the argument.
#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
static const char ID
Unique ID (due to the unique address)
bool mayReadFromMemory() const
Return true if this instruction may read memory.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
An abstract interface for value simplify abstract attribute.
ConstantRange getConstantRangeFromSCEV(Attributor &A, const Instruction *I=nullptr) const
Helper function to get a range from SCEV for the associated value at program point I...
const Use & getArgOperandUse(unsigned i) const
Wrappers for getting the Use of a call argument.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
AAValueConstantRangeCallSite(const IRPosition &IRP)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
An attribute for a call site (function scope).
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
static const char ID
Unique ID (due to the unique address)
If we do not capture the value in memory, through integers, or as a derived pointer we know it is not...
Function * getAssociatedFunction() const
Return the associated function, if any.
const SCEV * getSCEV(Attributor &A, const Instruction *I=nullptr) const
Helper function to get a SCEV expr for the associated value at program point I.
static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, AttributeList &Attrs, int AttrIdx)
Return true if the information provided by Attr was added to the attribute list Attrs.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
An abstract interface for range value analysis.
void removeFnAttr(Attribute::AttrKind Kind)
Remove function attributes from this function.
const std::string to_string(const T &Value)
bool isSingleElement() const
Return true if this set contains exactly one member.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
iterator_range< df_iterator< T > > depth_first(const T &G)
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
This pass computes, caches, and vends lazy value constraint information.
static const IRPosition EmptyKey
Special DenseMap key values.
void trackStatistics() const override
See AbstractAttribute::trackStatistics()
Deduce and propagate attributes
static bool runAttributorOnModule(Module &M, AnalysisGetter &AG)
}
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const IRPosition TombstoneKey
A raw_ostream that writes to an std::string.
BasicBlock * getUnwindDest() const
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
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.
virtual ChangeStatus manifest(Attributor &A)
Hook for the Attributor to trigger the manifestation of the information represented by the abstract a...
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
static cl::opt< bool > DisableAttributor("attributor-disable", cl::Hidden, cl::desc("Disable the attributor inter-procedural deduction pass."), cl::init(true))
#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
A vector that has set insertion semantics.
static cl::opt< bool > AnnotateDeclarationCallSites("attributor-annotate-decl-cs", cl::Hidden, cl::desc("Annotate call sites of function declarations."), cl::init(false))
succ_range successors(Instruction *I)
static const char ID
Unique ID (due to the unique address)
AttributeSet getFnAttributes() const
The function attributes are returned.
This class implements an extremely fast bulk output stream that can only output to a stream...
State for dereferenceable attribute.
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...
virtual bool isAssumedDead() const =0
Returns true if the underlying value is assumed dead.
const Use & getCalleeUseForCallback() const
Return the use of the callee value in the underlying instruction.
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
StringRef - Represent a constant reference to a string, i.e.
inst_range instructions(Function *F)
A container for analyses that lazily runs them and caches their results.
static bool isVolatile(Instruction *Inst)
APInt operator|(APInt a, const APInt &b)
unsigned getNumOperands() const
Return number of MDNode operands.
bool hasAttr(ArrayRef< Attribute::AttrKind > AKs, bool IgnoreSubsumingPositions=false) const
TODO: Figure out if the attribute related helper functions should live here or somewhere else...
virtual ChangeStatus indicateOptimisticFixpoint()=0
Indicate that the abstract state should converge to the optimistic state.
ChangeStatus manifest(Attributor &A) override
See AbstractAttribute::manifest()
void DetatchDeadBlocks(ArrayRef< BasicBlock *> BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
static bool genericValueTraversal(Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State, const function_ref< bool(Value &, StateTy &, bool)> &VisitValueCB, int MaxValues=8)
Recursively visit all values that might become IRP at some point.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
static IntegerType * getInt8Ty(LLVMContext &C)
AAValueConstantRangeArgument(const IRPosition &IRP)
bool changeUseAfterManifest(Use &U, Value &NV)
Record that U is to be replaces with NV after information was manifested.
bool AreStatisticsEnabled()
Check if statistics are enabled.
int KindOrArgNo
The argument number, if non-negative, or the position "kind".
static const IRPosition function(const Function &F)
Create a position describing the function scope of F.
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
PointerType * getType() const
Global values are always pointers.
Kind getPositionKind() const
Return the associated position kind.
ValTy * getArgOperand(unsigned i) const
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
iterator & begin(const Instruction *PP)
Return an iterator to explore the context around PP.
Analysis to compute lazy value information.
const BasicBlock * getParent() const
Simple wrapper for a single bit (boolean) state.
an instruction to allocate memory on the stack
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures, unsigned MaxUsesToExplore=DefaultMaxUsesToExplore)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
#define STATS_DECLTRACK_FLOATING_ATTR(NAME)
void recordDependence(const AbstractAttribute &FromAA, const AbstractAttribute &ToAA, DepClassTy DepClass)
Explicitly record a dependence from FromAA to ToAA, that is if FromAA changes ToAA should be updated ...
bool mayReadOrWriteMemory() const
Return true if this instruction may read or write memory.