79 #define DEBUG_TYPE "rewrite-statepoints-for-gc" 99 #ifdef EXPENSIVE_CHECKS 102 static bool ClobberNonLive =
false;
130 bool Changed =
false;
134 if (
F.isDeclaration() ||
F.empty())
163 class RewriteStatepointsForGCLegacyPass :
public ModulePass {
169 RewriteStatepointsForGCLegacyPass() :
ModulePass(ID), Impl() {
174 bool runOnModule(
Module &M)
override {
175 bool Changed =
false;
177 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
180 if (
F.isDeclaration() ||
F.empty())
189 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
190 auto &DT = getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
219 return new RewriteStatepointsForGCLegacyPass();
223 "rewrite-statepoints-for-gc",
224 "Make relocations explicit at statepoints",
false,
false)
228 "rewrite-statepoints-for-gc",
229 "Make relocations explicit at statepoints",
false,
false)
294 "Found non-leaf call without deopt info!");
303 GCPtrLivenessData &
Data);
314 if (
auto *PT = dyn_cast<PointerType>(T))
318 return PT->getAddressSpace() == 1;
332 if (
auto VT = dyn_cast<VectorType>(T))
344 if (
VectorType *VT = dyn_cast<VectorType>(Ty))
346 if (
ArrayType *AT = dyn_cast<ArrayType>(Ty))
374 GCPtrLivenessData &OriginalLivenessData,
CallSite CS,
375 PartiallyConstructedSafepointRecord &Result) {
382 dbgs() <<
"Live Variables:\n";
383 for (
Value *V : LiveSet)
384 dbgs() <<
" " << V->getName() <<
" " << *V <<
"\n";
388 dbgs() <<
"Number live values: " << LiveSet.size() <<
"\n";
390 Result.LiveSet = LiveSet;
405 struct BaseDefiningValueResult {
411 const bool IsKnownBase;
413 BaseDefiningValueResult(
Value *BDV,
bool IsKnownBase)
414 : BDV(BDV), IsKnownBase(IsKnownBase) {
419 assert(!MustBeBase || MustBeBase == IsKnownBase);
437 static BaseDefiningValueResult
442 if (isa<Argument>(I))
444 return BaseDefiningValueResult(I,
true);
446 if (isa<Constant>(I))
452 if (isa<LoadInst>(I))
453 return BaseDefiningValueResult(I,
true);
455 if (isa<InsertElementInst>(I))
459 return BaseDefiningValueResult(I,
false);
461 if (isa<ShuffleVectorInst>(I))
467 return BaseDefiningValueResult(I,
false);
471 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I))
476 if (
auto *BC = dyn_cast<BitCastInst>(I))
482 if (isa<CallInst>(I) || isa<InvokeInst>(
I))
483 return BaseDefiningValueResult(I,
true);
487 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
488 "unknown vector instruction - no base found for vector element");
489 return BaseDefiningValueResult(I,
false);
498 "Illegal to ask for the base pointer of a non-pointer type");
503 if (isa<Argument>(I))
506 return BaseDefiningValueResult(I,
true);
508 if (isa<Constant>(I)) {
519 return BaseDefiningValueResult(
523 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
524 Value *
Def = CI->stripPointerCasts();
527 assert(cast<PointerType>(Def->
getType())->getAddressSpace() ==
528 cast<PointerType>(CI->getType())->getAddressSpace() &&
529 "unsupported addrspacecast");
533 assert(!isa<CastInst>(Def) &&
"shouldn't find another cast here");
537 if (isa<LoadInst>(I))
539 return BaseDefiningValueResult(I,
true);
546 switch (II->getIntrinsicID()) {
550 case Intrinsic::experimental_gc_statepoint:
552 case Intrinsic::experimental_gc_relocate:
557 case Intrinsic::gcroot:
562 "interaction with the gcroot mechanism is not supported");
568 if (isa<CallInst>(I) || isa<InvokeInst>(I))
569 return BaseDefiningValueResult(I,
true);
573 assert(!isa<LandingPadInst>(I) &&
"Landing Pad is unimplemented");
575 if (isa<AtomicCmpXchgInst>(I))
579 return BaseDefiningValueResult(I,
true);
581 assert(!isa<AtomicRMWInst>(I) &&
"Xchg handled above, all others are " 582 "binary ops which don't apply to pointers");
587 if (isa<ExtractValueInst>(I))
588 return BaseDefiningValueResult(I,
true);
592 assert(!isa<InsertValueInst>(I) &&
593 "Base pointer for a struct is meaningless");
599 if (isa<ExtractElementInst>(I))
603 return BaseDefiningValueResult(I,
false);
609 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
610 "missing instruction case in findBaseDefiningValing");
611 return BaseDefiningValueResult(I,
false);
616 Value *&Cached = Cache[
I];
622 assert(Cache[I] !=
nullptr);
630 auto Found = Cache.find(Def);
631 if (Found != Cache.end()) {
633 return Found->second;
642 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
643 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
644 !isa<ShuffleVectorInst>(V)) {
648 if (isa<Instruction>(V) &&
649 cast<Instruction>(V)->getMetadata(
"is_base_value")) {
668 BDVState() : BaseValue(
nullptr) {}
670 explicit BDVState(Status Status,
Value *BaseValue =
nullptr)
671 : Status(Status), BaseValue(BaseValue) {
675 explicit BDVState(
Value *BaseValue) : Status(
Base), BaseValue(BaseValue) {}
677 Status getStatus()
const {
return Status; }
678 Value *getBaseValue()
const {
return BaseValue; }
680 bool isBase()
const {
return getStatus() ==
Base; }
681 bool isUnknown()
const {
return getStatus() ==
Unknown; }
682 bool isConflict()
const {
return getStatus() == Conflict; }
685 return BaseValue == Other.BaseValue && Status == Other.Status;
688 bool operator!=(
const BDVState &other)
const {
return !(*
this == other); }
697 switch (getStatus()) {
708 OS <<
" (" << getBaseValue() <<
" - " 709 << (getBaseValue() ? getBaseValue()->getName() :
"nullptr") <<
"): ";
727 switch (LHS.getStatus()) {
732 assert(LHS.getBaseValue() &&
"can't be null");
737 if (LHS.getBaseValue() == RHS.getBaseValue()) {
738 assert(LHS == RHS &&
"equality broken!");
741 return BDVState(BDVState::Conflict);
743 assert(RHS.isConflict() &&
"only three states!");
744 return BDVState(BDVState::Conflict);
746 case BDVState::Conflict:
754 static BDVState
meetBDVState(
const BDVState &LHS,
const BDVState &RHS) {
757 "Math is wrong: meet does not commute!");
794 auto isExpectedBDVType = [](
Value *BDV) {
795 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
796 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
797 isa<ShuffleVectorInst>(BDV);
814 while (!Worklist.
empty()) {
818 auto visitIncomingValue = [&](
Value *InVal) {
824 assert(isExpectedBDVType(Base) &&
"the only non-base values " 825 "we see should be base defining values");
826 if (States.
insert(std::make_pair(Base, BDVState())).second)
829 if (
PHINode *PN = dyn_cast<PHINode>(Current)) {
830 for (
Value *InVal : PN->incoming_values())
831 visitIncomingValue(InVal);
832 }
else if (
SelectInst *
SI = dyn_cast<SelectInst>(Current)) {
833 visitIncomingValue(
SI->getTrueValue());
834 visitIncomingValue(
SI->getFalseValue());
835 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(Current)) {
836 visitIncomingValue(EE->getVectorOperand());
837 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(Current)) {
838 visitIncomingValue(
IE->getOperand(0));
839 visitIncomingValue(
IE->getOperand(1));
840 }
else if (
auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
841 visitIncomingValue(SV->getOperand(0));
842 visitIncomingValue(SV->getOperand(1));
852 for (
auto Pair : States) {
853 LLVM_DEBUG(
dbgs() <<
" " << Pair.second <<
" for " << *Pair.first <<
"\n");
859 auto getStateForBDV = [&](
Value *baseValue) {
861 return BDVState(baseValue);
862 auto I = States.find(baseValue);
863 assert(I != States.end() &&
"lookup failed!");
867 bool Progress =
true;
870 const size_t OldSize = States.size();
877 for (
auto Pair : States) {
878 Value *BDV = Pair.first;
883 auto getStateForInput = [&](
Value *V)
mutable {
885 return getStateForBDV(BDV);
890 NewState =
meetBDVState(NewState, getStateForInput(
SI->getTrueValue()));
893 }
else if (
PHINode *PN = dyn_cast<PHINode>(BDV)) {
894 for (
Value *Val : PN->incoming_values())
895 NewState =
meetBDVState(NewState, getStateForInput(Val));
896 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
900 meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
901 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(BDV)){
904 NewState =
meetBDVState(NewState, getStateForInput(
IE->getOperand(0)));
905 NewState =
meetBDVState(NewState, getStateForInput(
IE->getOperand(1)));
909 auto *SV = cast<ShuffleVectorInst>(BDV);
910 NewState =
meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
911 NewState =
meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
914 BDVState OldState = States[BDV];
915 if (OldState != NewState) {
917 States[BDV] = NewState;
921 assert(OldSize == States.size() &&
922 "fixed point shouldn't be adding any new nodes to state");
927 for (
auto Pair : States) {
928 LLVM_DEBUG(
dbgs() <<
" " << Pair.second <<
" for " << *Pair.first <<
"\n");
934 for (
auto Pair : States) {
936 BDVState State = Pair.second;
938 assert(!State.isUnknown() &&
"Optimistic algorithm didn't complete!");
944 if (State.isBase() && isa<ExtractElementInst>(
I) &&
945 isa<VectorType>(State.getBaseValue()->getType())) {
946 auto *EE = cast<ExtractElementInst>(
I);
951 State.getBaseValue(), EE->getIndexOperand(),
"base_ee", EE);
953 States[
I] = BDVState(BDVState::Base, BaseInst);
959 assert(!isa<InsertElementInst>(I) || State.isConflict());
961 if (!State.isConflict())
967 if (isa<PHINode>(I)) {
970 assert(NumPreds > 0 &&
"how did we reach here");
978 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(I)) {
983 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(I)) {
990 auto *SV = cast<ShuffleVectorInst>(
I);
997 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
1000 States[
I] = BDVState(BDVState::Conflict, BaseInst);
1018 assert(States.count(BDV));
1019 Base = States[BDV].getBaseValue();
1021 assert(Base &&
"Can't be null");
1031 for (
auto Pair : States) {
1033 BDVState State = Pair.second;
1036 assert(!State.isUnknown() &&
"Optimistic algorithm didn't complete!");
1037 if (!State.isConflict())
1040 if (
PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
1041 PHINode *PN = cast<PHINode>(BDV);
1043 for (
unsigned i = 0; i < NumPHIValues; i++) {
1056 int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
1057 if (BlockIndex != -1) {
1058 Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
1059 BasePHI->addIncoming(OldBase, InBB);
1062 Value *
Base = getBaseForInput(InVal,
nullptr);
1070 "Sanity -- findBaseOrBDV should be pure!");
1079 BasePHI->addIncoming(Base, InBB);
1081 assert(BasePHI->getNumIncomingValues() == NumPHIValues);
1083 dyn_cast<SelectInst>(State.getBaseValue())) {
1088 BaseSI->setTrueValue(getBaseForInput(SI->
getTrueValue(), BaseSI));
1089 BaseSI->setFalseValue(getBaseForInput(SI->
getFalseValue(), BaseSI));
1090 }
else if (
auto *BaseEE =
1091 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
1092 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
1095 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
1096 }
else if (
auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
1097 auto *BdvIE = cast<InsertElementInst>(BDV);
1098 auto UpdateOperand = [&](
int OperandIdx) {
1099 Value *InVal = BdvIE->getOperand(OperandIdx);
1100 Value *
Base = getBaseForInput(InVal, BaseIE);
1101 BaseIE->setOperand(OperandIdx, Base);
1106 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
1107 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1108 auto UpdateOperand = [&](
int OperandIdx) {
1109 Value *InVal = BdvSV->getOperand(OperandIdx);
1110 Value *
Base = getBaseForInput(InVal, BaseSV);
1111 BaseSV->setOperand(OperandIdx, Base);
1121 for (
auto Pair : States) {
1122 auto *BDV = Pair.first;
1123 Value *
Base = Pair.second.getBaseValue();
1128 dbgs() <<
"Updating base value cache" 1129 <<
" for: " << BDV->getName() <<
" from: " 1130 << (Cache.count(BDV) ? Cache[BDV]->getName().str() :
"none")
1131 <<
" to: " << Base->
getName() <<
"\n");
1133 if (Cache.count(BDV)) {
1135 "must be something we 'know' is a base pointer");
1139 "base relation should be stable");
1143 assert(Cache.count(Def));
1166 for (
Value *ptr : live) {
1168 assert(base &&
"failed to find base pointer");
1169 PointerToBase[ptr] = base;
1170 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1171 DT->
dominates(cast<Instruction>(base)->getParent(),
1172 cast<Instruction>(ptr)->
getParent())) &&
1173 "The base we found better dominate the derived pointer");
1181 PartiallyConstructedSafepointRecord &result) {
1186 errs() <<
"Base Pairs (w/o Relocation):\n";
1187 for (
auto &Pair : PointerToBase) {
1188 errs() <<
" derived ";
1189 Pair.first->printAsOperand(
errs(),
false);
1191 Pair.second->printAsOperand(
errs(),
false);
1196 result.PointerToBase = PointerToBase;
1203 PartiallyConstructedSafepointRecord &result);
1210 GCPtrLivenessData RevisedLivenessData;
1212 for (
size_t i = 0; i < records.
size(); i++) {
1213 struct PartiallyConstructedSafepointRecord &
info = records[i];
1235 "All PHI nodes should have been removed!");
1273 const int LiveStart,
1277 if (LiveVariables.
empty())
1282 assert(ValIt != LiveVec.
end() &&
"Val not found in LiveVec!");
1283 size_t Index = std::distance(LiveVec.
begin(), ValIt);
1284 assert(Index < LiveVec.
size() &&
"Bug in std::find?");
1296 auto getGCRelocateDecl = [&] (
Type *Ty) {
1298 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1300 if (
auto *VT = dyn_cast<VectorType>(Ty))
1311 for (
unsigned i = 0; i < LiveVariables.
size(); i++) {
1314 Builder.
getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
1317 Type *Ty = LiveVariables[i]->getType();
1318 if (!TypeToDeclMap.
count(Ty))
1319 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1320 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1324 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1336 class DeferredReplacement {
1339 bool IsDeoptimize =
false;
1341 DeferredReplacement() =
default;
1345 assert(Old != New && Old && New &&
1346 "Cannot RAUW equal values or to / from null!");
1348 DeferredReplacement
D;
1354 static DeferredReplacement createDelete(
Instruction *ToErase) {
1355 DeferredReplacement
D;
1360 static DeferredReplacement createDeoptimizeReplacement(
Instruction *Old) {
1364 "Only way to construct a deoptimize deferred replacement");
1366 DeferredReplacement
D;
1368 D.IsDeoptimize =
true;
1373 void doReplacement() {
1377 assert(OldI != NewI &&
"Disallowed at construction?!");
1378 assert((!IsDeoptimize || !New) &&
1379 "Deoptimize intrinsics are not replaced!");
1402 const char *DeoptLowering =
"deopt-lowering";
1414 return "live-through";
1421 PartiallyConstructedSafepointRecord &Result,
1422 std::vector<DeferredReplacement> &Replacements) {
1440 if (
auto TransitionBundle =
1443 TransitionArgs = TransitionBundle->Inputs;
1449 bool IsDeoptimize =
false;
1460 if (DeoptLowering.
equals(
"live-in"))
1463 assert(DeoptLowering.
equals(
"live-through") &&
"Unsupported value!");
1467 if (
Function *F = dyn_cast<Function>(CallTarget)) {
1486 IsDeoptimize =
true;
1495 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1496 TransitionArgs, DeoptArgs, GCArgs,
"safepoint_token");
1521 StatepointID, NumPatchBytes, CallTarget, ToReplace->
getNormalDest(),
1522 ToReplace->
getUnwindDest(), Flags, CallArgs, TransitionArgs, DeoptArgs,
1523 GCArgs,
"statepoint_token");
1539 "can't safely insert in this block!");
1546 Result.UnwindToken = ExceptionalToken;
1556 "can't safely insert in this block!");
1563 assert(Token &&
"Should be set in one of the above branches!");
1569 Replacements.push_back(
1570 DeferredReplacement::createDeoptimizeReplacement(CS.
getInstruction()));
1572 Token->
setName(
"statepoint_token");
1587 Replacements.emplace_back(
1590 Replacements.emplace_back(
1595 Result.StatepointToken = Token;
1609 PartiallyConstructedSafepointRecord &Result,
1610 std::vector<DeferredReplacement> &Replacements) {
1611 const auto &LiveSet = Result.LiveSet;
1612 const auto &PointerToBase = Result.PointerToBase;
1616 LiveVec.
reserve(LiveSet.size());
1617 BaseVec.
reserve(LiveSet.size());
1618 for (
Value *L : LiveSet) {
1620 assert(PointerToBase.count(L));
1621 Value *
Base = PointerToBase.find(L)->second;
1640 for (
User *U : GCRelocs) {
1647 Value *Alloca = AllocaMap[OriginalValue];
1653 "Should always have one since it's not a terminator");
1655 Value *CastedRelocatedValue =
1656 Builder.CreateBitCast(Relocate,
1657 cast<AllocaInst>(Alloca)->getAllocatedType(),
1661 Store->
insertAfter(cast<Instruction>(CastedRelocatedValue));
1664 VisitedLiveValues.
insert(OriginalValue);
1675 for (
auto RematerializedValuePair: RematerializedValues) {
1676 Instruction *RematerializedValue = RematerializedValuePair.first;
1677 Value *OriginalValue = RematerializedValuePair.second;
1680 "Can not find alloca for rematerialized value");
1681 Value *Alloca = AllocaMap[OriginalValue];
1687 VisitedLiveValues.
insert(OriginalValue);
1699 int InitialAllocaNum = 0;
1701 if (isa<AllocaInst>(I))
1709 std::size_t NumRematerializedValues = 0;
1715 auto emitAllocaFor = [&](
Value *LiveValue) {
1719 AllocaMap[LiveValue] = Alloca;
1724 for (
Value *V : Live)
1728 for (
const auto &Info : Records)
1729 for (
auto RematerializedValuePair : Info.RematerializedValues) {
1730 Value *OriginalValue = RematerializedValuePair.second;
1731 if (AllocaMap.
count(OriginalValue) != 0)
1734 emitAllocaFor(OriginalValue);
1735 ++NumRematerializedValues;
1747 for (
const auto &Info : Records) {
1758 if (isa<InvokeInst>(Statepoint)) {
1767 if (ClobberNonLive) {
1774 for (
auto Pair : AllocaMap) {
1776 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1779 if (VisitedLiveValues.
count(Def)) {
1786 for (
auto *AI : ToClobber) {
1787 auto PT = cast<PointerType>(AI->getAllocatedType());
1796 if (
auto II = dyn_cast<InvokeInst>(Statepoint)) {
1797 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1798 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1800 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1806 for (
auto Pair : AllocaMap) {
1808 Value *Alloca = Pair.second;
1817 if (!isa<ConstantExpr>(U)) {
1828 auto Last = std::unique(Uses.
begin(), Uses.
end());
1832 if (isa<PHINode>(
Use)) {
1843 Use->replaceUsesOfWith(Def, Load);
1851 if (
Instruction *Inst = dyn_cast<Instruction>(Def)) {
1852 if (
InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1855 BasicBlock *NormalDest = Invoke->getNormalDest();
1858 assert(!Inst->isTerminator() &&
1859 "The only TerminatorInst that can produce a value is " 1860 "InvokeInst which is handled above.");
1864 assert(isa<Argument>(Def));
1869 assert(PromotableAllocas.
size() == Live.size() + NumRematerializedValues &&
1870 "we must have the same allocas with lives");
1871 if (!PromotableAllocas.
empty()) {
1878 if (isa<AllocaInst>(I))
1880 assert(InitialAllocaNum == 0 &&
"We must not introduce any extra allocas");
1915 Func, Values,
"", &*II->getNormalDest()->getFirstInsertionPt()));
1917 Func, Values,
"", &*II->getUnwindDest()->getFirstInsertionPt()));
1923 GCPtrLivenessData OriginalLivenessData;
1925 for (
size_t i = 0; i < records.
size(); i++) {
1926 struct PartiallyConstructedSafepointRecord &
info = records[i];
1939 Value *CurrentValue) {
1943 GEP->getPointerOperand());
1946 if (
CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1947 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1957 return CurrentValue;
1968 if (
CastInst *CI = dyn_cast<CastInst>(Instr)) {
1969 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1970 "non noop cast is found during rematerialization");
1972 Type *SrcTy = CI->getOperand(0)->getType();
1977 Type *ValTy =
GEP->getSourceElementType();
1983 if (!
GEP->hasAllConstantIndices())
2002 for (
unsigned i = 0; i < PhiNum; i++)
2008 for (
unsigned i = 0; i < PhiNum; i++) {
2011 if (CIVI == CurrentIncomingValues.
end())
2013 BasicBlock *CurrentIncomingBB = CIVI->second;
2025 PartiallyConstructedSafepointRecord &Info,
2027 const unsigned int ChainLengthThreshold = 10;
2033 for (
Value *LiveValue: Info.LiveSet) {
2036 assert(Info.PointerToBase.count(LiveValue));
2037 Value *RootOfChain =
2042 if ( ChainToBase.
size() == 0 ||
2043 ChainToBase.
size() > ChainLengthThreshold)
2048 if (RootOfChain != Info.PointerToBase[LiveValue]) {
2051 if (!OrigRootPhi || !AlternateRootPhi)
2067 assert(Info.LiveSet.count(AlternateRootPhi));
2086 LiveValuesToBeDeleted.
push_back(LiveValue);
2096 auto rematerializeChain = [&ChainToBase](
2105 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2109 ClonedValue->
setName(Instr->getName() +
".remat");
2113 if (LastClonedValue) {
2121 "incorrect use in rematerialization chain");
2124 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
2133 if (RootOfChain != AlternateLiveBase)
2137 LastClonedValue = ClonedValue;
2141 return LastClonedValue;
2149 Instruction *RematerializedValue = rematerializeChain(
2150 InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2151 Info.RematerializedValues[RematerializedValue] = LiveValue;
2160 Instruction *NormalRematerializedValue = rematerializeChain(
2161 NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2162 Instruction *UnwindRematerializedValue = rematerializeChain(
2163 UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2165 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2166 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2171 for (
auto LiveValue: LiveValuesToBeDeleted) {
2172 Info.LiveSet.remove(LiveValue);
2181 std::set<CallSite> Uniqued;
2182 Uniqued.insert(ToUpdate.
begin(), ToUpdate.
end());
2183 assert(Uniqued.size() == ToUpdate.
size() &&
"no duplicates please!");
2214 "support for FCA unimplemented");
2235 for (
size_t i = 0; i < Records.size(); i++) {
2236 PartiallyConstructedSafepointRecord &
info = Records[i];
2254 Holders.reserve(Holders.size() + Records.size());
2255 for (
size_t i = 0; i < Records.size(); i++) {
2256 PartiallyConstructedSafepointRecord &Info = Records[i];
2259 for (
auto Pair : Info.PointerToBase)
2271 for (
auto &Info : Records) {
2272 errs() <<
"Base Pairs: (w/Relocation)\n";
2273 for (
auto Pair : Info.PointerToBase) {
2274 errs() <<
" derived ";
2275 Pair.first->printAsOperand(
errs(),
false);
2277 Pair.second->printAsOperand(
errs(),
false);
2291 for (
auto &Info : Records)
2292 for (
auto &BasePair : Info.PointerToBase)
2293 if (isa<Constant>(BasePair.second))
2294 Info.LiveSet.remove(BasePair.first);
2297 CI->eraseFromParent();
2304 for (
size_t i = 0; i < Records.size(); i++)
2310 std::vector<DeferredReplacement> Replacements;
2318 for (
size_t i = 0; i < Records.size(); i++)
2323 for (
auto &PR : Replacements)
2326 Replacements.clear();
2328 for (
auto &Info : Records) {
2337 Info.LiveSet.clear();
2338 Info.PointerToBase.clear();
2343 for (
size_t i = 0; i < Records.size(); i++) {
2344 PartiallyConstructedSafepointRecord &Info = Records[i];
2360 "statepoint must be reachable or liveness is meaningless");
2362 if (!isa<Instruction>(V))
2365 auto *LiveInst = cast<Instruction>(V);
2367 "unreachable values should never be live");
2369 "basic SSA liveness expectation violated by liveness analysis");
2377 for (
auto *
Ptr : Live)
2379 "must be a gc pointer type");
2383 return !Records.empty();
2387 template <
typename AttrHolder>
2391 if (AH.getDereferenceableBytes(Index))
2393 AH.getDereferenceableBytes(Index)));
2394 if (AH.getDereferenceableOrNullBytes(Index))
2396 AH.getDereferenceableOrNullBytes(Index)));
2401 AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
2408 if (isa<PointerType>(
A.getType()))
2420 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2465 if (
auto *II = dyn_cast<IntrinsicInst>(&I))
2466 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2467 InvariantStartInstructions.
push_back(II);
2479 for (
int i = 0, e = CS.
arg_size(); i != e; i++)
2482 if (isa<PointerType>(CS.
getType()))
2488 for (
auto *II : InvariantStartInstructions) {
2490 II->eraseFromParent();
2499 const auto &FunctionGCName = F.
getGC();
2500 const StringRef StatepointExampleName(
"statepoint-example");
2502 return (StatepointExampleName == FunctionGCName) ||
2503 (CoreCLRName == FunctionGCName);
2524 "need function body to rewrite statepoints in");
2547 if (NeedsRewrite(I)) {
2553 "no unreachable blocks expected");
2559 if (ParsePointNeeded.
empty())
2567 if (BB.getUniquePredecessor()) {
2586 if (
auto *BI = dyn_cast<BranchInst>(TI))
2587 if (BI->isConditional())
2588 return dyn_cast<Instruction>(BI->getCondition());
2594 if (
auto *Cond = getConditionInst(TI))
2597 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2599 Cond->moveBefore(TI);
2624 if (isa<PHINode>(I))
2628 for (
Value *V : I.operands()) {
2630 "support for FCA unimplemented");
2650 for (
auto &I : *Succ) {
2657 "support for FCA unimplemented");
2677 for (
Value *V : Live) {
2678 if (
auto *I = dyn_cast<Instruction>(V)) {
2682 if (TermOkay && TI == I)
2685 "basic SSA liveness expectation violated by liveness analysis");
2702 GCPtrLivenessData &Data) {
2708 Data.LiveSet[&BB].clear();
2713 assert(!Data.LiveSet[&BB].count(
Kill) &&
"live set contains kill");
2718 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2719 Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2720 Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
2721 if (!Data.LiveIn[&BB].empty())
2726 while (!Worklist.
empty()) {
2732 const auto OldLiveOutSize = LiveOut.
size();
2734 assert(Data.LiveIn.count(Succ));
2738 if (OldLiveOutSize == LiveOut.
size()) {
2744 Data.LiveOut[BB] = LiveOut;
2751 assert(Data.LiveIn.count(BB));
2754 if (OldLiveIn.size() != LiveTmp.
size()) {
2755 Data.LiveIn[BB] = LiveTmp;
2773 assert(Data.LiveOut.count(BB));
2782 LiveOut.remove(Inst);
2783 Out.insert(LiveOut.begin(), LiveOut.end());
2788 PartiallyConstructedSafepointRecord &Info) {
2795 for (
auto V : Updated)
2796 if (Info.PointerToBase.insert({V, V}).second) {
2798 "Can't find base for unexpected live value!");
2803 for (
auto V : Updated)
2804 assert(Info.PointerToBase.count(V) &&
2805 "Must be able to find base for live value!");
2811 for (
auto KVPair : Info.PointerToBase)
2812 if (!Updated.count(KVPair.first))
2813 ToErase.
insert(KVPair.first);
2815 for (
auto *V : ToErase)
2816 Info.PointerToBase.erase(V);
2819 for (
auto KVPair : Info.PointerToBase)
2820 assert(Updated.count(KVPair.first) &&
"record for non-live value");
2823 Info.LiveSet = Updated;
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static void findLiveReferences(Function &F, DominatorTree &DT, ArrayRef< CallSite > toUpdate, MutableArrayRef< struct PartiallyConstructedSafepointRecord > records)
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static void unique_unsorted(SmallVectorImpl< T > &Vec)
Implement a unique function which doesn't require we sort the input vector.
static void computeLiveOutSeed(BasicBlock *BB, SetVector< Value *> &LiveTmp)
static bool isHandledGCPointerType(Type *T)
static cl::opt< bool, true > ClobberNonLiveOverride("rs4gc-clobber-non-live", cl::location(ClobberNonLive), cl::Hidden)
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
MapVector< Value *, Value * > DefiningValueMapTy
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
static Value * findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache)
Returns the base defining value for this value.
static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi)
unsigned arg_size() const
static BDVState meetBDVStateImpl(const BDVState &LHS, const BDVState &RHS)
static bool insertParsePoints(Function &F, DominatorTree &DT, TargetTransformInfo &TTI, SmallVectorImpl< CallSite > &ToUpdate)
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM_NODISCARD T pop_back_val()
Compute iterated dominance frontiers using a linear time algorithm.
Instruction * StatepointToken
The new gc.statepoint instruction itself.
size_type size() const
Determine the number of elements in the SetVector.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
static void stripInvalidMetadataFromInstruction(Instruction &I)
Certain metadata on instructions are invalid after running RS4GC.
Instruction * UnwindToken
Instruction to which exceptional gc relocates are attached Makes it easier to iterate through them du...
A Module instance is used to store all the information related to an LLVM module. ...
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
StatepointDirectives parseStatepointDirectivesFromAttrs(AttributeList AS)
Parse out statepoint directives from the function attributes present in AS.
static ConstantAggregateZero * get(Type *Ty)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
static void rematerializeLiveValues(CallSite CS, PartiallyConstructedSafepointRecord &Info, TargetTransformInfo &TTI)
static StringRef getDeoptLowering(CallSite CS)
This class represents a function call, abstracting a target machine's calling convention.
INITIALIZE_PASS_BEGIN(RewriteStatepointsForGCLegacyPass, "rewrite-statepoints-for-gc", "Make relocations explicit at statepoints", false, false) INITIALIZE_PASS_END(RewriteStatepointsForGCLegacyPass
MapVector< BasicBlock *, SetVector< Value * > > KillSet
Values defined in this block.
const Value * getTrueValue() const
The two locations do not alias at all.
Analysis pass providing the TargetTransformInfo.
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
MapVector< BasicBlock *, SetVector< Value * > > LiveSet
Values used in this block (and thus live); does not included values killed within this block...
LLVMContext & getContext() const
All values hold a context through their type.
static void stripNonValidAttributesFromPrototype(Function &F)
MapVector< BasicBlock *, SetVector< Value * > > LiveIn
Values live into this basic block (i.e.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class implements a map that also provides access to all stored values in a deterministic order...
Analysis pass which computes a DominatorTree.
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static void makeStatepointExplicitImpl(const CallSite CS, const SmallVectorImpl< Value *> &BasePtrs, const SmallVectorImpl< Value *> &LiveVariables, PartiallyConstructedSafepointRecord &Result, std::vector< DeferredReplacement > &Replacements)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
An instruction for reading from memory.
reverse_iterator rbegin()
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
bool isVectorTy() const
True if this is an instance of VectorType.
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
static void stripNonValidDataFromBody(Function &F)
static BaseDefiningValueResult findBaseDefiningValueOfVector(Value *I)
Return a base defining value for the 'Index' element of the given vector instruction 'I'...
void reserve(size_type N)
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
static void checkBasicSSA(DominatorTree &DT, SetVector< Value *> &Live, TerminatorInst *TI, bool TermOkay=false)
Check that the items in 'Live' dominate 'TI'.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
static void computeLiveInValues(DominatorTree &DT, Function &F, GCPtrLivenessData &Data)
Compute the live-in set for every basic block in the function.
iterator begin()
Instruction iterator methods.
unsigned getAllocaAddrSpace() const
AnalysisUsage & addRequired()
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
#define INITIALIZE_PASS_DEPENDENCY(depName)
CallSiteTy::arg_iterator gc_args_begin() const
static void relocationViaAlloca(Function &F, DominatorTree &DT, ArrayRef< Value *> Live, ArrayRef< PartiallyConstructedSafepointRecord > Records)
Do all the relocation update via allocas and mem2reg.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
This is the base class for all instructions that perform data casts.
'undef' values are things that do not have specified contents.
static bool isKnownBaseResult(Value *V)
Given the result of a call to findBaseDefiningValue, or findBaseOrBDV, is it known to be a base point...
TailCallKind getTailCallKind() const
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
static Value * findBasePointer(Value *I, DefiningValueMapTy &Cache)
For a given value or instruction, figure out what base ptr its derived from.
A Use represents the edge between a Value definition and its users.
Value * getDerivedPtr() const
static Value * findRematerializableChainToBasePointer(SmallVectorImpl< Instruction *> &ChainToBase, Value *CurrentValue)
static bool isGCPointerType(Type *T)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static void makeStatepointExplicit(DominatorTree &DT, CallSite CS, PartiallyConstructedSafepointRecord &Result, std::vector< DeferredReplacement > &Replacements)
This file contains the simple types necessary to represent the attributes associated with functions a...
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
InstrTy * getInstruction() const
void setName(const Twine &Name)
Change the name of the value.
bool remove(const value_type &X)
Remove an item from the set vector.
void initializeRewriteStatepointsForGCLegacyPassPass(PassRegistry &)
LLVMContext & getContext() const
Retrieve the LLVM context.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
ValTy * getCalledValue() const
Return the pointer to function that is being called.
static cl::opt< bool > PrintLiveSet("spp-print-liveset", cl::Hidden, cl::init(false))
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
CallSiteTy::arg_iterator gc_args_end() const
const T & getValue() const LLVM_LVALUE_FUNCTION
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Class to represent array types.
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
AttrBuilder & remove(const AttrBuilder &B)
Remove the attributes from the builder.
const std::string & getGC() const
An instruction for storing to memory.
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr, DeferredDominance *DDT=nullptr)
Remove all blocks that can not be reached from the function's entry.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ModulePass * createRewriteStatepointsForGCLegacyPass()
DominatorTree & flush()
Flushes all pending updates and block deletions.
AttributeList getAttributes() const
Return the parameter attributes for this call.
StatepointLiveSetTy LiveSet
The set of values known to be live across this safepoint.
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.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static unsigned chainToBasePointerCost(SmallVectorImpl< Instruction *> &Chain, TargetTransformInfo &TTI)
SetVector< Value * > StatepointLiveSetTy
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
bool isCall() const
Return true if a CallInst is enclosed.
iterator find(const_arg_type_t< KeyT > Val)
Optional< OperandBundleUse > getOperandBundle(StringRef Name) const
static SetVector< Value * > computeKillSet(BasicBlock *BB)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
CallInst * CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, ArrayRef< Value *> CallArgs, ArrayRef< Value *> DeoptArgs, ArrayRef< Value *> GCArgs, const Twine &Name="")
Create a call to the experimental.gc.statepoint intrinsic to start a new statepoint sequence...
initializer< Ty > init(const Ty &Val)
Type * getReturnType() const
Returns the type of the ret val.
static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH, unsigned Index)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
static ArrayRef< Use > GetDeoptBundleOperands(ImmutableCallSite CS)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
size_t size() const
size - Get the array size.
This function has undefined behavior.
This is an important base class in LLVM.
bool set_union(const STy &S)
Compute This := This u S, return whether 'This' changed.
static void analyzeParsePointLiveness(DominatorTree &DT, GCPtrLivenessData &OriginalLivenessData, CallSite CS, PartiallyConstructedSafepointRecord &Result)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if this function has the given attribute.
static cl::opt< unsigned > RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden, cl::init(6))
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static AttributeList legalizeCallAttributes(AttributeList AL)
std::pair< iterator, bool > insert(const ValueT &V)
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
bool runOnFunction(Function &F, DominatorTree &, TargetTransformInfo &, const TargetLibraryInfo &)
Optional< uint32_t > NumPatchBytes
InvokeInst * CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value *> InvokeArgs, ArrayRef< Value *> DeoptArgs, ArrayRef< Value *> GCArgs, const Twine &Name="")
Create an invoke to the experimental.gc.statepoint intrinsic to start a new statepoint sequence...
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
RematerializedValueMapTy RematerializedValues
Record live values we are rematerialized instead of relocating.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
A specialization of it's base class for read-write access to a gc.statepoint.
Interval::pred_iterator pred_end(Interval *I)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
bool callsGCLeafFunction(ImmutableCallSite CS, const TargetLibraryInfo &TLI)
Return true if the CallSite CS calls a gc leaf function.
self_iterator getIterator()
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
static void insertRelocationStores(iterator_range< Value::user_iterator > GCRelocs, DenseMap< Value *, Value *> &AllocaMap, DenseSet< Value *> &VisitedLiveValues)
static void insertRematerializationStores(const RematerializedValueMapTy &RematerializedValues, DenseMap< Value *, Value *> &AllocaMap, DenseSet< Value *> &VisitedLiveValues)
static void stripNonValidData(Module &M)
The IR fed into RewriteStatepointsForGC may have had attributes and metadata implying dereferenceabil...
void setTailCallKind(TailCallKind TCK)
const Function * getFunction() const
Return the function this instruction belongs to.
static bool containsGCPtrType(Type *Ty)
Returns true if this type contains a gc pointer whether we know how to handle that type or not...
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
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 aliases.
iterator erase(const_iterator CI)
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.
static void findLiveSetAtInst(Instruction *inst, GCPtrLivenessData &Data, StatepointLiveSetTy &out)
Given results from the dataflow liveness computation, find the set of live Values at a particular ins...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
static Value * findBaseOrBDV(Value *I, DefiningValueMapTy &Cache)
Return a base pointer for this value if known.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
static bool shouldRewriteStatepointsIn(Function &F)
Returns true if this function should be rewritten by this pass.
bool isInvoke() const
Return true if a InvokeInst is enclosed.
void setCallingConv(CallingConv::ID CC)
void sort(IteratorTy Start, IteratorTy End)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
BasicBlock * getNormalDest() const
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static cl::opt< bool > PrintBasePointers("spp-print-base-pointers", cl::Hidden, cl::init(false))
static cl::opt< bool > AllowStatepointWithNoDeoptInfo("rs4gc-allow-statepoint-with-no-deopt-info", cl::Hidden, cl::init(true))
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
ValTy * getArgument(unsigned ArgNo) const
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static BDVState meetBDVState(const BDVState &LHS, const BDVState &RHS)
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
static void insertUseHolderAfter(CallSite &CS, const ArrayRef< Value *> Values, SmallVectorImpl< CallInst *> &Holders)
Insert holders so that each Value is obviously live through the entire lifetime of the call...
Indicates that this statepoint is a transition from GC-aware code to code that is not GC-aware...
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static BasicBlock * normalizeForInvokeSafepoint(BasicBlock *BB, BasicBlock *InvokeParent, DominatorTree &DT)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
void set_subtract(const STy &S)
Compute This := This - B TODO: We should be able to use set_subtract from SetOperations.h, but SetVector interface is inconsistent with DenseSet.
Value handle that asserts if the Value is deleted.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool ClobberNonLive
A range adaptor for a pair of iterators.
Class to represent vector types.
static std::string suffixed_name_or(Value *V, StringRef Suffix, StringRef DefaultName)
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
MapVector< AssertingVH< Instruction >, AssertingVH< Value > > RematerializedValueMapTy
bool isStatepointDirectiveAttr(Attribute Attr)
Return true if the Attr is an attribute that is a statepoint directive.
Class to defer updates to a DominatorTree.
Optional< uint64_t > StatepointID
iterator_range< user_iterator > users()
static const uint64_t DefaultStatepointID
void FoldSingleEntryPHINodes(BasicBlock *BB, MemoryDependenceResults *MemDep=nullptr)
We know that BB has one predecessor.
iterator insert(iterator I, T &&Elt)
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
const Value * getFalseValue() const
amdgpu Simplify well known AMD library false Value Value * Arg
Call sites that get wrapped by a gc.statepoint (currently only in RewriteStatepointsForGC and potenti...
bool operator!=(uint64_t V1, const APInt &V2)
static void CreateGCRelocates(ArrayRef< Value *> LiveVariables, const int LiveStart, ArrayRef< Value *> BasePtrs, Instruction *StatepointToken, IRBuilder<> Builder)
Helper function to place all gc relocates necessary for the given statepoint.
unsigned getNumUses() const
This method computes the number of uses of this Value.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static cl::opt< bool > PrintLiveSetSize("spp-print-liveset-size", cl::Hidden, cl::init(false))
bool empty() const
Return true if the builder contains no target-independent attributes.
LLVM_NODISCARD bool empty() const
StringRef getValueAsString() const
Return the attribute's value as a string.
StringRef getName() const
Return a constant reference to the value's name.
static bool isUnhandledGCPointerType(Type *Ty)
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
unsigned pred_size(const BasicBlock *BB)
CallInst * CreateGCResult(Instruction *Statepoint, Type *ResultType, const Twine &Name="")
Create a call to the experimental.gc.result intrinsic to extract the result from a call wrapped in a ...
bool empty() const
Determine if the SetVector is empty or not.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static void findBasePointers(const StatepointLiveSetTy &live, MapVector< Value *, Value *> &PointerToBase, DominatorTree *DT, DefiningValueMapTy &DVCache)
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
ilist_iterator< OptionsT, !IsReverse, IsConst > getReverse() const
Get a reverse iterator to the same node.
void preserve()
Mark an analysis as preserved.
static Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Type * getType() const
Return the type of the instruction that generated this call site.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool isStatepoint(ImmutableCallSite CS)
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
BasicBlock * getUnwindDest() const
Represents calls to the gc.relocate intrinsic.
Mark the deopt arguments associated with the statepoint as only being "live-in".
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
A vector that has set insertion semantics.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
static void recomputeLiveInValues(GCPtrLivenessData &RevisedLivenessData, CallSite CS, PartiallyConstructedSafepointRecord &result)
Given an updated version of the dataflow liveness results, update the liveset and base pointer maps f...
static const Function * getParent(const Value *V)
AttributeSet getFnAttributes() const
The function attributes are returned.
iterator_range< arg_iterator > gc_args() const
range adapter for gc arguments
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
MapVector< BasicBlock *, SetVector< Value * > > LiveOut
Values live out of this basic block (i.e.
This class implements an extremely fast bulk output stream that can only output to a stream...
void PromoteMemToReg(ArrayRef< AllocaInst *> Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
unsigned gcArgsStartIdx() const
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.
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
Legacy analysis pass which computes a DominatorTree.
AttributeList getAttributes() const
Get the parameter attributes of the call.
bool operator==(uint64_t V1, const APInt &V2)
MapVector< Value *, Value * > PointerToBase
Mapping from live pointers to a base-defining-value.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setIncomingValue(unsigned i, Value *V)
bool isEmpty() const
Return true if there are no attributes.
MDNode * createMutableTBAAAccessTag(MDNode *Tag)
Return mutable version of the given mutable or immutable TBAA access tag.
LocationClass< Ty > location(Ty &L)
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()
bool empty() const
empty - Check if the array is empty.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
static BaseDefiningValueResult findBaseDefiningValue(Value *I)
Helper function for findBasePointer - Will return a value which either a) defines the base pointer fo...
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.