[Orc] Add support for emitting indirect stubs directly into the JIT target's
[oota-llvm.git] / lib / ExecutionEngine / Orc / IndirectionUtils.cpp
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"
12 #include "llvm/ExecutionEngine/Orc/IndirectionUtils.h"
13 #include "llvm/IR/CallSite.h"
14 #include "llvm/IR/IRBuilder.h"
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include <set>
17 #include <sstream>
18
19 namespace llvm {
20 namespace orc {
21
22 void JITCompileCallbackManagerBase::anchor() {}
23 void IndirectStubsManagerBase::anchor() {}
24
25 Constant* createIRTypedAddress(FunctionType &FT, TargetAddress Addr) {
26   Constant *AddrIntVal =
27     ConstantInt::get(Type::getInt64Ty(FT.getContext()), Addr);
28   Constant *AddrPtrVal =
29     ConstantExpr::getCast(Instruction::IntToPtr, AddrIntVal,
30                           PointerType::get(&FT, 0));
31   return AddrPtrVal;
32 }
33
34 GlobalVariable* createImplPointer(PointerType &PT, Module &M,
35                                   const Twine &Name, Constant *Initializer) {
36   auto IP = new GlobalVariable(M, &PT, false, GlobalValue::ExternalLinkage,
37                                Initializer, Name, nullptr,
38                                GlobalValue::NotThreadLocal, 0, true);
39   IP->setVisibility(GlobalValue::HiddenVisibility);
40   return IP;
41 }
42
43 void makeStub(Function &F, Value &ImplPointer) {
44   assert(F.isDeclaration() && "Can't turn a definition into a stub.");
45   assert(F.getParent() && "Function isn't in a module.");
46   Module &M = *F.getParent();
47   BasicBlock *EntryBlock = BasicBlock::Create(M.getContext(), "entry", &F);
48   IRBuilder<> Builder(EntryBlock);
49   LoadInst *ImplAddr = Builder.CreateLoad(&ImplPointer);
50   std::vector<Value*> CallArgs;
51   for (auto &A : F.args())
52     CallArgs.push_back(&A);
53   CallInst *Call = Builder.CreateCall(ImplAddr, CallArgs);
54   Call->setTailCall();
55   Call->setAttributes(F.getAttributes());
56   if (F.getReturnType()->isVoidTy())
57     Builder.CreateRetVoid();
58   else
59     Builder.CreateRet(Call);
60 }
61
62 // Utility class for renaming global values and functions during partitioning.
63 class GlobalRenamer {
64 public:
65
66   static bool needsRenaming(const Value &New) {
67     if (!New.hasName() || New.getName().startswith("\01L"))
68       return true;
69     return false;
70   }
71
72   const std::string& getRename(const Value &Orig) {
73     // See if we have a name for this global.
74     {
75       auto I = Names.find(&Orig);
76       if (I != Names.end())
77         return I->second;
78     }
79
80     // Nope. Create a new one.
81     // FIXME: Use a more robust uniquing scheme. (This may blow up if the user
82     //        writes a "__orc_anon[[:digit:]]* method).
83     unsigned ID = Names.size();
84     std::ostringstream NameStream;
85     NameStream << "__orc_anon" << ID++;
86     auto I = Names.insert(std::make_pair(&Orig, NameStream.str()));
87     return I.first->second;
88   }
89 private:
90   DenseMap<const Value*, std::string> Names;
91 };
92
93 static void raiseVisibilityOnValue(GlobalValue &V, GlobalRenamer &R) {
94   if (V.hasLocalLinkage()) {
95     if (R.needsRenaming(V))
96       V.setName(R.getRename(V));
97     V.setLinkage(GlobalValue::ExternalLinkage);
98     V.setVisibility(GlobalValue::HiddenVisibility);
99   }
100   V.setUnnamedAddr(false);
101   assert(!R.needsRenaming(V) && "Invalid global name.");
102 }
103
104 void makeAllSymbolsExternallyAccessible(Module &M) {
105   GlobalRenamer Renamer;
106
107   for (auto &F : M)
108     raiseVisibilityOnValue(F, Renamer);
109
110   for (auto &GV : M.globals())
111     raiseVisibilityOnValue(GV, Renamer);
112
113   for (auto &A : M.aliases())
114     raiseVisibilityOnValue(A, Renamer);
115 }
116
117 Function* cloneFunctionDecl(Module &Dst, const Function &F,
118                             ValueToValueMapTy *VMap) {
119   assert(F.getParent() != &Dst && "Can't copy decl over existing function.");
120   Function *NewF =
121     Function::Create(cast<FunctionType>(F.getType()->getElementType()),
122                      F.getLinkage(), F.getName(), &Dst);
123   NewF->copyAttributesFrom(&F);
124
125   if (VMap) {
126     (*VMap)[&F] = NewF;
127     auto NewArgI = NewF->arg_begin();
128     for (auto ArgI = F.arg_begin(), ArgE = F.arg_end(); ArgI != ArgE;
129          ++ArgI, ++NewArgI)
130       (*VMap)[&*ArgI] = &*NewArgI;
131   }
132
133   return NewF;
134 }
135
136 void moveFunctionBody(Function &OrigF, ValueToValueMapTy &VMap,
137                       ValueMaterializer *Materializer,
138                       Function *NewF) {
139   assert(!OrigF.isDeclaration() && "Nothing to move");
140   if (!NewF)
141     NewF = cast<Function>(VMap[&OrigF]);
142   else
143     assert(VMap[&OrigF] == NewF && "Incorrect function mapping in VMap.");
144   assert(NewF && "Function mapping missing from VMap.");
145   assert(NewF->getParent() != OrigF.getParent() &&
146          "moveFunctionBody should only be used to move bodies between "
147          "modules.");
148
149   SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
150   CloneFunctionInto(NewF, &OrigF, VMap, /*ModuleLevelChanges=*/true, Returns,
151                     "", nullptr, nullptr, Materializer);
152   OrigF.deleteBody();
153 }
154
155 GlobalVariable* cloneGlobalVariableDecl(Module &Dst, const GlobalVariable &GV,
156                                         ValueToValueMapTy *VMap) {
157   assert(GV.getParent() != &Dst && "Can't copy decl over existing global var.");
158   GlobalVariable *NewGV = new GlobalVariable(
159       Dst, GV.getType()->getElementType(), GV.isConstant(),
160       GV.getLinkage(), nullptr, GV.getName(), nullptr,
161       GV.getThreadLocalMode(), GV.getType()->getAddressSpace());
162   NewGV->copyAttributesFrom(&GV);
163   if (VMap)
164     (*VMap)[&GV] = NewGV;
165   return NewGV;
166 }
167
168 void moveGlobalVariableInitializer(GlobalVariable &OrigGV,
169                                    ValueToValueMapTy &VMap,
170                                    ValueMaterializer *Materializer,
171                                    GlobalVariable *NewGV) {
172   assert(OrigGV.hasInitializer() && "Nothing to move");
173   if (!NewGV)
174     NewGV = cast<GlobalVariable>(VMap[&OrigGV]);
175   else
176     assert(VMap[&OrigGV] == NewGV &&
177            "Incorrect global variable mapping in VMap.");
178   assert(NewGV->getParent() != OrigGV.getParent() &&
179          "moveGlobalVariable should only be used to move initializers between "
180          "modules");
181
182   NewGV->setInitializer(MapValue(OrigGV.getInitializer(), VMap, RF_None,
183                                  nullptr, Materializer));
184 }
185
186 GlobalAlias* cloneGlobalAliasDecl(Module &Dst, const GlobalAlias &OrigA,
187                                   ValueToValueMapTy &VMap) {
188   assert(OrigA.getAliasee() && "Original alias doesn't have an aliasee?");
189   auto *NewA = GlobalAlias::create(OrigA.getValueType(),
190                                    OrigA.getType()->getPointerAddressSpace(),
191                                    OrigA.getLinkage(), OrigA.getName(), &Dst);
192   NewA->copyAttributesFrom(&OrigA);
193   VMap[&OrigA] = NewA;
194   return NewA;
195 }
196
197 } // End namespace orc.
198 } // End namespace llvm.