74 #define DEBUG_TYPE "code-extractor" 82 cl::desc(
"Aggregate arguments to code-extracted functions"));
87 bool AllowVarArgs,
bool AllowAlloca) {
100 while (!ToVisit.
empty()) {
102 if (!Visited.
insert(Curr).second)
104 if (isa<BlockAddress const>(Curr))
107 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->
getParent() != &BB)
110 for (
auto const &U : Curr->
operands()) {
111 if (
auto *UU = dyn_cast<User>(U))
119 if (isa<AllocaInst>(
I)) {
125 if (
const auto *II = dyn_cast<InvokeInst>(
I)) {
128 if (
auto *UBB = II->getUnwindDest())
129 if (!Result.
count(UBB))
136 if (
const auto *CSI = dyn_cast<CatchSwitchInst>(
I)) {
137 if (
auto *UBB = CSI->getUnwindDest())
138 if (!Result.
count(UBB))
140 for (
auto *HBB : CSI->handlers())
141 if (!Result.
count(const_cast<BasicBlock*>(HBB)))
148 if (
const auto *CPI = dyn_cast<CatchPadInst>(
I)) {
149 for (
const auto *U : CPI->users())
150 if (
const auto *CRI = dyn_cast<CatchReturnInst>(U))
151 if (!Result.
count(const_cast<BasicBlock*>(CRI->getParent())))
159 if (
const auto *CPI = dyn_cast<CleanupPadInst>(
I)) {
160 for (
const auto *U : CPI->users())
161 if (
const auto *CRI = dyn_cast<CleanupReturnInst>(U))
162 if (!Result.
count(const_cast<BasicBlock*>(CRI->getParent())))
166 if (
const auto *CRI = dyn_cast<CleanupReturnInst>(
I)) {
167 if (
auto *UBB = CRI->getUnwindDest())
168 if (!Result.
count(UBB))
173 if (
const CallInst *CI = dyn_cast<CallInst>(
I)) {
174 if (
const Function *
F = CI->getCalledFunction()) {
175 auto IID =
F->getIntrinsicID();
176 if (IID == Intrinsic::vastart) {
185 if (IID == Intrinsic::eh_typeid_for)
197 bool AllowVarArgs,
bool AllowAlloca) {
198 assert(!BBs.
empty() &&
"The set of blocks to extract must be non-empty");
208 if (!Result.insert(BB))
212 LLVM_DEBUG(
dbgs() <<
"Region front block: " << Result.front()->getName()
215 for (
auto *BB : Result) {
220 if (BB == Result.front()) {
222 LLVM_DEBUG(
dbgs() <<
"The first block cannot be an unwind block\n");
231 if (!Result.count(PBB)) {
232 LLVM_DEBUG(
dbgs() <<
"No blocks in this region may have entries from " 233 "outside the region except for the first block!\n" 234 <<
"Problematic source BB: " << BB->getName() <<
"\n" 235 <<
"Problematic destination BB: " << PBB->getName()
247 bool AllowVarArgs,
bool AllowAlloca,
250 BPI(BPI), AC(AC), AllowVarArgs(AllowVarArgs),
259 BPI(BPI), AC(AC), AllowVarArgs(
false),
269 if (Blocks.
count(
I->getParent()))
278 if (isa<Argument>(V))
return true;
280 if (!Blocks.
count(
I->getParent()))
287 auto hasNonCommonExitSucc = [&](
BasicBlock *Block) {
290 if (Blocks.
count(Succ))
292 if (!CommonExitBlock) {
293 CommonExitBlock = Succ;
296 if (CommonExitBlock != Succ)
302 if (
any_of(Blocks, hasNonCommonExitSucc))
305 return CommonExitBlock;
310 for (
Instruction &II : BB.instructionsWithoutDebug())
311 if (
auto *AI = dyn_cast<AllocaInst>(&II))
312 Allocas.push_back(AI);
314 findSideEffectInfoForBlock(BB);
318 void CodeExtractorAnalysisCache::findSideEffectInfoForBlock(
BasicBlock &BB) {
320 unsigned Opcode = II.getOpcode();
321 Value *MemAddr =
nullptr;
333 if (dyn_cast<Constant>(MemAddr))
336 if (!isa<AllocaInst>(Base)) {
337 SideEffectingBlocks.insert(&BB);
340 BaseMemAddrs[&BB].insert(Base);
348 SideEffectingBlocks.insert(&BB);
352 if (II.mayHaveSideEffects()) {
353 SideEffectingBlocks.insert(&BB);
363 if (SideEffectingBlocks.count(&BB))
365 auto It = BaseMemAddrs.find(&BB);
366 if (It != BaseMemAddrs.end())
367 return It->second.count(Addr);
376 if (Blocks.count(&BB))
386 BasicBlock *SinglePredFromOutlineRegion =
nullptr;
387 assert(!Blocks.count(CommonExitBlock) &&
388 "Expect a block outside the region!");
390 if (!Blocks.count(Pred))
392 if (!SinglePredFromOutlineRegion) {
393 SinglePredFromOutlineRegion = Pred;
394 }
else if (SinglePredFromOutlineRegion != Pred) {
395 SinglePredFromOutlineRegion =
nullptr;
400 if (SinglePredFromOutlineRegion)
401 return SinglePredFromOutlineRegion;
407 while (I != BB->
end()) {
420 assert(!getFirstPHI(CommonExitBlock) &&
"Phi not expected");
429 if (Blocks.count(Pred))
434 Blocks.insert(CommonExitBlock);
435 return CommonExitBlock;
442 CodeExtractor::LifetimeMarkerInfo
446 LifetimeMarkerInfo
Info;
455 Info.LifeStart = IntrInst;
460 Info.LifeEnd = IntrInst;
469 if (!Info.LifeStart || !Info.LifeEnd)
475 if ((Info.SinkLifeStart || Info.HoistLifeEnd) &&
480 if (Info.HoistLifeEnd && !ExitBlock)
492 auto moveOrIgnoreLifetimeMarkers =
493 [&](
const LifetimeMarkerInfo &LMI) ->
bool {
496 if (LMI.SinkLifeStart) {
499 SinkCands.
insert(LMI.LifeStart);
501 if (LMI.HoistLifeEnd) {
502 LLVM_DEBUG(
dbgs() <<
"Hoisting lifetime.end: " << *LMI.LifeEnd <<
"\n");
503 HoistCands.
insert(LMI.LifeEnd);
512 if (Blocks.count(BB))
521 LifetimeMarkerInfo MarkerInfo = getLifetimeMarkers(CEAC, AI, ExitBlock);
522 bool Moved = moveOrIgnoreLifetimeMarkers(MarkerInfo);
533 if (U->stripInBoundsConstantOffsets() == AI) {
535 LifetimeMarkerInfo LMI = getLifetimeMarkers(CEAC, Bitcast, ExitBlock);
551 if (Bitcasts.
empty())
554 LLVM_DEBUG(
dbgs() <<
"Sinking alloca (via bitcast): " << *AI <<
"\n");
556 for (
unsigned I = 0,
E = Bitcasts.
size();
I !=
E; ++
I) {
558 const LifetimeMarkerInfo &LMI = BitcastLifetimeInfo[
I];
560 "Unsafe to sink bitcast without lifetime markers");
561 moveOrIgnoreLifetimeMarkers(LMI);
563 LLVM_DEBUG(
dbgs() <<
"Sinking bitcast-of-alloca: " << *BitcastAddr
565 SinkCands.
insert(BitcastAddr);
580 auto containsVarArgIntrinsic = [](
const Instruction &
I) {
581 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
583 return Callee->getIntrinsicID() == Intrinsic::vastart ||
584 Callee->getIntrinsicID() == Intrinsic::vaend;
588 for (
auto &BB : *F) {
589 if (Blocks.count(&BB))
604 for (
auto &OI : II.operands()) {
622 void CodeExtractor::severSplitPHINodesOfEntry(
BasicBlock *&Header) {
623 unsigned NumPredsFromRegion = 0;
624 unsigned NumPredsOutsideRegion = 0;
635 ++NumPredsFromRegion;
637 ++NumPredsOutsideRegion;
641 if (NumPredsOutsideRegion <= 1)
return;
653 Blocks.remove(OldPred);
654 Blocks.insert(NewBB);
659 if (NumPredsFromRegion) {
660 PHINode *PN = cast<PHINode>(OldPred->begin());
672 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
673 PHINode *PN = cast<PHINode>(AfterPHIs);
679 NewPN->addIncoming(PN, OldPred);
698 void CodeExtractor::severSplitPHINodesOfExits(
703 for (
PHINode &PN : ExitBB->phis()) {
706 for (
unsigned i = 0; i < PN.getNumIncomingValues(); ++i)
707 if (Blocks.count(PN.getIncomingBlock(i)))
713 if (IncomingVals.
size() <= 1)
720 ExitBB->getName() +
".split",
721 ExitBB->getParent(), ExitBB);
725 if (Blocks.count(PredBB))
726 PredBB->getTerminator()->replaceUsesOfWith(ExitBB, NewBB);
728 Blocks.insert(NewBB);
735 for (
unsigned i : IncomingVals)
736 NewPN->
addIncoming(PN.getIncomingValue(i), PN.getIncomingBlock(i));
737 for (
unsigned i :
reverse(IncomingVals))
738 PN.removeIncomingValue(i,
false);
739 PN.addIncoming(NewPN, NewBB);
744 void CodeExtractor::splitReturnBlocks() {
746 if (
ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) {
748 Block->splitBasicBlock(RI->getIterator(), Block->getName() +
".ret");
777 switch (NumExitBlocks) {
784 std::vector<Type *> paramTy;
787 for (
Value *value : inputs) {
789 paramTy.push_back(value->getType());
793 for (
Value *output : outputs) {
796 paramTy.push_back(output->getType());
802 dbgs() <<
"Function type: " << *RetTy <<
" f(";
803 for (
Type *i : paramTy)
804 dbgs() << *i <<
", ";
809 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
816 AllowVarArgs && oldFunction->
isVarArg());
818 std::string SuffixToUse =
825 oldFunction->
getName() +
"." + SuffixToUse, M);
842 if (Attr.isStringAttribute()) {
843 if (Attr.getKindAsString() ==
"thunk")
846 switch (Attr.getKindAsEnum()) {
850 case Attribute::Alignment:
851 case Attribute::AllocSize:
852 case Attribute::ArgMemOnly:
853 case Attribute::Builtin:
854 case Attribute::ByVal:
856 case Attribute::Dereferenceable:
857 case Attribute::DereferenceableOrNull:
858 case Attribute::InAlloca:
859 case Attribute::InReg:
860 case Attribute::InaccessibleMemOnly:
861 case Attribute::InaccessibleMemOrArgMemOnly:
863 case Attribute::Naked:
864 case Attribute::Nest:
866 case Attribute::NoBuiltin:
867 case Attribute::NoCapture:
868 case Attribute::NoReturn:
869 case Attribute::NoSync:
871 case Attribute::NonNull:
872 case Attribute::ReadNone:
873 case Attribute::ReadOnly:
874 case Attribute::Returned:
875 case Attribute::ReturnsTwice:
876 case Attribute::SExt:
877 case Attribute::Speculatable:
878 case Attribute::StackAlignment:
879 case Attribute::StructRet:
880 case Attribute::SwiftError:
881 case Attribute::SwiftSelf:
882 case Attribute::WillReturn:
883 case Attribute::WriteOnly:
884 case Attribute::ZExt:
885 case Attribute::ImmArg:
889 case Attribute::AlwaysInline:
891 case Attribute::NoRecurse:
892 case Attribute::InlineHint:
893 case Attribute::MinSize:
894 case Attribute::NoDuplicate:
895 case Attribute::NoFree:
896 case Attribute::NoImplicitFloat:
897 case Attribute::NoInline:
898 case Attribute::NonLazyBind:
899 case Attribute::NoRedZone:
900 case Attribute::NoUnwind:
901 case Attribute::OptForFuzzing:
902 case Attribute::OptimizeNone:
903 case Attribute::OptimizeForSize:
904 case Attribute::SafeStack:
905 case Attribute::ShadowCallStack:
906 case Attribute::SanitizeAddress:
907 case Attribute::SanitizeMemory:
908 case Attribute::SanitizeThread:
909 case Attribute::SanitizeHWAddress:
910 case Attribute::SanitizeMemTag:
911 case Attribute::SpeculativeLoadHardening:
912 case Attribute::StackProtect:
913 case Attribute::StackProtectReq:
914 case Attribute::StackProtectStrong:
915 case Attribute::StrictFP:
916 case Attribute::UWTable:
917 case Attribute::NoCfCheck:
930 for (
unsigned i = 0,
e = inputs.size(); i !=
e; ++i) {
938 StructTy, &*AI, Idx,
"gep_" + inputs[i]->
getName(), TI);
939 RewriteVal =
new LoadInst(StructTy->getElementType(i),
GEP,
940 "loadgep_" + inputs[i]->getName(), TI);
944 std::vector<User *>
Users(inputs[i]->user_begin(), inputs[i]->user_end());
947 if (Blocks.count(inst->getParent()))
948 inst->replaceUsesOfWith(inputs[i], RewriteVal);
952 if (!AggregateArgs) {
954 for (
unsigned i = 0,
e = inputs.size(); i !=
e; ++i, ++AI)
955 AI->
setName(inputs[i]->getName());
956 for (
unsigned i = 0,
e = outputs.size(); i !=
e; ++i, ++AI)
957 AI->
setName(outputs[i]->getName()+
".out");
964 for (
auto &U :
Users)
968 if (
I->isTerminator() &&
I->getFunction() == oldFunction &&
969 !Blocks.count(
I->getParent()))
970 I->replaceUsesOfWith(header, newHeader);
985 for (
auto It = BB->
begin(), End = BB->
end(); It != End;) {
988 if (!II || !II->isLifetimeStartOrEnd())
998 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
999 LifetimesStart.
insert(Mem);
1000 II->eraseFromParent();
1022 bool InsertBefore) {
1023 for (
Value *Mem : Objects) {
1026 "Input memory not defined in original function");
1027 Value *&MemAsI8Ptr = Bitcasts[Mem];
1029 if (Mem->getType() == Int8PtrTy)
1040 Marker->insertBefore(Term);
1044 if (!LifetimesStart.
empty()) {
1046 M, llvm::Intrinsic::lifetime_start, Int8PtrTy);
1047 insertMarkers(StartFn, LifetimesStart,
true);
1050 if (!LifetimesEnd.
empty()) {
1052 M, llvm::Intrinsic::lifetime_end, Int8PtrTy);
1053 insertMarkers(EndFn, LifetimesEnd,
false);
1063 ValueSet &outputs) {
1066 std::vector<Value *> params, StructValues, ReloadOutputs, Reloads;
1076 for (
Value *input : inputs) {
1080 params.push_back(input);
1081 if (input->isSwiftError())
1088 for (
Value *output : outputs) {
1089 if (AggregateArgs) {
1090 StructValues.push_back(output);
1094 nullptr, output->getName() +
".loc",
1096 ReloadOutputs.push_back(alloca);
1097 params.push_back(alloca);
1103 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
1104 std::vector<Type *> ArgTypes;
1106 ve = StructValues.end(); v != ve; ++v)
1107 ArgTypes.push_back((*v)->getType());
1114 params.push_back(Struct);
1116 for (
unsigned i = 0,
e = inputs.size(); i !=
e; ++i) {
1121 StructArgTy, Struct, Idx,
"gep_" + StructValues[i]->
getName());
1130 NumExitBlocks > 1 ?
"targetBlock" :
"");
1142 for (
unsigned SwiftErrArgNo : SwiftErrorArgs) {
1143 call->
addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
1144 newFunction->
addParamAttr(SwiftErrArgNo, Attribute::SwiftError);
1148 unsigned FirstOut = inputs.size();
1150 std::advance(OutputArgBegin, inputs.size());
1153 for (
unsigned i = 0,
e = outputs.size(); i !=
e; ++i) {
1154 Value *Output =
nullptr;
1155 if (AggregateArgs) {
1160 StructArgTy, Struct, Idx,
"gep_reload_" + outputs[i]->
getName());
1164 Output = ReloadOutputs[i];
1167 outputs[i]->
getName() +
".reload");
1168 Reloads.push_back(load);
1170 std::vector<User *>
Users(outputs[i]->user_begin(), outputs[i]->user_end());
1171 for (
unsigned u = 0,
e = Users.size(); u !=
e; ++u) {
1181 codeReplacer, 0, codeReplacer);
1188 std::map<BasicBlock *, BasicBlock *> ExitBlockMap;
1190 unsigned switchVal = 0;
1197 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
1202 OldTarget->
getName() +
".exitStub",
1204 unsigned SuccNum = switchVal++;
1206 Value *brVal =
nullptr;
1207 switch (NumExitBlocks) {
1235 for (
unsigned i = 0,
e = outputs.size(); i !=
e; ++i) {
1244 if (
auto *InvokeI = dyn_cast<InvokeInst>(OutI))
1245 InsertPt = InvokeI->getNormalDest()->getFirstInsertionPt();
1246 else if (
auto *Phi = dyn_cast<PHINode>(OutI))
1247 InsertPt = Phi->getParent()->getFirstInsertionPt();
1249 InsertPt = std::next(OutI->getIterator());
1252 assert((InsertBefore->getFunction() == newFunction ||
1253 Blocks.count(InsertBefore->getParent())) &&
1254 "InsertPt should be in new function");
1256 "Number of output arguments should match " 1257 "the amount of defined values");
1258 if (AggregateArgs) {
1263 StructArgTy, &*OAI, Idx,
"gep_" + outputs[i]->
getName(),
1265 new StoreInst(outputs[i], GEP, InsertBefore);
1270 new StoreInst(outputs[i], &*OAI, InsertBefore);
1277 switch (NumExitBlocks) {
1326 void CodeExtractor::moveCodeToFunction(
Function *newFunction) {
1340 void CodeExtractor::calculateNewCallTerminatorWeights(
1352 Distribution BranchDist;
1356 BlockNode ExitNode(i);
1357 uint64_t ExitFreq = ExitWeights[TI->
getSuccessor(i)].getFrequency();
1359 BranchDist.addExit(ExitNode, ExitFreq);
1365 if (BranchDist.Total == 0)
1369 BranchDist.normalize();
1372 for (
unsigned I = 0,
E = BranchDist.Weights.
size();
I <
E; ++
I) {
1373 const auto &Weight = BranchDist.Weights[
I];
1376 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
1381 LLVMContext::MD_prof,
1399 assert(BPI &&
"Both BPI and BFI are required to preserve profile info");
1401 if (Blocks.count(Pred))
1412 for (
auto &
I : *Block)
1413 if (
match(&
I, m_Intrinsic<Intrinsic::assume>()))
1419 splitReturnBlocks();
1428 if (!Blocks.count(*
SI)) {
1438 NumExitBlocks = ExitBlocks.
size();
1441 severSplitPHINodesOfEntry(header);
1442 severSplitPHINodesOfExits(ExitBlocks);
1446 "codeRepl", oldFunction,
1468 newFuncRoot->getInstList().push_back(BranchI);
1470 ValueSet inputs, outputs, SinkingCands, HoistingCands;
1472 findAllocas(CEAC, SinkingCands, HoistingCands, CommonExit);
1482 for (
auto *II : SinkingCands) {
1483 if (
auto *AI = dyn_cast<AllocaInst>(II)) {
1484 AI->
moveBefore(*newFuncRoot, newFuncRoot->getFirstInsertionPt());
1485 if (!FirstSunkAlloca)
1486 FirstSunkAlloca = AI;
1489 assert((SinkingCands.empty() || FirstSunkAlloca) &&
1490 "Did not expect a sink candidate without any allocas");
1491 for (
auto *II : SinkingCands) {
1492 if (!isa<AllocaInst>(II)) {
1493 cast<Instruction>(II)->moveAfter(FirstSunkAlloca);
1497 if (!HoistingCands.
empty()) {
1500 for (
auto *II : HoistingCands)
1501 cast<Instruction>(II)->moveBefore(TI);
1513 constructFunction(inputs, outputs, header, newFuncRoot, codeReplacer,
1519 if (Count.hasValue())
1526 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
1528 moveCodeToFunction(newFunction);
1540 if (BFI && NumExitBlocks > 1)
1541 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1553 for (
PHINode &PN : ExitBB->phis()) {
1554 Value *IncomingCodeReplacerVal =
nullptr;
1555 for (
unsigned i = 0,
e = PN.getNumIncomingValues(); i !=
e; ++i) {
1557 if (!Blocks.count(PN.getIncomingBlock(i)))
1561 if (!IncomingCodeReplacerVal) {
1562 PN.setIncomingBlock(i, codeReplacer);
1563 IncomingCodeReplacerVal = PN.getIncomingValue(i);
1565 assert(IncomingCodeReplacerVal == PN.getIncomingValue(i) &&
1566 "PHI has two incompatbile incoming values from codeRepl");
1574 auto BlockIt = BB.
begin();
1576 while (BlockIt != BB.
end()) {
1579 if (isa<DbgInfoIntrinsic>(Inst))
1588 DVI->eraseFromParent();
1596 return isa<ReturnInst>(Term) || isa<ResumeInst>(Term);
1599 newFunction->setDoesNotReturn();
1602 newFunction->dump();
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
This class represents an incoming formal argument to a Function.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
const Value * stripInBoundsOffsets() const
Strip off pointer casts and inbounds GEPs.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
ArrayRef< T > getArrayRef() const
size_type size() const
Determine the number of elements in the SetVector.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void push_back(const T &Elt)
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void findDbgUsers(SmallVectorImpl< DbgVariableIntrinsic *> &DbgInsts, Value *V)
Finds the debug info intrinsics describing a value.
This class represents a function call, abstracting a target machine's calling convention.
Value * getCondition() const
The two locations do not alias at all.
A cache of @llvm.assume calls within a function.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
LLVMContext & getContext() const
All values hold a context through their type.
An instruction for reading from memory.
static IntegerType * getInt64Ty(LLVMContext &C)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
iv Induction Variable Users
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
static IntegerType * getInt16Ty(LLVMContext &C)
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
MutableArrayRef< WeakTrackingVH > assumptions()
Access the list of assumption handles currently tracked for this function.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
bool match(Val *V, const Pattern &P)
unsigned getAllocaAddrSpace() const
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
Class to represent struct types.
LLVMContext & getContext() const
Get the global data context.
bool hasUWTable() const
True if the ABI mandates (or the user requested) that this function be in a unwind table...
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
static StringRef getName(Value *V)
This file contains the simple types necessary to represent the attributes associated with functions a...
No attributes have been set.
void setName(const Twine &Name)
Change the name of the value.
void unregisterAssumption(CallInst *CI)
Remove an @llvm.assume intrinsic from this function's cache if it has been added to the cache earlier...
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Class to represent function types.
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.
This is the common base class for debug info intrinsics for variables.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
AttributeList getAttributes() const
Return the attribute list for this Function.
An instruction for storing to memory.
bool hasPersonalityFn() const
Check whether this function has a personality function.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
BasicBlock * getSuccessor(unsigned idx) const
static Function * getFunction(Constant *C)
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.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Analysis containing CSE Info
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
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 ...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Type * getReturnType() const
Returns the type of the ret val.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Move duplicate certain instructions close to their use
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.
DISubprogram * getSubprogram() const
Get the attached subprogram.
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Distribution of unscaled probability weight.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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 isLifetimeStartOrEnd() const
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
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...
unsigned getAddressSpace() const
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
static CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
Create a BitCast AddrSpaceCast, or a PtrToInt cast instruction.
const Function * getFunction() const
Return the function this instruction belongs to.
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
Sentinal value useful for loops.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Class to represent profile counts.
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
#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.
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
bool doesNotThrow() const
Determine if the function cannot unwind.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
typename vector_type::const_iterator iterator
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
void setIncomingBlock(unsigned i, BasicBlock *BB)
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors, BranchProbability Prob)
Set the raw edge probability for the given edge.
void setBlockFreq(const BasicBlock *BB, uint64_t Freq)
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
void push_back(pointer val)
amdgpu Simplify well known AMD library false FunctionCallee Callee
iterator_range< user_iterator > users()
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
pointer remove(iterator &IT)
Analysis providing branch probability information.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
bool empty() const
Determine if the SetVector is empty or not.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
Rename collisions when linking (static functions).
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
const BasicBlock & front() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
void setDefaultDest(BasicBlock *DefaultCase)
A vector that has set insertion semantics.
succ_range successors(Instruction *I)
static const Function * getParent(const Value *V)
AttributeSet getFnAttributes() const
The function attributes are returned.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
void setPersonalityFn(Constant *Fn)
static BranchProbability getZero()
const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Value * getPointerOperand()
Optional< uint64_t > getProfileCountFromFreq(uint64_t Freq) const
Returns the estimated profile count of Freq.
Representative of a block.
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