LLVM  3.7.0
IndirectionUtils.cpp
Go to the documentation of this file.
1 //===---- IndirectionUtils.cpp - Utilities for call indirection in Orc ----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/Triple.h"
13 #include "llvm/IR/CallSite.h"
14 #include "llvm/IR/IRBuilder.h"
16 #include <set>
17 #include <sstream>
18 
19 namespace llvm {
20 namespace orc {
21 
23  Constant *AddrIntVal =
25  Constant *AddrPtrVal =
26  ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
27  PointerType::get(&FT, 0));
28  return AddrPtrVal;
29 }
30 
32  const Twine &Name, Constant *Initializer) {
33  auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
34  Initializer, Name, nullptr,
36  IP->setVisibility(GlobalValue::HiddenVisibility);
37  return IP;
38 }
39 
40 void makeStub(Function &F, GlobalVariable &ImplPointer) {
41  assert(F.isDeclaration() && "Can't turn a definition into a stub.");
42  assert(F.getParent() && "Function isn't in a module.");
43  Module &M = *F.getParent();
44  BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
45  IRBuilder<> Builder(EntryBlock);
46  LoadInst *ImplAddr = Builder.CreateLoad(&ImplPointer);
47  std::vector<Value*> CallArgs;
48  for (auto &A : F.args())
49  CallArgs.push_back(&A);
50  CallInst *Call = Builder.CreateCall(ImplAddr, CallArgs);
51  Call->setTailCall();
52  Call->setAttributes(F.getAttributes());
53  if (F.getReturnType()->isVoidTy())
54  Builder.CreateRetVoid();
55  else
56  Builder.CreateRet(Call);
57 }
58 
59 // Utility class for renaming global values and functions during partitioning.
61 public:
62 
63  static bool needsRenaming(const Value &New) {
64  if (!New.hasName() || New.getName().startswith("\01L"))
65  return true;
66  return false;
67  }
68 
69  const std::string& getRename(const Value &Orig) {
70  // See if we have a name for this global.
71  {
72  auto I = Names.find(&Orig);
73  if (I != Names.end())
74  return I->second;
75  }
76 
77  // Nope. Create a new one.
78  // FIXME: Use a more robust uniquing scheme. (This may blow up if the user
79  // writes a "__orc_anon[[:digit:]]* method).
80  unsigned ID = Names.size();
81  std::ostringstream NameStream;
82  NameStream << "__orc_anon" << ID++;
83  auto I = Names.insert(std::make_pair(&Orig, NameStream.str()));
84  return I.first->second;
85  }
86 private:
88 };
89 
91  if (V.hasLocalLinkage()) {
92  if (R.needsRenaming(V))
93  V.setName(R.getRename(V));
96  }
97  V.setUnnamedAddr(false);
98  assert(!R.needsRenaming(V) && "Invalid global name.");
99 }
100 
102  GlobalRenamer Renamer;
103 
104  for (auto &F : M)
105  raiseVisibilityOnValue(F, Renamer);
106 
107  for (auto &GV : M.globals())
108  raiseVisibilityOnValue(GV, Renamer);
109 }
110 
112  ValueToValueMapTy *VMap) {
113  assert(F.getParent() != &Dst && "Can't copy decl over existing function.");
114  Function *NewF =
115  Function::Create(cast<FunctionType>(F.getType()->getElementType()),
116  F.getLinkage(), F.getName(), &Dst);
117  NewF->copyAttributesFrom(&F);
118 
119  if (VMap) {
120  (*VMap)[&F] = NewF;
121  auto NewArgI = NewF->arg_begin();
122  for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
123  ++ArgI, ++NewArgI)
124  (*VMap)[ArgI] = NewArgI;
125  }
126 
127  return NewF;
128 }
129 
131  ValueMaterializer *Materializer,
132  Function *NewF) {
133  assert(!OrigF.isDeclaration() && "Nothing to move");
134  if (!NewF)
135  NewF = cast<Function>(VMap[&OrigF]);
136  else
137  assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
138  assert(NewF && "Function mapping missing from VMap.");
139  assert(NewF->getParent() != OrigF.getParent() &&
140  "moveFunctionBody should only be used to move bodies between "
141  "modules.");
142 
143  SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
144  CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns,
145  "", nullptr, nullptr, Materializer);
146  OrigF.deleteBody();
147 }
148 
150  ValueToValueMapTy *VMap) {
151  assert(GV.getParent() != &Dst && "Can't copy decl over existing global var.");
152  GlobalVariable *NewGV = new GlobalVariable(
153  Dst, GV.getType()->getElementType(), GV.isConstant(),
154  GV.getLinkage(), nullptr, GV.getName(), nullptr,
156  NewGV->copyAttributesFrom(&GV);
157  if (VMap)
158  (*VMap)[&GV] = NewGV;
159  return NewGV;
160 }
161 
163  ValueToValueMapTy &VMap,
164  ValueMaterializer *Materializer,
165  GlobalVariable *NewGV) {
166  assert(OrigGV.hasInitializer() && "Nothing to move");
167  if (!NewGV)
168  NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
169  else
170  assert(VMap[&OrigGV] == NewGV &&
171  "Incorrect global variable mapping in VMap.");
172  assert(NewGV->getParent() != OrigGV.getParent() &&
173  "moveGlobalVariable should only be used to move initializers between "
174  "modules");
175 
176  NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
177  nullptr, Materializer));
178 }
179 
180 } // End namespace orc.
181 } // End namespace llvm.
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:145
LinkageTypes getLinkage() const
Definition: GlobalValue.h:289
bool hasName() const
Definition: Value.h:228
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
CallInst - This class represents a function call, abstracting a target machine's calling convention...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
PointerType::get - This constructs a pointer to an object of the specified type in a numbered address...
Definition: Type.cpp:738
static bool needsRenaming(const Value &New)
Externally visible function.
Definition: GlobalValue.h:40
Type * getReturnType() const
Definition: Function.cpp:233
arg_iterator arg_end()
Definition: Function.h:480
F(f)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:472
LoadInst - an instruction for reading from memory.
Definition: Instructions.h:177
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:240
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
const std::string & getRename(const Value &Orig)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:198
GlobalVariable * createImplPointer(PointerType &PT, Module &M, const Twine &Name, Constant *Initializer)
Create a function pointer with the given type, name, and initializer in the given Module...
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, bool ModuleLevelChanges, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:517
static void raiseVisibilityOnValue(GlobalValue &V, GlobalRenamer &R)
Constant * createIRTypedAddress(FunctionType &FT, TargetAddress Addr)
Build a function pointer of FunctionType with the given constant address.
void moveGlobalVariableInitializer(GlobalVariable &OrigGV, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, GlobalVariable *NewGV=nullptr)
Move global variable GV from its parent module to cloned global declaration in a different module...
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:250
FunctionType - Class to represent function types.
Definition: DerivedTypes.h:96
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
Definition: Type.h:125
Type * getElementType() const
Definition: DerivedTypes.h:323
GlobalVariable * cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV, ValueToValueMapTy *VMap=nullptr)
Clone a global variable declaration into a new module.
PointerType - Class to represent pointers.
Definition: DerivedTypes.h:449
ValueMaterializer - This is a class that can be implemented by clients to materialize Values on deman...
Definition: ValueMapper.h:39
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
void deleteBody()
deleteBody - This method deletes the body of the function, and converts the linkage to external...
Definition: Function.h:405
This is an important base class in LLVM.
Definition: Constant.h:41
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Definition: ValueMapper.cpp:28
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:416
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:103
arg_iterator arg_begin()
Definition: Function.h:472
void setTailCall(bool isTC=true)
bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:215
Function * cloneFunctionDecl(Module &Dst, const Function &F, ValueToValueMapTy *VMap=nullptr)
Clone a function declaration into a new module.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
void setUnnamedAddr(bool Val)
Definition: GlobalValue.h:131
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.
Definition: Constants.cpp:582
uint64_t TargetAddress
Represents an address in the target process's address space.
Definition: JITSymbol.h:26
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:284
AttributeSet getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:181
bool hasInitializer() const
Definitions have initializers, declarations don't.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1591
void makeAllSymbolsExternallyAccessible(Module &M)
Raise linkage types and rename as necessary to ensure that all symbols are accessible for other modul...
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:160
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:185
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:128
#define I(x, y, z)
Definition: MD5.cpp:54
void makeStub(Function &F, GlobalVariable &ImplPointer)
Turn a function declaration into a stub function that makes an indirect call using the given function...
bool hasLocalLinkage() const
Definition: GlobalValue.h:280
void copyAttributesFrom(const GlobalValue *Src) override
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:221
void setAttributes(const AttributeSet &Attrs)
setAttributes - Set the parameter attributes for this call.
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:365
LLVM Value Representation.
Definition: Value.h:69
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:121
void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap, ValueMaterializer *Materializer=nullptr, Function *NewF=nullptr)
Move the body of function 'F' to a cloned function declaration in a different module (See related clo...
iterator_range< arg_iterator > args()
Definition: Function.h:489
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
Definition: Type.h:137