47 #define DEBUG_TYPE "code-extractor"
55 cl::desc(
"Aggregate arguments to code-extracted functions"));
74 while (!ToVisit.
empty()) {
76 if (!Visited.
insert(Curr).second)
78 if (isa<BlockAddress const>(Curr))
81 if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->
getParent() != &BB)
84 for (
auto const &U : Curr->
operands()) {
85 if (
auto *UU = dyn_cast<User>(U))
92 if (isa<AllocaInst>(
I) || isa<InvokeInst>(
I))
94 if (
const CallInst *CI = dyn_cast<CallInst>(
I))
95 if (
const Function *
F = CI->getCalledFunction())
96 if (
F->getIntrinsicID() == Intrinsic::vastart)
106 assert(!BBs.
empty() &&
"The set of blocks to extract must be non-empty");
117 if (!Result.insert(BB))
131 assert(Result.count(*PI) &&
132 "No blocks in this region may have entries from outside the region"
133 " except for the first block!");
150 NumExitBlocks(~0U) {}
156 if (Blocks.
count(
I->getParent()))
165 if (isa<Argument>(V))
return true;
167 if (!Blocks.
count(
I->getParent()))
174 auto hasNonCommonExitSucc = [&](
BasicBlock *Block) {
177 if (Blocks.
count(Succ))
179 if (!CommonExitBlock) {
180 CommonExitBlock = Succ;
183 if (CommonExitBlock == Succ)
191 if (
any_of(Blocks, hasNonCommonExitSucc))
194 return CommonExitBlock;
202 if (Blocks.count(&BB))
206 if (isa<DbgInfoIntrinsic>(II))
209 unsigned Opcode = II.getOpcode();
210 Value *MemAddr =
nullptr;
222 if (dyn_cast<Constant>(MemAddr))
225 if (!dyn_cast<AllocaInst>(Base) || Base == AI)
238 if (II.mayHaveSideEffects())
250 BasicBlock *SinglePredFromOutlineRegion =
nullptr;
251 assert(!Blocks.count(CommonExitBlock) &&
252 "Expect a block outside the region!");
254 if (!Blocks.count(Pred))
256 if (!SinglePredFromOutlineRegion) {
257 SinglePredFromOutlineRegion = Pred;
258 }
else if (SinglePredFromOutlineRegion != Pred) {
259 SinglePredFromOutlineRegion =
nullptr;
264 if (SinglePredFromOutlineRegion)
265 return SinglePredFromOutlineRegion;
271 while (I != BB->end()) {
284 assert(!getFirstPHI(CommonExitBlock) &&
"Phi not expected");
291 if (Blocks.count(Pred))
296 Blocks.insert(CommonExitBlock);
297 return CommonExitBlock;
306 if (Blocks.count(&BB))
318 auto GetLifeTimeMarkers =
320 bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> {
321 Instruction *LifeStart =
nullptr, *LifeEnd =
nullptr;
329 return std::make_pair<Instruction *>(
nullptr,
nullptr);
330 LifeStart = IntrInst;
334 return std::make_pair<Instruction *>(
nullptr,
nullptr);
341 return std::make_pair<Instruction *>(
nullptr,
nullptr);
344 if (!LifeStart || !LifeEnd)
345 return std::make_pair<Instruction *>(
nullptr,
nullptr);
350 if ((SinkLifeStart || HoistLifeEnd) &&
352 return std::make_pair<Instruction *>(
nullptr,
nullptr);
355 if (HoistLifeEnd && !ExitBlock)
356 return std::make_pair<Instruction *>(
nullptr,
nullptr);
358 return std::make_pair(LifeStart, LifeEnd);
361 bool SinkLifeStart =
false, HoistLifeEnd =
false;
362 auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd);
366 SinkCands.
insert(Markers.first);
369 HoistCands.
insert(Markers.second);
377 if (U->stripInBoundsConstantOffsets() == AI) {
378 SinkLifeStart =
false;
379 HoistLifeEnd =
false;
381 Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd);
390 MarkerAddr =
nullptr;
397 SinkCands.
insert(Markers.first);
399 SinkCands.
insert(MarkerAddr);
402 HoistCands.
insert(Markers.second);
434 void CodeExtractor::severSplitPHINodes(
BasicBlock *&Header) {
435 unsigned NumPredsFromRegion = 0;
436 unsigned NumPredsOutsideRegion = 0;
447 ++NumPredsFromRegion;
449 ++NumPredsOutsideRegion;
453 if (NumPredsOutsideRegion <= 1)
return;
465 Blocks.remove(OldPred);
466 Blocks.insert(NewBB);
471 if (NumPredsFromRegion) {
472 PHINode *PN = cast<PHINode>(OldPred->begin());
484 for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
485 PHINode *PN = cast<PHINode>(AfterPHIs);
491 NewPN->addIncoming(PN, OldPred);
506 void CodeExtractor::splitReturnBlocks() {
510 Block->splitBasicBlock(RI->getIterator(),
Block->getName() +
".ret");
529 Function *CodeExtractor::constructFunction(
const ValueSet &inputs,
530 const ValueSet &outputs,
536 DEBUG(
dbgs() <<
"inputs: " << inputs.size() <<
"\n");
537 DEBUG(
dbgs() <<
"outputs: " << outputs.size() <<
"\n");
540 switch (NumExitBlocks) {
547 std::vector<Type*> paramTy;
550 for (
Value *value : inputs) {
551 DEBUG(
dbgs() <<
"value used in func: " << *value <<
"\n");
552 paramTy.push_back(value->getType());
556 for (
Value *output : outputs) {
557 DEBUG(
dbgs() <<
"instr used in func: " << *output <<
"\n");
559 paramTy.push_back(output->getType());
565 dbgs() <<
"Function type: " << *RetTy <<
" f(";
566 for (
Type *i : paramTy)
567 dbgs() << *i <<
", ";
572 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
600 for (
const auto &Attr : AB.td_attrs())
601 newFunction->
addFnAttr(Attr.first, Attr.second);
610 for (
unsigned i = 0, e = inputs.size(); i != e; ++i) {
618 StructTy, &*AI, Idx,
"gep_" + inputs[i]->
getName(), TI);
623 std::vector<User*>
Users(inputs[i]->user_begin(), inputs[i]->user_end());
626 if (Blocks.count(inst->getParent()))
627 inst->replaceUsesOfWith(inputs[i], RewriteVal);
631 if (!AggregateArgs) {
633 for (
unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
634 AI->
setName(inputs[i]->getName());
635 for (
unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
636 AI->
setName(outputs[i]->getName()+
".out");
643 for (
unsigned i = 0, e = Users.size(); i != e; ++i)
672 ValueSet &inputs, ValueSet &outputs) {
675 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
682 for (
Value *input : inputs)
684 StructValues.push_back(input);
686 params.push_back(input);
689 for (
Value *output : outputs) {
691 StructValues.push_back(output);
695 nullptr, output->getName() +
".loc",
697 ReloadOutputs.push_back(alloca);
698 params.push_back(alloca);
704 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
705 std::vector<Type*> ArgTypes;
707 ve = StructValues.end(); v != ve; ++v)
708 ArgTypes.push_back((*v)->getType());
715 params.push_back(Struct);
717 for (
unsigned i = 0, e = inputs.size(); i != e; ++i) {
722 StructArgTy, Struct, Idx,
"gep_" + StructValues[i]->
getName());
731 NumExitBlocks > 1 ?
"targetBlock" :
"");
735 unsigned FirstOut = inputs.size();
737 std::advance(OutputArgBegin, inputs.size());
740 for (
unsigned i = 0, e = outputs.size(); i != e; ++i) {
741 Value *Output =
nullptr;
747 StructArgTy, Struct, Idx,
"gep_reload_" + outputs[i]->
getName());
751 Output = ReloadOutputs[i];
754 Reloads.push_back(load);
756 std::vector<User*>
Users(outputs[i]->user_begin(), outputs[i]->user_end());
757 for (
unsigned u = 0, e = Users.size(); u != e; ++u) {
767 codeReplacer, 0, codeReplacer);
774 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
776 unsigned switchVal = 0;
783 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
788 OldTarget->
getName() +
".exitStub",
790 unsigned SuccNum = switchVal++;
792 Value *brVal =
nullptr;
793 switch (NumExitBlocks) {
813 for (
unsigned out = 0, e = outputs.size(); out != e; ++out) {
818 bool DominatesDef =
true;
821 if (
auto *Invoke = dyn_cast<InvokeInst>(outputs[out]))
822 NormalDest = Invoke->getNormalDest();
825 DefBlock = NormalDest;
830 for (
const auto &
I : ExitBlockMap)
831 if (DefBlock ==
I.second) {
839 if (!DT && DefBlock != OldTarget)
840 DominatesDef =
false;
844 DominatesDef = DT->
dominates(DefBlock, OldTarget);
852 if (pred && DT && DT->
dominates(DefBlock, pred))
863 StructArgTy, &*OAI, Idx,
"gep_" + outputs[out]->
getName(),
867 new StoreInst(outputs[out], &*OAI, NTRet);
871 if (!AggregateArgs) ++OAI;
882 switch (NumExitBlocks) {
925 void CodeExtractor::moveCodeToFunction(
Function *newFunction) {
939 void CodeExtractor::calculateNewCallTerminatorWeights(
951 Distribution BranchDist;
955 BlockNode ExitNode(i);
956 uint64_t ExitFreq = ExitWeights[TI->
getSuccessor(i)].getFrequency();
958 BranchDist.addExit(ExitNode, ExitFreq);
964 if (BranchDist.Total == 0)
968 BranchDist.normalize();
971 for (
unsigned I = 0,
E = BranchDist.Weights.
size();
I <
E; ++
I) {
972 const auto &Weight = BranchDist.Weights[
I];
975 BranchWeights[Weight.TargetNode.Index] = Weight.Amount;
988 ValueSet inputs, outputs, SinkingCands, HoistingCands;
999 assert(BPI &&
"Both BPI and BFI are required to preserve profile info");
1001 if (Blocks.count(Pred))
1009 severSplitPHINodes(header);
1013 splitReturnBlocks();
1019 "codeRepl", oldFunction,
1028 findAllocas(SinkingCands, HoistingCands, CommonExit);
1035 for (
auto *II : SinkingCands)
1036 cast<Instruction>(II)->moveBefore(*newFuncRoot,
1037 newFuncRoot->getFirstInsertionPt());
1039 if (!HoistingCands.
empty()) {
1042 for (
auto *II : HoistingCands)
1043 cast<Instruction>(II)->moveBefore(TI);
1053 if (!Blocks.count(*SI)) {
1063 NumExitBlocks = ExitBlocks.
size();
1066 Function *newFunction = constructFunction(inputs, outputs, header,
1068 codeReplacer, oldFunction,
1080 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
1082 moveCodeToFunction(newFunction);
1085 if (BFI && NumExitBlocks > 1)
1086 calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI);
1100 std::vector<BasicBlock*> Succs(
succ_begin(codeReplacer),
1102 for (
unsigned i = 0, e = Succs.size(); i != e; ++i)
1105 std::set<BasicBlock*> ProcessedPreds;
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
iterator_range< use_iterator > uses()
static IntegerType * getInt1Ty(LLVMContext &C)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
This class represents an incoming formal argument to a Function.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
A Module instance is used to store all the information related to an LLVM module. ...
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
This class represents a function call, abstracting a target machine's calling convention.
bool isEHPad() const
Return true if this basic block is an exception handling block.
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
const Instruction & front() const
An instruction for reading from memory.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
iv Induction Variable Users
static IntegerType * getInt16Ty(LLVMContext &C)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
AttributeList getAttributes() const
Return the attribute list for this Function.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
bool doesNotThrow() const
Determine if the function cannot unwind.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
static StringRef getName(Value *V)
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() const
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...
Class to represent function types.
bool insert(const value_type &X)
Insert a new element into the SetVector.
const T & getValue() const LLVM_LVALUE_FUNCTION
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Optional< uint64_t > getProfileCountFromFreq(uint64_t Freq) const
Returns the estimated profile count of Freq.
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.
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
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.
Subclasses of this class are all able to terminate a basic block.
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
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.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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...
unsigned getAllocaAddrSpace() const
static Type * getVoidTy(LLVMContext &C)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
const InstListType & getInstList() const
Return the underlying instruction list container.
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()
bool empty() const
empty - Check if the array is empty.
CaseIt removeCase(CaseIt I)
This method removes the specified case and its successor from the switch instruction.
LLVMContext & getContext() const
All values hold a context through their type.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
typename vector_type::const_iterator iterator
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
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)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
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...
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 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 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)
const BasicBlock & getEntryBlock() const
AttributeSet getFnAttributes() const
The function attributes are returned.
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void push_back(pointer val)
iterator_range< user_iterator > users()
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Value * getCondition() const
llvm_unreachable("Unknown RegBank!")
pointer remove(iterator &IT)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
BasicBlock * getSuccessor(unsigned idx) const
Analysis providing branch probability information.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
Represents a single loop in the control flow graph.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
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)
Rename collisions when linking (static functions).
bool hasUWTable() const
True if the ABI mandates (or the user requested) that this function be in a unwind table...
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
LLVMContext & getContext() const
Get the context in which this basic block lives.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
void setDefaultDest(BasicBlock *DefaultCase)
A vector that has set insertion semantics.
static const Function * getParent(const Value *V)
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
static BranchProbability getZero()
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...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
Value * getPointerOperand()
const BasicBlock * getParent() const
Representative of a block.
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
BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.