41 #define DEBUG_TYPE "code-extractor"
49 cl::desc(
"Aggregate arguments to code-extracted functions"));
59 if (isa<AllocaInst>(
I) || isa<InvokeInst>(
I))
61 if (
const CallInst *CI = dyn_cast<CallInst>(
I))
62 if (
const Function *
F = CI->getCalledFunction())
63 if (
F->getIntrinsicID() == Intrinsic::vastart)
71 template <
typename IteratorT>
76 assert(BBBegin != BBEnd);
80 for (IteratorT
I = BBBegin, E = BBEnd;
I != E; ++
I) {
96 assert(Result.
count(*PI) &&
97 "No blocks in this region may have entries from outside the region"
98 " except for the first block!");
144 if (Blocks.
count(
I->getParent()))
153 if (isa<Argument>(V))
return true;
155 if (!Blocks.
count(
I->getParent()))
188 void CodeExtractor::severSplitPHINodes(
BasicBlock *&Header) {
189 unsigned NumPredsFromRegion = 0;
190 unsigned NumPredsOutsideRegion = 0;
201 ++NumPredsFromRegion;
203 ++NumPredsOutsideRegion;
207 if (NumPredsOutsideRegion <= 1)
return;
221 Blocks.remove(OldPred);
222 Blocks.insert(NewBB);
232 if (NumPredsFromRegion) {
244 for (AfterPHIs = OldPred->
begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
245 PHINode *PN = cast<PHINode>(AfterPHIs);
265 void CodeExtractor::splitReturnBlocks() {
268 if (
ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
282 E = Children.
end();
I != E; ++
I)
291 Function *CodeExtractor::constructFunction(
const ValueSet &
inputs,
292 const ValueSet &outputs,
298 DEBUG(
dbgs() <<
"inputs: " << inputs.size() <<
"\n");
299 DEBUG(
dbgs() <<
"outputs: " << outputs.size() <<
"\n");
302 switch (NumExitBlocks) {
309 std::vector<Type*> paramTy;
314 const Value *value = *i;
315 DEBUG(
dbgs() <<
"value used in func: " << *value <<
"\n");
316 paramTy.push_back(value->
getType());
322 DEBUG(
dbgs() <<
"instr used in func: " << **
I <<
"\n");
324 paramTy.push_back((*I)->getType());
329 DEBUG(
dbgs() <<
"Function type: " << *RetTy <<
" f(");
330 for (std::vector<Type*>::iterator i = paramTy.begin(),
331 e = paramTy.end(); i != e; ++i)
336 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
360 for (
unsigned i = 0, e = inputs.size(); i != e; ++i) {
368 StructTy, AI, Idx,
"gep_" + inputs[i]->
getName(), TI);
373 std::vector<User*>
Users(inputs[i]->user_begin(), inputs[i]->user_end());
374 for (std::vector<User*>::iterator use =
Users.begin(), useE =
Users.end();
376 if (
Instruction* inst = dyn_cast<Instruction>(*use))
377 if (Blocks.count(inst->getParent()))
378 inst->replaceUsesOfWith(inputs[i], RewriteVal);
382 if (!AggregateArgs) {
384 for (
unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
385 AI->setName(inputs[i]->getName());
386 for (
unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
387 AI->setName(outputs[i]->getName()+
".out");
394 for (
unsigned i = 0, e =
Users.size(); i != e; ++i)
423 ValueSet &inputs, ValueSet &outputs) {
426 std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
433 StructValues.push_back(*i);
435 params.push_back(*i);
440 StructValues.push_back(*i);
443 new AllocaInst((*i)->getType(),
nullptr, (*i)->getName()+
".loc",
445 ReloadOutputs.push_back(alloca);
446 params.push_back(alloca);
452 if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
453 std::vector<Type*> ArgTypes;
455 ve = StructValues.end(); v != ve; ++v)
456 ArgTypes.push_back((*v)->getType());
461 new AllocaInst(StructArgTy,
nullptr,
"structArg",
463 params.push_back(Struct);
465 for (
unsigned i = 0, e = inputs.size(); i != e; ++i) {
470 StructArgTy, Struct, Idx,
"gep_" + StructValues[i]->
getName());
479 NumExitBlocks > 1 ?
"targetBlock" :
"");
483 unsigned FirstOut = inputs.size();
488 for (
unsigned i = 0, e = outputs.size(); i != e; ++i) {
489 Value *Output =
nullptr;
495 StructArgTy, Struct, Idx,
"gep_reload_" + outputs[i]->
getName());
499 Output = ReloadOutputs[i];
502 Reloads.push_back(load);
504 std::vector<User*>
Users(outputs[i]->user_begin(), outputs[i]->user_end());
505 for (
unsigned u = 0, e =
Users.size(); u != e; ++u) {
515 codeReplacer, 0, codeReplacer);
522 std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
524 unsigned switchVal = 0;
526 e = Blocks.end(); i != e; ++i) {
532 BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
537 OldTarget->
getName() +
".exitStub",
539 unsigned SuccNum = switchVal++;
541 Value *brVal =
nullptr;
542 switch (NumExitBlocks) {
562 for (
unsigned out = 0, e = outputs.size(); out != e; ++out) {
567 bool DominatesDef =
true;
569 if (
InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
570 DefBlock = Invoke->getNormalDest();
575 for (std::map<BasicBlock*, BasicBlock*>::iterator
I =
576 ExitBlockMap.begin(), E = ExitBlockMap.end();
I != E; ++
I)
577 if (DefBlock ==
I->second) {
585 if (!DT && DefBlock != OldTarget)
586 DominatesDef =
false;
590 DominatesDef = DT->
dominates(DefBlock, OldTarget);
598 if (pred && DT && DT->
dominates(DefBlock, pred))
609 StructArgTy, OAI, Idx,
"gep_" + outputs[out]->
getName(),
617 if (!AggregateArgs) ++OAI;
628 switch (NumExitBlocks) {
671 void CodeExtractor::moveCodeToFunction(
Function *newFunction) {
677 e = Blocks.end(); i != e; ++i) {
697 severSplitPHINodes(header);
707 "codeRepl", oldFunction,
723 if (!Blocks.count(*SI))
725 NumExitBlocks = ExitBlocks.
size();
728 Function *newFunction = constructFunction(inputs, outputs, header,
730 codeReplacer, oldFunction,
733 emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
735 moveCodeToFunction(newFunction);
749 std::vector<BasicBlock*> Succs(
succ_begin(codeReplacer),
751 for (
unsigned i = 0, e = Succs.size(); i != e; ++i)
754 std::set<BasicBlock*> ProcessedPreds;
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
addNewBlock - Add a new node to the dominator tree information.
ReturnInst - Return a value (possibly void), from a function.
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
void push_back(const T &Elt)
iterator_range< use_iterator > uses()
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
A Module instance is used to store all the information related to an LLVM module. ...
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
addCase - Add an entry to the switch instruction...
CallInst - This class represents a function call, abstracting a target machine's calling convention...
const_iterator begin(StringRef path)
Get begin iterator over path.
Type * getReturnType() const
const Function * getParent() const
Return the enclosing method, or null if none.
bool isSubRegion() const
Is this RegionNode a subregion?
LoadInst - an instruction for reading from memory.
vector_type::const_iterator const_iterator
iv Induction Variable Users
static IntegerType * getInt16Ty(LLVMContext &C)
iterator end()
Get an iterator to the end of the SetVector.
T * getNodeAs() const
Get the content of this RegionNode.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
Reports a serious error, calling any installed error handler.
static Constant * getNullValue(Type *Ty)
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
void push_back(NodeTy *val)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
removeIncomingValue - Remove an incoming value.
bool doesNotThrow() const
Determine if the function cannot unwind.
std::vector< DomTreeNodeBase< NodeT > * >::iterator iterator
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
StructType - Class to represent struct types.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A Use represents the edge between a Value definition and its users.
static void advance(T &it, size_t Val)
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static StringRef getName(Value *V)
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...
FunctionType - Class to represent function types.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static std::vector< std::string > inputs
iterator begin()
Get an iterator to the beginning of the SetVector.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
FunctionType::get - 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)...
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
StoreInst - an instruction for storing to memory.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
getNumIncomingValues - Return the number of incoming edges
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
GetElementPtrInst - an instruction for type-safe pointer arithmetic to access elements of arrays and ...
Subclasses of this class are all able to terminate a basic block.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
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...
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...
static Type * getVoidTy(LLVMContext &C)
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
const InstListType & getInstList() const
Return the underlying instruction list container.
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
const BasicBlockListType & getBasicBlockList() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static PointerType * getUnqual(Type *ElementType)
PointerType::getUnqual - This constructs a pointer to an object of the specified type in the generic ...
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
StructType::get - This static method is the primary way to create a literal StructType.
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.
Type * getType() const
All values are typed, get the type of this value.
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...
const BasicBlock & getEntryBlock() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void clear()
Completely clear the SetVector.
iterator_range< user_iterator > users()
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Value * getCondition() const
block_iterator block_begin()
BasicBlock * getSuccessor(unsigned idx) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
block_iterator block_end()
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isLandingPad() const
Return true if this basic block is a landing pad.
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
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.
void removeCase(CaseIt i)
removeCase - This method removes the specified case and its successor from the switch instruction...
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
SwitchInst - Multiway switch.
user_iterator user_begin()
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.
vector_type::const_iterator iterator
void setDefaultDest(BasicBlock *DefaultCase)
A vector that has set insertion semantics.
static const Function * getParent(const Value *V)
InvokeInst - Invoke instruction.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
NodeTy * remove(iterator &IT)
const BasicBlock * getParent() const
LLVMContext & getContext() const
Get the global data context.
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
AllocaInst - an instruction to allocate memory on the stack.
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.