46 #define DEBUG_TYPE "rewrite-statepoints-for-gc"
65 #ifdef EXPENSIVE_CHECKS
79 struct RewriteStatepointsForGC :
public ModulePass {
86 bool runOnModule(
Module &M)
override {
89 Changed |= runOnFunction(
F);
95 stripNonValidAttributesAndMetadata(M);
117 void stripNonValidAttributesAndMetadata(
Module &M);
120 void stripNonValidAttributesAndMetadataFromBody(
Function &
F);
121 void stripNonValidAttributesFromPrototype(
Function &
F);
125 void stripInvalidMetadataFromInstruction(
Instruction &
I);
132 return new RewriteStatepointsForGC();
136 "Make relocations explicit at statepoints",
false,
false)
202 "Found non-leaf call without deopt info!");
211 GCPtrLivenessData &
Data);
222 if (
auto *PT = dyn_cast<PointerType>(T))
226 return PT->getAddressSpace() == 1;
240 if (
auto VT = dyn_cast<VectorType>(T))
252 if (
VectorType *VT = dyn_cast<VectorType>(Ty))
254 if (
ArrayType *AT = dyn_cast<ArrayType>(Ty))
282 GCPtrLivenessData &OriginalLivenessData,
CallSite CS,
283 PartiallyConstructedSafepointRecord &Result) {
290 dbgs() <<
"Live Variables:\n";
291 for (
Value *V : LiveSet)
292 dbgs() <<
" " << V->getName() <<
" " << *V <<
"\n";
296 dbgs() <<
"Number live values: " << LiveSet.size() <<
"\n";
298 Result.LiveSet = LiveSet;
311 struct BaseDefiningValueResult {
316 const bool IsKnownBase;
317 BaseDefiningValueResult(
Value *BDV,
bool IsKnownBase)
318 : BDV(BDV), IsKnownBase(IsKnownBase) {
323 assert(!MustBeBase || MustBeBase == IsKnownBase);
340 static BaseDefiningValueResult
345 if (isa<Argument>(I))
347 return BaseDefiningValueResult(I,
true);
349 if (isa<Constant>(I))
355 if (isa<LoadInst>(I))
356 return BaseDefiningValueResult(I,
true);
358 if (isa<InsertElementInst>(I))
362 return BaseDefiningValueResult(I,
false);
364 if (isa<ShuffleVectorInst>(I))
370 return BaseDefiningValueResult(I,
false);
374 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I))
379 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
380 "unknown vector instruction - no base found for vector element");
381 return BaseDefiningValueResult(I,
false);
390 "Illegal to ask for the base pointer of a non-pointer type");
395 if (isa<Argument>(I))
398 return BaseDefiningValueResult(I,
true);
400 if (isa<Constant>(I)) {
411 return BaseDefiningValueResult(
415 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
416 Value *
Def = CI->stripPointerCasts();
419 assert(cast<PointerType>(Def->
getType())->getAddressSpace() ==
420 cast<PointerType>(CI->getType())->getAddressSpace() &&
421 "unsupported addrspacecast");
425 assert(!isa<CastInst>(Def) &&
"shouldn't find another cast here");
429 if (isa<LoadInst>(I))
431 return BaseDefiningValueResult(I,
true);
439 switch (II->getIntrinsicID()) {
443 case Intrinsic::experimental_gc_statepoint:
445 case Intrinsic::experimental_gc_relocate: {
451 case Intrinsic::gcroot:
456 "interaction with the gcroot mechanism is not supported");
462 if (isa<CallInst>(I) || isa<InvokeInst>(I))
463 return BaseDefiningValueResult(I,
true);
467 assert(!isa<LandingPadInst>(I) &&
"Landing Pad is unimplemented");
469 if (isa<AtomicCmpXchgInst>(I))
473 return BaseDefiningValueResult(I,
true);
475 assert(!isa<AtomicRMWInst>(I) &&
"Xchg handled above, all others are "
476 "binary ops which don't apply to pointers");
481 if (isa<ExtractValueInst>(I))
482 return BaseDefiningValueResult(I,
true);
486 assert(!isa<InsertValueInst>(I) &&
487 "Base pointer for a struct is meaningless");
493 if (isa<ExtractElementInst>(I))
497 return BaseDefiningValueResult(I,
false);
503 assert((isa<SelectInst>(I) || isa<PHINode>(I)) &&
504 "missing instruction case in findBaseDefiningValing");
505 return BaseDefiningValueResult(I,
false);
510 Value *&Cached = Cache[
I];
516 assert(Cache[I] !=
nullptr);
524 auto Found = Cache.find(Def);
525 if (Found != Cache.end()) {
527 return Found->second;
536 if (!isa<PHINode>(V) && !isa<SelectInst>(V) &&
537 !isa<ExtractElementInst>(V) && !isa<InsertElementInst>(V) &&
538 !isa<ShuffleVectorInst>(V)) {
542 if (isa<Instruction>(V) &&
543 cast<Instruction>(V)->getMetadata(
"is_base_value")) {
561 BDVState() : Status(
Unknown), BaseValue(nullptr) {}
563 explicit BDVState(Status Status,
Value *BaseValue =
nullptr)
564 : Status(Status), BaseValue(BaseValue) {
568 explicit BDVState(
Value *BaseValue) : Status(
Base), BaseValue(BaseValue) {}
570 Status getStatus()
const {
return Status; }
571 Value *getBaseValue()
const {
return BaseValue; }
573 bool isBase()
const {
return getStatus() ==
Base; }
574 bool isUnknown()
const {
return getStatus() ==
Unknown; }
575 bool isConflict()
const {
return getStatus() == Conflict; }
577 bool operator==(
const BDVState &Other)
const {
578 return BaseValue == Other.BaseValue && Status == Other.Status;
581 bool operator!=(
const BDVState &other)
const {
return !(*
this == other); }
590 switch (getStatus()) {
601 OS <<
" (" << getBaseValue() <<
" - "
602 << (getBaseValue() ? getBaseValue()->getName() :
"nullptr") <<
"): ";
619 switch (LHS.getStatus()) {
624 assert(LHS.getBaseValue() &&
"can't be null");
629 if (LHS.getBaseValue() == RHS.getBaseValue()) {
630 assert(LHS == RHS &&
"equality broken!");
633 return BDVState(BDVState::Conflict);
635 assert(RHS.isConflict() &&
"only three states!");
636 return BDVState(BDVState::Conflict);
638 case BDVState::Conflict:
646 static BDVState
meetBDVState(
const BDVState &LHS,
const BDVState &RHS) {
649 "Math is wrong: meet does not commute!");
686 auto isExpectedBDVType = [](
Value *BDV) {
687 return isa<PHINode>(BDV) || isa<SelectInst>(BDV) ||
688 isa<ExtractElementInst>(BDV) || isa<InsertElementInst>(BDV) ||
689 isa<ShuffleVectorInst>(BDV);
706 while (!Worklist.
empty()) {
710 auto visitIncomingValue = [&](
Value *InVal) {
716 assert(isExpectedBDVType(Base) &&
"the only non-base values "
717 "we see should be base defining values");
718 if (States.
insert(std::make_pair(Base, BDVState())).second)
721 if (
PHINode *PN = dyn_cast<PHINode>(Current)) {
722 for (
Value *InVal : PN->incoming_values())
723 visitIncomingValue(InVal);
724 }
else if (
SelectInst *
SI = dyn_cast<SelectInst>(Current)) {
725 visitIncomingValue(
SI->getTrueValue());
726 visitIncomingValue(
SI->getFalseValue());
727 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(Current)) {
728 visitIncomingValue(EE->getVectorOperand());
729 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(Current)) {
730 visitIncomingValue(
IE->getOperand(0));
731 visitIncomingValue(
IE->getOperand(1));
732 }
else if (
auto *SV = dyn_cast<ShuffleVectorInst>(Current)) {
733 visitIncomingValue(SV->getOperand(0));
734 visitIncomingValue(SV->getOperand(1));
743 DEBUG(
dbgs() <<
"States after initialization:\n");
744 for (
auto Pair : States) {
745 DEBUG(
dbgs() <<
" " << Pair.second <<
" for " << *Pair.first <<
"\n");
751 auto getStateForBDV = [&](
Value *baseValue) {
753 return BDVState(baseValue);
754 auto I = States.find(baseValue);
755 assert(I != States.end() &&
"lookup failed!");
759 bool Progress =
true;
762 const size_t OldSize = States.size();
769 for (
auto Pair : States) {
770 Value *BDV = Pair.first;
775 auto getStateForInput = [&](
Value *V)
mutable {
777 return getStateForBDV(BDV);
782 NewState =
meetBDVState(NewState, getStateForInput(
SI->getTrueValue()));
785 }
else if (
PHINode *PN = dyn_cast<PHINode>(BDV)) {
786 for (
Value *Val : PN->incoming_values())
787 NewState =
meetBDVState(NewState, getStateForInput(Val));
788 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(BDV)) {
792 meetBDVState(NewState, getStateForInput(EE->getVectorOperand()));
793 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(BDV)){
796 NewState =
meetBDVState(NewState, getStateForInput(
IE->getOperand(0)));
797 NewState =
meetBDVState(NewState, getStateForInput(
IE->getOperand(1)));
801 auto *SV = cast<ShuffleVectorInst>(BDV);
802 NewState =
meetBDVState(NewState, getStateForInput(SV->getOperand(0)));
803 NewState =
meetBDVState(NewState, getStateForInput(SV->getOperand(1)));
806 BDVState OldState = States[BDV];
807 if (OldState != NewState) {
809 States[BDV] = NewState;
813 assert(OldSize == States.size() &&
814 "fixed point shouldn't be adding any new nodes to state");
818 DEBUG(
dbgs() <<
"States after meet iteration:\n");
819 for (
auto Pair : States) {
820 DEBUG(
dbgs() <<
" " << Pair.second <<
" for " << *Pair.first <<
"\n");
826 for (
auto Pair : States) {
828 BDVState State = Pair.second;
830 assert(!State.isUnknown() &&
"Optimistic algorithm didn't complete!");
836 if (State.isBase() && isa<ExtractElementInst>(
I) &&
837 isa<VectorType>(State.getBaseValue()->getType())) {
838 auto *EE = cast<ExtractElementInst>(
I);
843 State.getBaseValue(), EE->getIndexOperand(),
"base_ee", EE);
845 States[
I] = BDVState(BDVState::Base, BaseInst);
851 assert(!isa<InsertElementInst>(I) || State.isConflict());
853 if (!State.isConflict())
859 if (isa<PHINode>(I)) {
862 assert(NumPreds > 0 &&
"how did we reach here");
870 }
else if (
auto *EE = dyn_cast<ExtractElementInst>(I)) {
875 }
else if (
auto *
IE = dyn_cast<InsertElementInst>(I)) {
882 auto *SV = cast<ShuffleVectorInst>(
I);
889 Instruction *BaseInst = MakeBaseInstPlaceholder(I);
892 States[
I] = BDVState(BDVState::Conflict, BaseInst);
910 assert(States.count(BDV));
911 Base = States[BDV].getBaseValue();
913 assert(Base &&
"Can't be null");
923 for (
auto Pair : States) {
925 BDVState State = Pair.second;
928 assert(!State.isUnknown() &&
"Optimistic algorithm didn't complete!");
929 if (!State.isConflict())
932 if (
PHINode *BasePHI = dyn_cast<PHINode>(State.getBaseValue())) {
933 PHINode *PN = cast<PHINode>(BDV);
935 for (
unsigned i = 0; i < NumPHIValues; i++) {
948 int BlockIndex = BasePHI->getBasicBlockIndex(InBB);
949 if (BlockIndex != -1) {
950 Value *OldBase = BasePHI->getIncomingValue(BlockIndex);
951 BasePHI->addIncoming(OldBase, InBB);
954 Value *
Base = getBaseForInput(InVal,
nullptr);
962 "Sanity -- findBaseOrBDV should be pure!");
971 BasePHI->addIncoming(Base, InBB);
973 assert(BasePHI->getNumIncomingValues() == NumPHIValues);
975 dyn_cast<SelectInst>(State.getBaseValue())) {
980 BaseSI->setTrueValue(getBaseForInput(SI->
getTrueValue(), BaseSI));
981 BaseSI->setFalseValue(getBaseForInput(SI->
getFalseValue(), BaseSI));
982 }
else if (
auto *BaseEE =
983 dyn_cast<ExtractElementInst>(State.getBaseValue())) {
984 Value *InVal = cast<ExtractElementInst>(BDV)->getVectorOperand();
987 BaseEE->setOperand(0, getBaseForInput(InVal, BaseEE));
988 }
else if (
auto *BaseIE = dyn_cast<InsertElementInst>(State.getBaseValue())){
989 auto *BdvIE = cast<InsertElementInst>(BDV);
990 auto UpdateOperand = [&](
int OperandIdx) {
991 Value *InVal = BdvIE->getOperand(OperandIdx);
992 Value *
Base = getBaseForInput(InVal, BaseIE);
993 BaseIE->setOperand(OperandIdx, Base);
998 auto *BaseSV = cast<ShuffleVectorInst>(State.getBaseValue());
999 auto *BdvSV = cast<ShuffleVectorInst>(BDV);
1000 auto UpdateOperand = [&](
int OperandIdx) {
1001 Value *InVal = BdvSV->getOperand(OperandIdx);
1002 Value *
Base = getBaseForInput(InVal, BaseSV);
1003 BaseSV->setOperand(OperandIdx, Base);
1013 for (
auto Pair : States) {
1014 auto *BDV = Pair.first;
1015 Value *
Base = Pair.second.getBaseValue();
1019 DEBUG(
dbgs() <<
"Updating base value cache"
1020 <<
" for: " << BDV->getName() <<
" from: "
1021 << (Cache.count(BDV) ? Cache[BDV]->getName().str() :
"none")
1022 <<
" to: " << Base->
getName() <<
"\n");
1024 if (Cache.count(BDV)) {
1026 "must be something we 'know' is a base pointer");
1030 "base relation should be stable");
1034 assert(Cache.count(Def));
1057 for (
Value *ptr : live) {
1059 assert(base &&
"failed to find base pointer");
1060 PointerToBase[ptr] = base;
1061 assert((!isa<Instruction>(base) || !isa<Instruction>(ptr) ||
1062 DT->
dominates(cast<Instruction>(base)->getParent(),
1063 cast<Instruction>(ptr)->
getParent())) &&
1064 "The base we found better dominate the derived pointer");
1072 PartiallyConstructedSafepointRecord &result) {
1077 errs() <<
"Base Pairs (w/o Relocation):\n";
1078 for (
auto &Pair : PointerToBase) {
1079 errs() <<
" derived ";
1080 Pair.first->printAsOperand(
errs(),
false);
1082 Pair.second->printAsOperand(
errs(),
false);
1087 result.PointerToBase = PointerToBase;
1094 PartiallyConstructedSafepointRecord &result);
1101 GCPtrLivenessData RevisedLivenessData;
1103 for (
size_t i = 0; i < records.
size(); i++) {
1104 struct PartiallyConstructedSafepointRecord &
info = records[i];
1126 "All PHI nodes should have been removed!");
1164 const int LiveStart,
1168 if (LiveVariables.
empty())
1172 auto ValIt =
find(LiveVec, Val);
1173 assert(ValIt != LiveVec.
end() &&
"Val not found in LiveVec!");
1174 size_t Index = std::distance(LiveVec.
begin(), ValIt);
1175 assert(Index < LiveVec.
size() &&
"Bug in std::find?");
1187 auto getGCRelocateDecl = [&] (
Type *Ty) {
1189 auto AS = Ty->getScalarType()->getPointerAddressSpace();
1191 if (
auto *VT = dyn_cast<VectorType>(Ty))
1202 for (
unsigned i = 0; i < LiveVariables.
size(); i++) {
1205 Builder.
getInt32(LiveStart + FindIndex(LiveVariables, BasePtrs[i]));
1208 Type *Ty = LiveVariables[i]->getType();
1209 if (!TypeToDeclMap.
count(Ty))
1210 TypeToDeclMap[Ty] = getGCRelocateDecl(Ty);
1211 Value *GCRelocateDecl = TypeToDeclMap[Ty];
1215 GCRelocateDecl, {StatepointToken, BaseIdx, LiveIdx},
1227 class DeferredReplacement {
1230 bool IsDeoptimize =
false;
1232 DeferredReplacement() {}
1236 assert(Old != New && Old && New &&
1237 "Cannot RAUW equal values or to / from null!");
1239 DeferredReplacement
D;
1245 static DeferredReplacement createDelete(
Instruction *ToErase) {
1246 DeferredReplacement
D;
1251 static DeferredReplacement createDeoptimizeReplacement(
Instruction *Old) {
1254 assert(
F &&
F->getIntrinsicID() == Intrinsic::experimental_deoptimize &&
1255 "Only way to construct a deoptimize deferred replacement");
1257 DeferredReplacement
D;
1259 D.IsDeoptimize =
true;
1264 void doReplacement() {
1268 assert(OldI != NewI &&
"Disallowed at construction?!");
1269 assert((!IsDeoptimize || !New) &&
1270 "Deoptimize instrinsics are not replaced!");
1292 const char *DeoptLowering =
"deopt-lowering";
1304 return "live-through";
1312 PartiallyConstructedSafepointRecord &Result,
1313 std::vector<DeferredReplacement> &Replacements) {
1331 if (
auto TransitionBundle =
1334 TransitionArgs = TransitionBundle->Inputs;
1340 bool IsDeoptimize =
false;
1351 if (DeoptLowering.
equals(
"live-in"))
1354 assert(DeoptLowering.
equals(
"live-through") &&
"Unsupported value!");
1358 if (
Function *
F = dyn_cast<Function>(CallTarget)) {
1359 if (
F->getIntrinsicID() == Intrinsic::experimental_deoptimize) {
1365 for (
Value *Arg : CallArgs)
1375 F->getParent()->getOrInsertFunction(
"__llvm_deoptimize", FTy);
1377 IsDeoptimize =
true;
1386 StatepointID, NumPatchBytes, CallTarget, Flags, CallArgs,
1387 TransitionArgs, DeoptArgs, GCArgs,
"safepoint_token");
1412 StatepointID, NumPatchBytes, CallTarget, ToReplace->
getNormalDest(),
1414 GCArgs,
"statepoint_token");
1430 "can't safely insert in this block!");
1437 Result.UnwindToken = ExceptionalToken;
1447 "can't safely insert in this block!");
1454 assert(Token &&
"Should be set in one of the above branches!");
1460 Replacements.push_back(
1461 DeferredReplacement::createDeoptimizeReplacement(CS.
getInstruction()));
1463 Token->
setName(
"statepoint_token");
1478 Replacements.emplace_back(
1481 Replacements.emplace_back(
1486 Result.StatepointToken = Token;
1500 PartiallyConstructedSafepointRecord &Result,
1501 std::vector<DeferredReplacement> &Replacements) {
1502 const auto &LiveSet = Result.LiveSet;
1503 const auto &PointerToBase = Result.PointerToBase;
1507 LiveVec.
reserve(LiveSet.size());
1508 BaseVec.
reserve(LiveSet.size());
1509 for (
Value *
L : LiveSet) {
1511 assert(PointerToBase.count(
L));
1532 for (
User *U : GCRelocs) {
1539 Value *Alloca = AllocaMap[OriginalValue];
1545 "Should always have one since it's not a terminator");
1547 Value *CastedRelocatedValue =
1548 Builder.CreateBitCast(Relocate,
1549 cast<AllocaInst>(Alloca)->getAllocatedType(),
1553 Store->
insertAfter(cast<Instruction>(CastedRelocatedValue));
1556 VisitedLiveValues.
insert(OriginalValue);
1568 for (
auto RematerializedValuePair: RematerializedValues) {
1569 Instruction *RematerializedValue = RematerializedValuePair.first;
1570 Value *OriginalValue = RematerializedValuePair.second;
1573 "Can not find alloca for rematerialized value");
1574 Value *Alloca = AllocaMap[OriginalValue];
1580 VisitedLiveValues.
insert(OriginalValue);
1592 int InitialAllocaNum = 0;
1594 if (isa<AllocaInst>(
I))
1602 std::size_t NumRematerializedValues = 0;
1608 auto emitAllocaFor = [&](
Value *LiveValue) {
1612 AllocaMap[LiveValue] = Alloca;
1617 for (
Value *V : Live)
1621 for (
const auto &Info : Records)
1622 for (
auto RematerializedValuePair : Info.RematerializedValues) {
1623 Value *OriginalValue = RematerializedValuePair.second;
1624 if (AllocaMap.
count(OriginalValue) != 0)
1627 emitAllocaFor(OriginalValue);
1628 ++NumRematerializedValues;
1640 for (
const auto &Info : Records) {
1651 if (isa<InvokeInst>(Statepoint)) {
1667 for (
auto Pair : AllocaMap) {
1669 AllocaInst *Alloca = cast<AllocaInst>(Pair.second);
1672 if (VisitedLiveValues.
count(Def)) {
1679 for (
auto *AI : ToClobber) {
1680 auto PT = cast<PointerType>(AI->getAllocatedType());
1689 if (
auto II = dyn_cast<InvokeInst>(Statepoint)) {
1690 InsertClobbersAt(&*II->getNormalDest()->getFirstInsertionPt());
1691 InsertClobbersAt(&*II->getUnwindDest()->getFirstInsertionPt());
1693 InsertClobbersAt(cast<Instruction>(Statepoint)->getNextNode());
1699 for (
auto Pair : AllocaMap) {
1701 Value *Alloca = Pair.second;
1710 if (!isa<ConstantExpr>(U)) {
1721 auto Last = std::unique(Uses.
begin(), Uses.
end());
1725 if (isa<PHINode>(
Use)) {
1736 Use->replaceUsesOfWith(Def, Load);
1744 if (
Instruction *Inst = dyn_cast<Instruction>(Def)) {
1745 if (
InvokeInst *Invoke = dyn_cast<InvokeInst>(Inst)) {
1748 BasicBlock *NormalDest = Invoke->getNormalDest();
1751 assert(!Inst->isTerminator() &&
1752 "The only TerminatorInst that can produce a value is "
1753 "InvokeInst which is handled above.");
1757 assert(isa<Argument>(Def));
1762 assert(PromotableAllocas.
size() == Live.size() + NumRematerializedValues &&
1763 "we must have the same allocas with lives");
1764 if (!PromotableAllocas.
empty()) {
1771 if (isa<AllocaInst>(
I))
1773 assert(InitialAllocaNum == 0 &&
"We must not introduce any extra allocas");
1808 Func, Values,
"", &*II->getNormalDest()->getFirstInsertionPt()));
1810 Func, Values,
"", &*II->getUnwindDest()->getFirstInsertionPt()));
1816 GCPtrLivenessData OriginalLivenessData;
1818 for (
size_t i = 0; i < records.
size(); i++) {
1819 struct PartiallyConstructedSafepointRecord &
info = records[i];
1832 Value *CurrentValue) {
1837 GEP->getPointerOperand());
1840 if (
CastInst *CI = dyn_cast<CastInst>(CurrentValue)) {
1841 if (!CI->isNoopCast(CI->getModule()->getDataLayout()))
1851 return CurrentValue;
1862 if (
CastInst *CI = dyn_cast<CastInst>(Instr)) {
1863 assert(CI->isNoopCast(CI->getModule()->getDataLayout()) &&
1864 "non noop cast is found during rematerialization");
1866 Type *SrcTy = CI->getOperand(0)->getType();
1871 Type *ValTy =
GEP->getSourceElementType();
1877 if (!
GEP->hasAllConstantIndices())
1897 for (
unsigned i = 0; i < PhiNum; i++)
1903 for (
unsigned i = 0; i < PhiNum; i++) {
1906 if (CIVI == CurrentIncomingValues.
end())
1908 BasicBlock *CurrentIncomingBB = CIVI->second;
1921 PartiallyConstructedSafepointRecord &Info,
1923 const unsigned int ChainLengthThreshold = 10;
1929 for (
Value *LiveValue: Info.LiveSet) {
1932 assert(Info.PointerToBase.count(LiveValue));
1933 Value *RootOfChain =
1938 if ( ChainToBase.
size() == 0 ||
1939 ChainToBase.
size() > ChainLengthThreshold)
1944 if (RootOfChain != Info.PointerToBase[LiveValue]) {
1947 if (!OrigRootPhi || !AlternateRootPhi)
1963 assert(Info.LiveSet.count(AlternateRootPhi));
1982 LiveValuesToBeDeleted.
push_back(LiveValue);
1992 auto rematerializeChain = [&ChainToBase](
2001 assert(isa<GetElementPtrInst>(Instr) || isa<CastInst>(Instr));
2005 ClonedValue->
setName(Instr->getName() +
".remat");
2009 if (LastClonedValue) {
2017 "incorrect use in rematerialization chain");
2020 assert(OpValue != RootOfChain && OpValue != AlternateLiveBase);
2029 if (RootOfChain != AlternateLiveBase)
2033 LastClonedValue = ClonedValue;
2037 return LastClonedValue;
2045 Instruction *RematerializedValue = rematerializeChain(
2046 InsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2047 Info.RematerializedValues[RematerializedValue] = LiveValue;
2056 Instruction *NormalRematerializedValue = rematerializeChain(
2057 NormalInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2058 Instruction *UnwindRematerializedValue = rematerializeChain(
2059 UnwindInsertBefore, RootOfChain, Info.PointerToBase[LiveValue]);
2061 Info.RematerializedValues[NormalRematerializedValue] = LiveValue;
2062 Info.RematerializedValues[UnwindRematerializedValue] = LiveValue;
2067 for (
auto LiveValue: LiveValuesToBeDeleted) {
2068 Info.LiveSet.remove(LiveValue);
2077 std::set<CallSite> Uniqued;
2078 Uniqued.insert(ToUpdate.
begin(), ToUpdate.
end());
2079 assert(Uniqued.size() == ToUpdate.
size() &&
"no duplicates please!");
2082 assert(CS.getInstruction()->getFunction() == &
F);
2092 auto *II = cast<InvokeInst>(CS.getInstruction());
2110 "support for FCA unimplemented");
2131 for (
size_t i = 0; i < Records.size(); i++) {
2132 PartiallyConstructedSafepointRecord &
info = Records[i];
2151 for (
size_t i = 0; i < Records.size(); i++) {
2152 PartiallyConstructedSafepointRecord &Info = Records[i];
2155 for (
auto Pair : Info.PointerToBase)
2167 for (
auto &Info : Records) {
2168 errs() <<
"Base Pairs: (w/Relocation)\n";
2169 for (
auto Pair : Info.PointerToBase) {
2170 errs() <<
" derived ";
2171 Pair.first->printAsOperand(
errs(),
false);
2173 Pair.second->printAsOperand(
errs(),
false);
2187 for (
auto &Info : Records)
2188 for (
auto &BasePair : Info.PointerToBase)
2189 if (isa<Constant>(BasePair.second))
2190 Info.LiveSet.remove(BasePair.first);
2193 CI->eraseFromParent();
2200 for (
size_t i = 0; i < Records.size(); i++)
2206 std::vector<DeferredReplacement> Replacements;
2214 for (
size_t i = 0; i < Records.size(); i++)
2219 for (
auto &PR : Replacements)
2222 Replacements.clear();
2224 for (
auto &Info : Records) {
2233 Info.LiveSet.clear();
2234 Info.PointerToBase.clear();
2239 for (
size_t i = 0; i < Records.size(); i++) {
2240 PartiallyConstructedSafepointRecord &Info = Records[i];
2256 "statepoint must be reachable or liveness is meaningless");
2258 if (!isa<Instruction>(V))
2261 auto *LiveInst = cast<Instruction>(V);
2263 "unreachable values should never be live");
2265 "basic SSA liveness expectation violated by liveness analysis");
2273 for (
auto *
Ptr : Live)
2275 "must be a gc pointer type");
2279 return !Records.empty();
2283 template <
typename AttrHolder>
2287 if (AH.getDereferenceableBytes(Index))
2289 AH.getDereferenceableBytes(Index)));
2290 if (AH.getDereferenceableOrNullBytes(Index))
2292 AH.getDereferenceableOrNullBytes(Index)));
2297 AH.setAttributes(AH.getAttributes().removeAttributes(Ctx, Index, R));
2301 RewriteStatepointsForGC::stripNonValidAttributesFromPrototype(
Function &
F) {
2305 if (isa<PointerType>(
A.getType()))
2313 void RewriteStatepointsForGC::stripInvalidMetadataFromInstruction(
Instruction &
I) {
2315 if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
2343 void RewriteStatepointsForGC::stripNonValidAttributesAndMetadataFromBody(
Function &F) {
2353 assert(MD->getNumOperands() < 5 &&
"unrecognized metadata shape!");
2354 bool IsImmutableTBAA =
2355 MD->getNumOperands() == 4 &&
2356 mdconst::extract<ConstantInt>(MD->getOperand(3))->getValue() == 1;
2358 if (!IsImmutableTBAA)
2361 MDNode *
Base = cast<MDNode>(MD->getOperand(0));
2362 MDNode *Access = cast<MDNode>(MD->getOperand(1));
2364 mdconst::extract<ConstantInt>(MD->getOperand(2))->getZExtValue();
2367 Builder.createTBAAStructTagNode(Base, Access, Offset);
2371 stripInvalidMetadataFromInstruction(I);
2374 for (
int i = 0, e =
CS.arg_size(); i != e; i++)
2375 if (isa<PointerType>(
CS.getArgument(i)->getType()))
2377 if (isa<PointerType>(
CS.getType()))
2388 const auto &FunctionGCName = F.
getGC();
2389 const StringRef StatepointExampleName(
"statepoint-example");
2391 return (StatepointExampleName == FunctionGCName) ||
2392 (CoreCLRName == FunctionGCName);
2397 void RewriteStatepointsForGC::stripNonValidAttributesAndMetadata(
Module &M) {
2403 stripNonValidAttributesFromPrototype(F);
2406 stripNonValidAttributesAndMetadataFromBody(F);
2409 bool RewriteStatepointsForGC::runOnFunction(
Function &F) {
2419 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>(
F).getDomTree();
2421 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2433 bool HasUnreachableStatepoint =
false;
2436 if (NeedsRewrite(I)) {
2440 HasUnreachableStatepoint =
true;
2444 bool MadeChange =
false;
2450 if (HasUnreachableStatepoint)
2454 if (ParsePointNeeded.
empty())
2462 if (BB.getUniquePredecessor()) {
2481 if (
auto *BI = dyn_cast<BranchInst>(TI))
2482 if (BI->isConditional())
2483 return dyn_cast<Instruction>(BI->getCondition());
2489 if (
auto *Cond = getConditionInst(TI))
2492 if (isa<ICmpInst>(Cond) && Cond->hasOneUse()) {
2494 Cond->moveBefore(TI);
2519 if (isa<PHINode>(I))
2525 "support for FCA unimplemented");
2545 for (
auto &I : *Succ) {
2552 "support for FCA unimplemented");
2572 for (
Value *V : Live) {
2573 if (
auto *I = dyn_cast<Instruction>(V)) {
2577 if (TermOkay && TI == I)
2580 "basic SSA liveness expectation violated by liveness analysis");
2597 GCPtrLivenessData &
Data) {
2603 Data.LiveSet[&BB].clear();
2608 assert(!Data.LiveSet[&BB].count(
Kill) &&
"live set contains kill");
2613 Data.LiveIn[&BB] = Data.LiveSet[&BB];
2614 Data.LiveIn[&BB].set_union(Data.LiveOut[&BB]);
2615 Data.LiveIn[&BB].set_subtract(Data.KillSet[&BB]);
2616 if (!Data.LiveIn[&BB].empty())
2621 while (!Worklist.
empty()) {
2627 const auto OldLiveOutSize = LiveOut.
size();
2629 assert(Data.LiveIn.count(Succ));
2633 if (OldLiveOutSize == LiveOut.
size()) {
2639 Data.LiveOut[BB] = LiveOut;
2646 assert(Data.LiveIn.count(BB));
2649 if (OldLiveIn.size() != LiveTmp.
size()) {
2650 Data.LiveIn[BB] = LiveTmp;
2669 assert(Data.LiveOut.count(BB));
2678 LiveOut.remove(Inst);
2679 Out.insert(LiveOut.begin(), LiveOut.end());
2684 PartiallyConstructedSafepointRecord &Info) {
2691 for (
auto KVPair : Info.PointerToBase)
2692 Bases.
insert(KVPair.second);
2697 for (
auto V : Updated)
2698 if (Info.PointerToBase.insert({V, V}).
second) {
2699 assert(Bases.count(V) &&
"Can't find base for unexpected live value!");
2704 for (
auto V : Updated)
2705 assert(Info.PointerToBase.count(V) &&
2706 "Must be able to find base for live value!");
2712 for (
auto KVPair : Info.PointerToBase)
2713 if (!Updated.count(KVPair.first))
2714 ToErase.
insert(KVPair.first);
2716 for (
auto *V : ToErase)
2717 Info.PointerToBase.erase(V);
2720 for (
auto KVPair : Info.PointerToBase)
2721 assert(Updated.count(KVPair.first) &&
"record for non-live value");
2724 Info.LiveSet = Updated;
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
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 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.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
This class represents an incoming formal argument to a Function.
static Value * findBaseDefiningValueCached(Value *I, DefiningValueMapTy &Cache)
Returns the base defining value for this value.
static bool AreEquivalentPhiNodes(PHINode &OrigRootPhi, PHINode &AlternateRootPhi)
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.
LLVM_NODISCARD T pop_back_val()
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Instruction * StatepointToken
The new gc.statepoint instruction itself.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
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.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
StatepointDirectives parseStatepointDirectivesFromAttrs(AttributeList AS)
Parse out statepoint directives from the function attributes present in AS.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Attribute getAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return the attribute object that exists at the given index.
static ConstantAggregateZero * get(Type *Ty)
static void rematerializeLiveValues(CallSite CS, PartiallyConstructedSafepointRecord &Info, TargetTransformInfo &TTI)
static void computeLiveOutSeed(BasicBlock *BB, SetVector< Value * > &LiveTmp)
static StringRef getDeoptLowering(CallSite CS)
ilist_iterator< OptionsT,!IsReverse, IsConst > getReverse() const
Get a reverse iterator to the same node.
This class represents a function call, abstracting a target machine's calling convention.
MapVector< BasicBlock *, SetVector< Value * > > KillSet
Values defined in this block.
unsigned gcArgsStartIdx() const
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="")
brief Create an invoke to the experimental.gc.statepoint intrinsic to start a new statepoint sequence...
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...
MapVector< BasicBlock *, SetVector< Value * > > LiveIn
Values live into this basic block (i.e.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
This class implements a map that also provides access to all stored values in a deterministic order...
The two locations do not alias at all.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
An instruction for reading from memory.
reverse_iterator rbegin()
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
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)
size_type size() const
Determine the number of elements in the SetVector.
static void computeLiveInValues(DominatorTree &DT, Function &F, GCPtrLivenessData &Data)
Compute the live-in set for every basic block in the function.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
void setCallingConv(CallingConv::ID CC)
static void relocationViaAlloca(Function &F, DominatorTree &DT, ArrayRef< Value * > Live, ArrayRef< PartiallyConstructedSafepointRecord > Records)
Do all the relocation update via allocas and mem2reg.
Value * getDerivedPtr() const
AnalysisUsage & addRequired()
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
rewrite statepoints for Make relocations at false
#define INITIALIZE_PASS_DEPENDENCY(depName)
static unsigned chainToBasePointerCost(SmallVectorImpl< Instruction * > &Chain, TargetTransformInfo &TTI)
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
This class represents the LLVM 'select' instruction.
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...
Class to represent struct types.
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.
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.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
static bool isGCPointerType(Type *T)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
bool isCall() const
Return true if a CallInst is enclosed.
static void makeStatepointExplicit(DominatorTree &DT, CallSite CS, PartiallyConstructedSafepointRecord &Result, std::vector< DeferredReplacement > &Replacements)
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 ...
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
bool remove(const value_type &X)
Remove an item from the set vector.
LLVM_NODISCARD bool empty() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static cl::opt< bool > PrintLiveSet("spp-print-liveset", cl::Hidden, cl::init(false))
bool insert(const value_type &X)
Insert a new element into the SetVector.
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...
const T & getValue() const LLVM_LVALUE_FUNCTION
Class to represent array types.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
This class represents a no-op cast from one type to another.
bool empty() const
Determine if the SetVector is empty or not.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
AttrBuilder & remove(const AttrBuilder &B)
Remove the attributes from the builder.
An instruction for storing to memory.
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.
static Value * findRematerializableChainToBasePointer(SmallVectorImpl< Instruction * > &ChainToBase, Value *CurrentValue)
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...
size_t size() const
size - Get the array size.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
BasicBlock * getNormalDest() const
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
iterator find(const_arg_type_t< KeyT > Val)
static SetVector< Value * > computeKillSet(BasicBlock *BB)
bool isInvoke() const
Return true if a InvokeInst is enclosed.
CallSiteTy::arg_iterator gc_args_begin() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Type * getReturnType() const
Returns the type of the ret val.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
initializer< Ty > init(const Ty &Val)
static void RemoveNonValidAttrAtIndex(LLVMContext &Ctx, AttrHolder &AH, unsigned Index)
Optional< OperandBundleUse > getOperandBundle(StringRef Name) const
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
Subclasses of this class are all able to terminate a basic block.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
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)
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
MapVector< Value *, Value * > DefiningValueMapTy
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.
bool isVectorTy() const
True if this is an instance of VectorType.
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)
CallSiteTy::arg_iterator gc_args_end() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
static cl::opt< unsigned > RematerializationThreshold("spp-rematerialization-threshold", cl::Hidden, cl::init(6))
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
static AttributeList legalizeCallAttributes(AttributeList AL)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
std::pair< iterator, bool > insert(const ValueT &V)
iterator_range< arg_iterator > gc_args() const
range adapter for gc arguments
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...
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...
unsigned getAllocaAddrSpace() const
Optional< uint32_t > NumPatchBytes
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static void insertRelocationStores(iterator_range< Value::user_iterator > GCRelocs, DenseMap< Value *, Value * > &AllocaMap, DenseSet< Value * > &VisitedLiveValues)
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
A specialization of it's base class for read-write access to a gc.statepoint.
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if this function has the given attribute.
Interval::pred_iterator pred_end(Interval *I)
AttributeList getAttributes() const
Get the parameter attributes of the call.
self_iterator getIterator()
SetVector< Value * > StatepointLiveSetTy
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
bool callsGCLeafFunction(ImmutableCallSite CS)
Return true if the CallSite CS calls a gc leaf function.
rewrite statepoints for gc
bool empty() const
empty - Check if the array is empty.
void setTailCallKind(TailCallKind TCK)
static bool containsGCPtrType(Type *Ty)
Returns true if this type contains a gc pointer whether we know how to handle that type or not...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Type * getType() const
Return the type of the instruction that generated this call site.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
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...
LLVMContext & getContext() const
All values hold a context through their type.
INITIALIZE_PASS_BEGIN(RewriteStatepointsForGC,"rewrite-statepoints-for-gc","Make relocations explicit at statepoints", false, false) INITIALIZE_PASS_END(RewriteStatepointsForGC
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const Value * getTrueValue() const
static Value * findBaseOrBDV(Value *I, DefiningValueMapTy &Cache)
Return a base pointer for this value if known.
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.
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
static void findBasePointers(const StatepointLiveSetTy &live, MapVector< Value *, Value * > &PointerToBase, DominatorTree *DT, DefiningValueMapTy &DVCache)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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))
rewrite statepoints for Make relocations at statepoints
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
BasicBlock * getUnwindDest() const
MapVector< AssertingVH< Instruction >, AssertingVH< Value > > RematerializedValueMapTy
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...
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
InstrTy * getInstruction() const
bool isEmpty() const
Return true if there are no attributes.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI=nullptr)
Remove all blocks that can not be reached from the function's entry.
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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)
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
void initializeRewriteStatepointsForGCPass(PassRegistry &)
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
TailCallKind getTailCallKind() const
Indicates that this statepoint is a transition from GC-aware code to code that is not GC-aware...
bool empty() const
Return true if the builder contains no target-independent attributes.
LLVM_NODISCARD T pop_back_val()
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
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...
const BasicBlock & getEntryBlock() const
static const Function * getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin)
AttributeSet getFnAttributes() const
The function attributes are returned.
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.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool ClobberNonLive
static void checkBasicSSA(DominatorTree &DT, SetVector< Value * > &Live, TerminatorInst *TI, bool TermOkay=false)
Check that the items in 'Live' dominate 'TI'.
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)
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
bool isStatepointDirectiveAttr(Attribute Attr)
Return true if the the Attr is an attribute that is a statepoint directive.
Optional< uint64_t > StatepointID
Value * getIncomingValueForBlock(const BasicBlock *BB) const
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)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
llvm_unreachable("Unknown RegBank!")
Call sites that get wrapped by a gc.statepoint (currently only in RewriteStatepointsForGC and potenti...
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static std::vector< std::string > Flags
bool operator!=(uint64_t V1, const APInt &V2)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static void insertRematerializationStores(const RematerializedValueMapTy &RematerializedValues, DenseMap< Value *, Value * > &AllocaMap, DenseSet< Value * > &VisitedLiveValues)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
AttributeList getAttributes() const
Return the parameter attributes for this invoke.
static cl::opt< bool > PrintLiveSetSize("spp-print-liveset-size", cl::Hidden, cl::init(false))
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
static bool isUnhandledGCPointerType(Type *Ty)
Establish a view to a call site for examination.
AttributeList getAttributes() const
Return the parameter attributes for this call.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
const std::string & getGC() const
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 ...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
iterator_range< value_op_iterator > operand_values()
static void makeStatepointExplicitImpl(const CallSite CS, const SmallVectorImpl< Value * > &BasePtrs, const SmallVectorImpl< Value * > &LiveVariables, PartiallyConstructedSafepointRecord &Result, std::vector< DeferredReplacement > &Replacements)
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 Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
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...
bool isStatepoint(ImmutableCallSite CS)
StringRef getValueAsString() const
Return the attribute's value as a string.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it's an indirect...
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)
ModulePass * createRewriteStatepointsForGCPass()
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)
void setCallingConv(CallingConv::ID CC)
MapVector< BasicBlock *, SetVector< Value * > > LiveOut
Values live out of this basic block (i.e.
LLVMContext & getContext() const
Retrieve the LLVM context.
This class implements an extremely fast bulk output stream that can only output to a stream...
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
inst_range instructions(Function *F)
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
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)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
LocationClass< Ty > location(Ty &L)
const BasicBlock * getParent() 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()
A wrapper class for inspecting calls to intrinsic functions.
LLVMContext & getContext() const
Get the global data context.
bool isVoidTy() const
Return true if this is 'void'.
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...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.