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