Line data Source code
1 : //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
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 : // This file defines the common interface used by the various execution engine
11 : // subclasses.
12 : //
13 : //===----------------------------------------------------------------------===//
14 :
15 : #include "llvm/ExecutionEngine/ExecutionEngine.h"
16 : #include "llvm/ADT/STLExtras.h"
17 : #include "llvm/ADT/SmallString.h"
18 : #include "llvm/ADT/Statistic.h"
19 : #include "llvm/ExecutionEngine/GenericValue.h"
20 : #include "llvm/ExecutionEngine/JITEventListener.h"
21 : #include "llvm/ExecutionEngine/ObjectCache.h"
22 : #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
23 : #include "llvm/IR/Constants.h"
24 : #include "llvm/IR/DataLayout.h"
25 : #include "llvm/IR/DerivedTypes.h"
26 : #include "llvm/IR/Mangler.h"
27 : #include "llvm/IR/Module.h"
28 : #include "llvm/IR/Operator.h"
29 : #include "llvm/IR/ValueHandle.h"
30 : #include "llvm/Object/Archive.h"
31 : #include "llvm/Object/ObjectFile.h"
32 : #include "llvm/Support/Debug.h"
33 : #include "llvm/Support/DynamicLibrary.h"
34 : #include "llvm/Support/ErrorHandling.h"
35 : #include "llvm/Support/Host.h"
36 : #include "llvm/Support/MutexGuard.h"
37 : #include "llvm/Support/TargetRegistry.h"
38 : #include "llvm/Support/raw_ostream.h"
39 : #include "llvm/Target/TargetMachine.h"
40 : #include <cmath>
41 : #include <cstring>
42 : using namespace llvm;
43 :
44 : #define DEBUG_TYPE "jit"
45 :
46 : STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
47 : STATISTIC(NumGlobals , "Number of global vars initialized");
48 :
49 : ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 : std::unique_ptr<Module> M, std::string *ErrorStr,
51 : std::shared_ptr<MCJITMemoryManager> MemMgr,
52 : std::shared_ptr<LegacyJITSymbolResolver> Resolver,
53 : std::unique_ptr<TargetMachine> TM) = nullptr;
54 :
55 : ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
56 : std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
57 : std::shared_ptr<LegacyJITSymbolResolver> Resolver,
58 : std::unique_ptr<TargetMachine> TM) = nullptr;
59 :
60 : ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
61 : std::string *ErrorStr) =nullptr;
62 :
63 0 : void JITEventListener::anchor() {}
64 :
65 0 : void ObjectCache::anchor() {}
66 :
67 145 : void ExecutionEngine::Init(std::unique_ptr<Module> M) {
68 145 : CompilingLazily = false;
69 145 : GVCompilationDisabled = false;
70 145 : SymbolSearchingDisabled = false;
71 :
72 : // IR module verification is enabled by default in debug builds, and disabled
73 : // by default in release builds.
74 : #ifndef NDEBUG
75 : VerifyModules = true;
76 : #else
77 145 : VerifyModules = false;
78 : #endif
79 :
80 : assert(M && "Module is null?");
81 145 : Modules.push_back(std::move(M));
82 145 : }
83 :
84 24 : ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
85 72 : : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
86 24 : Init(std::move(M));
87 24 : }
88 :
89 121 : ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
90 242 : : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
91 121 : Init(std::move(M));
92 121 : }
93 :
94 65 : ExecutionEngine::~ExecutionEngine() {
95 65 : clearAllGlobalMappings();
96 65 : }
97 0 :
98 : namespace {
99 0 : /// Helper class which uses a value handler to automatically deletes the
100 65 : /// memory block when the GlobalVariable is destroyed.
101 65 : class GVMemoryBlock final : public CallbackVH {
102 65 : GVMemoryBlock(const GlobalVariable *GV)
103 : : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
104 :
105 : public:
106 : /// Returns the address the GlobalVariable should be written into. The
107 1 : /// GVMemoryBlock object prefixes that.
108 : static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
109 13 : Type *ElTy = GV->getValueType();
110 : size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
111 : void *RawMemory = ::operator new(
112 : alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
113 : new(RawMemory) GVMemoryBlock(GV);
114 13 : return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
115 13 : }
116 13 :
117 13 : void deleted() override {
118 13 : // We allocated with operator new and with some extra memory hanging off the
119 : // end, so don't just delete this. I'm not sure if this is actually
120 13 : // required.
121 : this->~GVMemoryBlock();
122 : ::operator delete(this);
123 1 : }
124 : };
125 : } // anonymous namespace
126 :
127 : char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
128 1 : return GVMemoryBlock::Create(GV, getDataLayout());
129 1 : }
130 :
131 : void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
132 : llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
133 13 : }
134 13 :
135 : void
136 : ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
137 0 : llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
138 0 : }
139 :
140 : void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
141 : llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
142 0 : }
143 0 :
144 : bool ExecutionEngine::removeModule(Module *M) {
145 : for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
146 0 : Module *Found = I->get();
147 0 : if (Found == M) {
148 : I->release();
149 : Modules.erase(I);
150 0 : clearGlobalMappingsFromModule(M);
151 0 : return true;
152 : }
153 0 : }
154 : return false;
155 0 : }
156 0 :
157 0 : Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
158 : for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
159 : Function *F = Modules[i]->getFunction(FnName);
160 : if (F && !F->isDeclaration())
161 : return F;
162 : }
163 0 : return nullptr;
164 0 : }
165 0 :
166 0 : GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
167 0 : for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
168 : GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
169 : if (GV && !GV->isDeclaration())
170 : return GV;
171 : }
172 0 : return nullptr;
173 0 : }
174 0 :
175 0 : uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
176 0 : GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
177 : uint64_t OldVal;
178 :
179 : // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
180 : // GlobalAddressMap.
181 3 : if (I == GlobalAddressMap.end())
182 3 : OldVal = 0;
183 : else {
184 : GlobalAddressReverseMap.erase(I->second);
185 : OldVal = I->second;
186 : GlobalAddressMap.erase(I);
187 6 : }
188 :
189 : return OldVal;
190 3 : }
191 3 :
192 : std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
193 : assert(GV->hasName() && "Global must have name.");
194 :
195 3 : MutexGuard locked(lock);
196 : SmallString<128> FullName;
197 :
198 138 : const DataLayout &DL =
199 : GV->getParent()->getDataLayout().isDefault()
200 : ? getDataLayout()
201 : : GV->getParent()->getDataLayout();
202 :
203 : Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
204 : return FullName.str();
205 138 : }
206 138 :
207 95 : void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
208 : MutexGuard locked(lock);
209 138 : addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
210 138 : }
211 :
212 : void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
213 19 : MutexGuard locked(lock);
214 :
215 19 : assert(!Name.empty() && "Empty GlobalMapping symbol name!");
216 19 :
217 : LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
218 19 : uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
219 : assert((!CurVal || !Addr) && "GlobalMapping already established!");
220 : CurVal = Addr;
221 :
222 : // If we are using the reverse mapping, add it too.
223 : if (!EEState.getGlobalAddressReverseMap().empty()) {
224 19 : std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
225 : assert((!V.empty() || !Name.empty()) &&
226 19 : "GlobalMapping already established!");
227 : V = Name;
228 : }
229 19 : }
230 0 :
231 : void ExecutionEngine::clearAllGlobalMappings() {
232 : MutexGuard locked(lock);
233 0 :
234 : EEState.getGlobalAddressMap().clear();
235 19 : EEState.getGlobalAddressReverseMap().clear();
236 : }
237 65 :
238 : void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
239 : MutexGuard locked(lock);
240 65 :
241 : for (GlobalObject &GO : M->global_objects())
242 65 : EEState.RemoveMapping(getMangledName(&GO));
243 : }
244 1 :
245 : uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
246 : void *Addr) {
247 : MutexGuard locked(lock);
248 1 : return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
249 1 : }
250 :
251 80 : uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
252 : MutexGuard locked(lock);
253 :
254 80 : ExecutionEngineState::GlobalAddressMapTy &Map =
255 : EEState.getGlobalAddressMap();
256 :
257 80 : // Deleting from the mapping?
258 : if (!Addr)
259 : return EEState.RemoveMapping(Name);
260 :
261 : uint64_t &CurVal = Map[Name];
262 : uint64_t OldVal = CurVal;
263 :
264 80 : if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
265 2 : EEState.getGlobalAddressReverseMap().erase(CurVal);
266 : CurVal = Addr;
267 78 :
268 78 : // If we are using the reverse mapping, add it too.
269 : if (!EEState.getGlobalAddressReverseMap().empty()) {
270 78 : std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
271 : assert((!V.empty() || !Name.empty()) &&
272 78 : "GlobalMapping already established!");
273 : V = Name;
274 : }
275 78 : return OldVal;
276 1 : }
277 :
278 : uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
279 2 : MutexGuard locked(lock);
280 : uint64_t Address = 0;
281 : ExecutionEngineState::GlobalAddressMapTy::iterator I =
282 : EEState.getGlobalAddressMap().find(S);
283 : if (I != EEState.getGlobalAddressMap().end())
284 273 : Address = I->second;
285 : return Address;
286 : }
287 :
288 273 :
289 546 : void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
290 37 : MutexGuard locked(lock);
291 273 : if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
292 : return Address;
293 : return nullptr;
294 : }
295 273 :
296 : void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
297 273 : MutexGuard locked(lock);
298 37 : return getPointerToGlobalIfAvailable(getMangledName(GV));
299 : }
300 :
301 : const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
302 38 : MutexGuard locked(lock);
303 :
304 38 : // If we haven't computed the reverse mapping yet, do so first.
305 : if (EEState.getGlobalAddressReverseMap().empty()) {
306 : for (ExecutionEngineState::GlobalAddressMapTy::iterator
307 14 : I = EEState.getGlobalAddressMap().begin(),
308 : E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
309 : StringRef Name = I->first();
310 : uint64_t Addr = I->second;
311 14 : EEState.getGlobalAddressReverseMap().insert(std::make_pair(
312 : Addr, Name));
313 7 : }
314 13 : }
315 :
316 6 : std::map<uint64_t, std::string>::iterator I =
317 6 : EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
318 :
319 : if (I != EEState.getGlobalAddressReverseMap().end()) {
320 : StringRef Name = I->second;
321 : for (unsigned i = 0, e = Modules.size(); i != e; ++i)
322 : if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
323 14 : return GV;
324 : }
325 14 : return nullptr;
326 : }
327 11 :
328 20 : namespace {
329 9 : class ArgvArray {
330 : std::unique_ptr<char[]> Array;
331 : std::vector<std::unique_ptr<char[]>> Values;
332 : public:
333 : /// Turn a vector of strings into a nice argv style array of pointers to null
334 : /// terminated strings.
335 : void *reset(LLVMContext &C, ExecutionEngine *EE,
336 : const std::vector<std::string> &InputArgv);
337 : };
338 : } // anonymous namespace
339 : void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
340 : const std::vector<std::string> &InputArgv) {
341 : Values.clear(); // Free the old contents.
342 : Values.reserve(InputArgv.size());
343 : unsigned PtrSize = EE->getDataLayout().getPointerSize();
344 : Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
345 15 :
346 : LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array.get() << "\n");
347 : Type *SBytePtr = Type::getInt8PtrTy(C);
348 30 :
349 15 : for (unsigned i = 0; i != InputArgv.size(); ++i) {
350 30 : unsigned Size = InputArgv[i].size()+1;
351 : auto Dest = make_unique<char[]>(Size);
352 : LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void *)Dest.get()
353 15 : << "\n");
354 :
355 75 : std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
356 45 : Dest[Size-1] = 0;
357 45 :
358 : // Endian safe: Array[i] = (PointerTy)Dest;
359 : EE->StoreValueToMemory(PTOGV(Dest.get()),
360 : (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
361 45 : Values.push_back(std::move(Dest));
362 45 : }
363 :
364 : // Null terminate it
365 45 : EE->StoreValueToMemory(PTOGV(nullptr),
366 45 : (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
367 : SBytePtr);
368 : return Array.get();
369 : }
370 :
371 15 : void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
372 15 : bool isDtors) {
373 : StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");
374 15 : GlobalVariable *GV = module.getNamedGlobal(Name);
375 :
376 : // If this global has internal linkage, or if it has a use, then it must be
377 199 : // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
378 : // this is the case, don't execute any of the global ctors, __main will do
379 199 : // it.
380 : if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
381 :
382 : // Should be an array of '{ i32, void ()* }' structs. The first value is
383 : // the init priority, which we ignore.
384 : ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
385 : if (!InitList)
386 199 : return;
387 : for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
388 : ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
389 : if (!CS) continue;
390 :
391 : Constant *FP = CS->getOperand(1);
392 : if (FP->isNullValue())
393 4 : continue; // Found a sentinal value, ignore.
394 2 :
395 : // Strip off constant expression casts.
396 : if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
397 2 : if (CE->isCast())
398 2 : FP = CE->getOperand(0);
399 :
400 : // Execute the ctor/dtor function!
401 : if (Function *F = dyn_cast<Function>(FP))
402 : runFunction(F, None);
403 0 :
404 : // FIXME: It is marginally lame that we just do nothing here if we see an
405 : // entry we don't recognize. It might not be unreasonable for the verifier
406 : // to not even allow this and just assert here.
407 : }
408 4 : }
409 :
410 : void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
411 : // Execute global ctors/dtors for each module in the program.
412 : for (std::unique_ptr<Module> &M : Modules)
413 : runStaticConstructorsDestructors(*M, isDtors);
414 : }
415 :
416 38 : #ifndef NDEBUG
417 : /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
418 76 : static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
419 76 : unsigned PtrSize = EE->getDataLayout().getPointerSize();
420 38 : for (unsigned i = 0; i < PtrSize; ++i)
421 : if (*(i + (uint8_t*)Loc))
422 : return false;
423 : return true;
424 : }
425 : #endif
426 :
427 : int ExecutionEngine::runFunctionAsMain(Function *Fn,
428 : const std::vector<std::string> &argv,
429 : const char * const * envp) {
430 : std::vector<GenericValue> GVArgs;
431 : GenericValue GVArgc;
432 : GVArgc.IntVal = APInt(32, argv.size());
433 155 :
434 : // Check main() type
435 : unsigned NumArgs = Fn->getFunctionType()->getNumParams();
436 153 : FunctionType *FTy = Fn->getFunctionType();
437 153 : Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
438 310 :
439 : // Check the argument types.
440 : if (NumArgs > 3)
441 155 : report_fatal_error("Invalid number of arguments of main() supplied");
442 : if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
443 155 : report_fatal_error("Invalid type for third argument of main() supplied");
444 : if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
445 : report_fatal_error("Invalid type for second argument of main() supplied");
446 155 : if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
447 0 : report_fatal_error("Invalid type for first argument of main() supplied");
448 155 : if (!FTy->getReturnType()->isIntegerTy() &&
449 0 : !FTy->getReturnType()->isVoidTy())
450 155 : report_fatal_error("Invalid return type of main() supplied");
451 0 :
452 155 : ArgvArray CArgv;
453 0 : ArgvArray CEnv;
454 310 : if (NumArgs) {
455 : GVArgs.push_back(GVArgc); // Arg #0 = argc.
456 0 : if (NumArgs > 1) {
457 : // Arg #1 = argv.
458 153 : GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
459 153 : assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
460 155 : "argv[0] was null after CreateArgv");
461 17 : if (NumArgs > 2) {
462 17 : std::vector<std::string> EnvVars;
463 : for (unsigned i = 0; envp[i]; ++i)
464 26 : EnvVars.emplace_back(envp[i]);
465 : // Arg #2 = envp.
466 : GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
467 13 : }
468 2 : }
469 32 : }
470 30 :
471 : return runFunction(Fn, GVArgs).IntVal.getZExtValue();
472 4 : }
473 :
474 : EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
475 :
476 : EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
477 463 : : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
478 : OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
479 : UseOrcMCJITReplacement(false) {
480 38 : // IR module verification is enabled by default in debug builds, and disabled
481 : // by default in release builds.
482 241 : #ifndef NDEBUG
483 : VerifyModules = true;
484 : #else
485 482 : VerifyModules = false;
486 : #endif
487 : }
488 :
489 : EngineBuilder::~EngineBuilder() = default;
490 :
491 241 : EngineBuilder &EngineBuilder::setMCJITMemoryManager(
492 : std::unique_ptr<RTDyldMemoryManager> mcjmm) {
493 241 : auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
494 : MemMgr = SharedMM;
495 : Resolver = SharedMM;
496 : return *this;
497 193 : }
498 :
499 : EngineBuilder&
500 : EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
501 : MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
502 193 : return *this;
503 : }
504 :
505 : EngineBuilder &
506 0 : EngineBuilder::setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR) {
507 0 : Resolver = std::shared_ptr<LegacyJITSymbolResolver>(std::move(SR));
508 0 : return *this;
509 : }
510 :
511 : ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
512 0 : std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
513 0 :
514 0 : // Make sure we can resolve symbols in the program as well. The zero arg
515 : // to the function tells DynamicLibrary to load the program, not a library.
516 : if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
517 222 : return nullptr;
518 :
519 : // If the user specified a memory manager but didn't specify which engine to
520 : // create, we assume they only want the JIT, and we fail if they only want
521 : // the interpreter.
522 222 : if (MemMgr) {
523 : if (WhichEngine & EngineKind::JIT)
524 : WhichEngine = EngineKind::JIT;
525 : else {
526 : if (ErrorStr)
527 : *ErrorStr = "Cannot create an interpreter with a memory manager.";
528 222 : return nullptr;
529 193 : }
530 193 : }
531 :
532 0 : // Unless the interpreter was explicitly selected or the JIT is not linked,
533 : // try making a JIT.
534 0 : if ((WhichEngine & EngineKind::JIT) && TheTM) {
535 : if (!TM->getTarget().hasJIT()) {
536 : errs() << "WARNING: This target JIT is not designed for the host"
537 : << " you are running. If bad things happen, please choose"
538 : << " a different -march switch.\n";
539 : }
540 222 :
541 198 : ExecutionEngine *EE = nullptr;
542 0 : if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
543 0 : EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
544 0 : std::move(Resolver),
545 : std::move(TheTM));
546 : EE->addModule(std::move(M));
547 : } else if (ExecutionEngine::MCJITCtor)
548 198 : EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
549 154 : std::move(Resolver), std::move(TheTM));
550 :
551 : if (EE) {
552 154 : EE->setVerifyModules(VerifyModules);
553 121 : return EE;
554 242 : }
555 : }
556 :
557 198 : // If we can't make a JIT and we didn't request one specifically, try making
558 198 : // an interpreter instead.
559 198 : if (WhichEngine & EngineKind::Interpreter) {
560 : if (ExecutionEngine::InterpCtor)
561 : return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
562 : if (ErrorStr)
563 : *ErrorStr = "Interpreter has not been linked in.";
564 : return nullptr;
565 24 : }
566 24 :
567 48 : if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
568 0 : if (ErrorStr)
569 : *ErrorStr = "JIT has not been linked in.";
570 0 : }
571 :
572 : return nullptr;
573 0 : }
574 0 :
575 : void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
576 : if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
577 : return getPointerToFunction(F);
578 :
579 : MutexGuard locked(lock);
580 : if (void* P = getPointerToGlobalIfAvailable(GV))
581 23 : return P;
582 :
583 6 : // Global variable might have been added since interpreter started.
584 : if (GlobalVariable *GVar =
585 : const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
586 17 : EmitGlobalVariable(GVar);
587 : else
588 : llvm_unreachable("Global hasn't had an address allocated yet!");
589 :
590 : return getPointerToGlobalIfAvailable(GV);
591 : }
592 1 :
593 : /// Converts a Constant* into a GenericValue, including handling of
594 0 : /// ConstantExpr values.
595 : GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
596 1 : // If its undefined, return the garbage.
597 : if (isa<UndefValue>(C)) {
598 : GenericValue Result;
599 : switch (C->getType()->getTypeID()) {
600 : default:
601 710 : break;
602 : case Type::IntegerTyID:
603 710 : case Type::X86_FP80TyID:
604 35 : case Type::FP128TyID:
605 70 : case Type::PPC_FP128TyID:
606 : // Although the value is undefined, we still have to construct an APInt
607 : // with the correct bit width.
608 1 : Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
609 : break;
610 : case Type::StructTyID: {
611 : // if the whole struct is 'undef' just reserve memory for the value.
612 : if(StructType *STy = dyn_cast<StructType>(C->getType())) {
613 : unsigned int elemNum = STy->getNumElements();
614 1 : Result.AggregateVal.resize(elemNum);
615 1 : for (unsigned int i = 0; i < elemNum; ++i) {
616 2 : Type *ElemTy = STy->getElementType(i);
617 : if (ElemTy->isIntegerTy())
618 : Result.AggregateVal[i].IntVal =
619 2 : APInt(ElemTy->getPrimitiveSizeInBits(), 0);
620 2 : else if (ElemTy->isAggregateType()) {
621 6 : const Constant *ElemUndef = UndefValue::get(ElemTy);
622 4 : Result.AggregateVal[i] = getConstantValue(ElemUndef);
623 4 : }
624 1 : }
625 2 : }
626 : }
627 1 : break;
628 1 : case Type::VectorTyID:
629 : // if the whole vector is 'undef' just reserve memory for the value.
630 : auto* VTy = dyn_cast<VectorType>(C->getType());
631 : Type *ElemTy = VTy->getElementType();
632 : unsigned int elemNum = VTy->getNumElements();
633 : Result.AggregateVal.resize(elemNum);
634 30 : if (ElemTy->isIntegerTy())
635 : for (unsigned int i = 0; i < elemNum; ++i)
636 : Result.AggregateVal[i].IntVal =
637 30 : APInt(ElemTy->getPrimitiveSizeInBits(), 0);
638 30 : break;
639 30 : }
640 30 : return Result;
641 152 : }
642 132 :
643 264 : // Otherwise, if the value is a ConstantExpr...
644 : if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
645 : Constant *Op0 = CE->getOperand(0);
646 : switch (CE->getOpcode()) {
647 : case Instruction::GetElementPtr: {
648 : // Compute the index
649 : GenericValue Result = getConstantValue(Op0);
650 : APInt Offset(DL.getPointerSizeInBits(), 0);
651 : cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
652 0 :
653 0 : char* tmp = (char*) Result.PointerVal;
654 : Result = PTOGV(tmp + Offset.getSExtValue());
655 0 : return Result;
656 0 : }
657 0 : case Instruction::Trunc: {
658 : GenericValue GV = getConstantValue(Op0);
659 0 : uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
660 0 : GV.IntVal = GV.IntVal.trunc(BitWidth);
661 : return GV;
662 : }
663 0 : case Instruction::ZExt: {
664 0 : GenericValue GV = getConstantValue(Op0);
665 0 : uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
666 0 : GV.IntVal = GV.IntVal.zext(BitWidth);
667 : return GV;
668 : }
669 0 : case Instruction::SExt: {
670 0 : GenericValue GV = getConstantValue(Op0);
671 0 : uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
672 0 : GV.IntVal = GV.IntVal.sext(BitWidth);
673 : return GV;
674 : }
675 0 : case Instruction::FPTrunc: {
676 0 : // FIXME long double
677 0 : GenericValue GV = getConstantValue(Op0);
678 0 : GV.FloatVal = float(GV.DoubleVal);
679 : return GV;
680 : }
681 0 : case Instruction::FPExt:{
682 : // FIXME long double
683 0 : GenericValue GV = getConstantValue(Op0);
684 0 : GV.DoubleVal = double(GV.FloatVal);
685 : return GV;
686 : }
687 0 : case Instruction::UIToFP: {
688 : GenericValue GV = getConstantValue(Op0);
689 0 : if (CE->getType()->isFloatTy())
690 0 : GV.FloatVal = float(GV.IntVal.roundToDouble());
691 : else if (CE->getType()->isDoubleTy())
692 : GV.DoubleVal = GV.IntVal.roundToDouble();
693 0 : else if (CE->getType()->isX86_FP80Ty()) {
694 0 : APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
695 0 : (void)apf.convertFromAPInt(GV.IntVal,
696 0 : false,
697 0 : APFloat::rmNearestTiesToEven);
698 0 : GV.IntVal = apf.bitcastToAPInt();
699 0 : }
700 0 : return GV;
701 0 : }
702 : case Instruction::SIToFP: {
703 : GenericValue GV = getConstantValue(Op0);
704 0 : if (CE->getType()->isFloatTy())
705 : GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
706 : else if (CE->getType()->isDoubleTy())
707 : GV.DoubleVal = GV.IntVal.signedRoundToDouble();
708 0 : else if (CE->getType()->isX86_FP80Ty()) {
709 0 : APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
710 0 : (void)apf.convertFromAPInt(GV.IntVal,
711 0 : true,
712 0 : APFloat::rmNearestTiesToEven);
713 0 : GV.IntVal = apf.bitcastToAPInt();
714 0 : }
715 0 : return GV;
716 0 : }
717 : case Instruction::FPToUI: // double->APInt conversion handles sign
718 : case Instruction::FPToSI: {
719 0 : GenericValue GV = getConstantValue(Op0);
720 : uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
721 : if (Op0->getType()->isFloatTy())
722 : GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
723 0 : else if (Op0->getType()->isDoubleTy())
724 : GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
725 0 : else if (Op0->getType()->isX86_FP80Ty()) {
726 0 : APFloat apf = APFloat(APFloat::x87DoubleExtended(), GV.IntVal);
727 0 : uint64_t v;
728 0 : bool ignored;
729 0 : (void)apf.convertToInteger(makeMutableArrayRef(v), BitWidth,
730 0 : CE->getOpcode()==Instruction::FPToSI,
731 0 : APFloat::rmTowardZero, &ignored);
732 0 : GV.IntVal = v; // endian?
733 : }
734 : return GV;
735 0 : }
736 : case Instruction::PtrToInt: {
737 : GenericValue GV = getConstantValue(Op0);
738 0 : uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
739 : assert(PtrWidth <= 64 && "Bad pointer width");
740 : GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
741 : uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
742 0 : GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
743 0 : return GV;
744 0 : }
745 : case Instruction::IntToPtr: {
746 0 : GenericValue GV = getConstantValue(Op0);
747 0 : uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
748 0 : GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
749 : assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
750 : GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
751 0 : return GV;
752 0 : }
753 0 : case Instruction::BitCast: {
754 0 : GenericValue GV = getConstantValue(Op0);
755 : Type* DestTy = CE->getType();
756 0 : switch (Op0->getType()->getTypeID()) {
757 : default: llvm_unreachable("Invalid bitcast operand");
758 : case Type::IntegerTyID:
759 0 : assert(DestTy->isFloatingPointTy() && "invalid bitcast");
760 0 : if (DestTy->isFloatTy())
761 0 : GV.FloatVal = GV.IntVal.bitsToFloat();
762 0 : else if (DestTy->isDoubleTy())
763 0 : GV.DoubleVal = GV.IntVal.bitsToDouble();
764 : break;
765 : case Type::FloatTyID:
766 0 : assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
767 0 : GV.IntVal = APInt::floatToBits(GV.FloatVal);
768 0 : break;
769 0 : case Type::DoubleTyID:
770 : assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
771 0 : GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
772 : break;
773 0 : case Type::PointerTyID:
774 0 : assert(DestTy->isPointerTy() && "Invalid bitcast");
775 0 : break; // getConstantValue(Op0) above already converted it
776 : }
777 0 : return GV;
778 0 : }
779 : case Instruction::Add:
780 : case Instruction::FAdd:
781 : case Instruction::Sub:
782 : case Instruction::FSub:
783 : case Instruction::Mul:
784 : case Instruction::FMul:
785 0 : case Instruction::UDiv:
786 : case Instruction::SDiv:
787 : case Instruction::URem:
788 : case Instruction::SRem:
789 : case Instruction::And:
790 : case Instruction::Or:
791 : case Instruction::Xor: {
792 : GenericValue LHS = getConstantValue(Op0);
793 : GenericValue RHS = getConstantValue(CE->getOperand(1));
794 : GenericValue GV;
795 : switch (CE->getOperand(0)->getType()->getTypeID()) {
796 : default: llvm_unreachable("Bad add type!");
797 : case Type::IntegerTyID:
798 0 : switch (CE->getOpcode()) {
799 0 : default: llvm_unreachable("Invalid integer opcode");
800 0 : case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
801 0 : case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
802 0 : case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
803 : case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
804 : case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
805 0 : case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
806 0 : case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
807 0 : case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
808 0 : case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
809 0 : case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
810 0 : }
811 0 : break;
812 0 : case Type::FloatTyID:
813 0 : switch (CE->getOpcode()) {
814 0 : default: llvm_unreachable("Invalid float opcode");
815 0 : case Instruction::FAdd:
816 : GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
817 : case Instruction::FSub:
818 : GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
819 : case Instruction::FMul:
820 0 : GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
821 0 : case Instruction::FDiv:
822 0 : GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
823 0 : case Instruction::FRem:
824 0 : GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
825 0 : }
826 0 : break;
827 0 : case Type::DoubleTyID:
828 0 : switch (CE->getOpcode()) {
829 0 : default: llvm_unreachable("Invalid double opcode");
830 0 : case Instruction::FAdd:
831 : GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
832 : case Instruction::FSub:
833 : GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
834 : case Instruction::FMul:
835 0 : GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
836 0 : case Instruction::FDiv:
837 0 : GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
838 0 : case Instruction::FRem:
839 0 : GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
840 0 : }
841 0 : break;
842 0 : case Type::X86_FP80TyID:
843 0 : case Type::PPC_FP128TyID:
844 0 : case Type::FP128TyID: {
845 0 : const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
846 : APFloat apfLHS = APFloat(Sem, LHS.IntVal);
847 : switch (CE->getOpcode()) {
848 : default: llvm_unreachable("Invalid long double opcode");
849 : case Instruction::FAdd:
850 : apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
851 0 : GV.IntVal = apfLHS.bitcastToAPInt();
852 : break;
853 : case Instruction::FSub:
854 0 : apfLHS.subtract(APFloat(Sem, RHS.IntVal),
855 : APFloat::rmNearestTiesToEven);
856 0 : GV.IntVal = apfLHS.bitcastToAPInt();
857 0 : break;
858 0 : case Instruction::FMul:
859 : apfLHS.multiply(APFloat(Sem, RHS.IntVal),
860 0 : APFloat::rmNearestTiesToEven);
861 : GV.IntVal = apfLHS.bitcastToAPInt();
862 0 : break;
863 0 : case Instruction::FDiv:
864 : apfLHS.divide(APFloat(Sem, RHS.IntVal),
865 0 : APFloat::rmNearestTiesToEven);
866 : GV.IntVal = apfLHS.bitcastToAPInt();
867 0 : break;
868 0 : case Instruction::FRem:
869 : apfLHS.mod(APFloat(Sem, RHS.IntVal));
870 0 : GV.IntVal = apfLHS.bitcastToAPInt();
871 : break;
872 0 : }
873 0 : }
874 : break;
875 0 : }
876 0 : return GV;
877 0 : }
878 0 : default:
879 : break;
880 0 : }
881 :
882 : SmallString<256> Msg;
883 : raw_svector_ostream OS(Msg);
884 : OS << "ConstantExpr not handled: " << *CE;
885 : report_fatal_error(OS.str());
886 : }
887 :
888 : // Otherwise, we have a simple constant.
889 : GenericValue Result;
890 0 : switch (C->getType()->getTypeID()) {
891 0 : case Type::FloatTyID:
892 : Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
893 : break;
894 : case Type::DoubleTyID:
895 675 : Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
896 1350 : break;
897 19 : case Type::X86_FP80TyID:
898 19 : case Type::FP128TyID:
899 19 : case Type::PPC_FP128TyID:
900 26 : Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
901 26 : break;
902 26 : case Type::IntegerTyID:
903 0 : Result.IntVal = cast<ConstantInt>(C)->getValue();
904 : break;
905 : case Type::PointerTyID:
906 0 : while (auto *A = dyn_cast<GlobalAlias>(C)) {
907 0 : C = A->getAliasee();
908 192 : }
909 192 : if (isa<ConstantPointerNull>(C))
910 192 : Result.PointerVal = nullptr;
911 50 : else if (const Function *F = dyn_cast<Function>(C))
912 : Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
913 : else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
914 : Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
915 50 : else
916 0 : llvm_unreachable("Unknown constant pointer type!");
917 : break;
918 68 : case Type::VectorTyID: {
919 : unsigned elemNum;
920 32 : Type* ElemTy;
921 : const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
922 0 : const ConstantVector *CV = dyn_cast<ConstantVector>(C);
923 : const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
924 388 :
925 : if (CDV) {
926 : elemNum = CDV->getNumElements();
927 : ElemTy = CDV->getElementType();
928 : } else if (CV || CAZ) {
929 : VectorType* VTy = dyn_cast<VectorType>(C->getType());
930 : elemNum = VTy->getNumElements();
931 388 : ElemTy = VTy->getElementType();
932 217 : } else {
933 217 : llvm_unreachable("Unknown constant vector type!");
934 171 : }
935 :
936 171 : Result.AggregateVal.resize(elemNum);
937 171 : // Check if vector holds floats.
938 : if(ElemTy->isFloatTy()) {
939 0 : if (CAZ) {
940 : GenericValue floatZero;
941 : floatZero.FloatVal = 0.f;
942 388 : std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
943 : floatZero);
944 388 : break;
945 38 : }
946 20 : if(CV) {
947 20 : for (unsigned i = 0; i < elemNum; ++i)
948 : if (!isa<UndefValue>(CV->getOperand(i)))
949 : Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
950 : CV->getOperand(i))->getValueAPF().convertToFloat();
951 : break;
952 18 : }
953 0 : if(CDV)
954 0 : for (unsigned i = 0; i < elemNum; ++i)
955 0 : Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
956 0 :
957 : break;
958 : }
959 18 : // Check if vector holds doubles.
960 103 : if (ElemTy->isDoubleTy()) {
961 170 : if (CAZ) {
962 : GenericValue doubleZero;
963 : doubleZero.DoubleVal = 0.0;
964 : std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
965 : doubleZero);
966 350 : break;
967 49 : }
968 20 : if(CV) {
969 20 : for (unsigned i = 0; i < elemNum; ++i)
970 : if (!isa<UndefValue>(CV->getOperand(i)))
971 : Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
972 : CV->getOperand(i))->getValueAPF().convertToDouble();
973 : break;
974 29 : }
975 0 : if(CDV)
976 0 : for (unsigned i = 0; i < elemNum; ++i)
977 0 : Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
978 0 :
979 : break;
980 : }
981 29 : // Check if vector holds integers.
982 144 : if (ElemTy->isIntegerTy()) {
983 230 : if (CAZ) {
984 : GenericValue intZero;
985 : intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
986 : std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
987 : intZero);
988 301 : break;
989 301 : }
990 81 : if(CV) {
991 162 : for (unsigned i = 0; i < elemNum; ++i)
992 : if (!isa<UndefValue>(CV->getOperand(i)))
993 : Result.AggregateVal[i].IntVal = cast<ConstantInt>(
994 : CV->getOperand(i))->getValue();
995 : else {
996 220 : Result.AggregateVal[i].IntVal =
997 298 : APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
998 248 : }
999 248 : break;
1000 248 : }
1001 : if(CDV)
1002 0 : for (unsigned i = 0; i < elemNum; ++i)
1003 0 : Result.AggregateVal[i].IntVal = APInt(
1004 : CDV->getElementType()->getPrimitiveSizeInBits(),
1005 : CDV->getElementAsInteger(i));
1006 :
1007 170 : break;
1008 906 : }
1009 1472 : llvm_unreachable("Unknown constant pointer type!");
1010 : }
1011 : break;
1012 :
1013 : default:
1014 : SmallString<256> Msg;
1015 0 : raw_svector_ostream OS(Msg);
1016 : OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1017 : report_fatal_error(OS.str());
1018 : }
1019 :
1020 : return Result;
1021 : }
1022 0 :
1023 0 : /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1024 : /// with the integer held in IntVal.
1025 : static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1026 : unsigned StoreBytes) {
1027 : assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
1028 : const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
1029 :
1030 : if (sys::IsLittleEndianHost) {
1031 : // Little-endian host - the source is ordered from LSB to MSB. Order the
1032 : // destination from LSB to MSB: Do a straight copy.
1033 : memcpy(Dst, Src, StoreBytes);
1034 : } else {
1035 : // Big-endian host - the source is an array of 64 bit words ordered from
1036 : // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1037 : // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1038 : while (StoreBytes > sizeof(uint64_t)) {
1039 26 : StoreBytes -= sizeof(uint64_t);
1040 : // May not be aligned so use memcpy.
1041 : memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1042 : Src += sizeof(uint64_t);
1043 : }
1044 :
1045 : memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1046 : }
1047 : }
1048 :
1049 : void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1050 : GenericValue *Ptr, Type *Ty) {
1051 : const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
1052 :
1053 : switch (Ty->getTypeID()) {
1054 : default:
1055 93 : dbgs() << "Cannot store value of type " << *Ty << "!\n";
1056 : break;
1057 93 : case Type::IntegerTyID:
1058 : StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1059 93 : break;
1060 0 : case Type::FloatTyID:
1061 0 : *((float*)Ptr) = Val.FloatVal;
1062 0 : break;
1063 22 : case Type::DoubleTyID:
1064 : *((double*)Ptr) = Val.DoubleVal;
1065 : break;
1066 4 : case Type::X86_FP80TyID:
1067 4 : memcpy(Ptr, Val.IntVal.getRawData(), 10);
1068 4 : break;
1069 4 : case Type::PointerTyID:
1070 4 : // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1071 4 : if (StoreBytes != sizeof(PointerTy))
1072 0 : memset(&(Ptr->PointerVal), 0, StoreBytes);
1073 0 :
1074 0 : *((PointerTy*)Ptr) = Val.PointerVal;
1075 60 : break;
1076 : case Type::VectorTyID:
1077 60 : for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1078 0 : if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1079 : *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1080 60 : if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1081 60 : *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1082 : if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1083 18 : unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1084 24 : StoreIntToMemory(Val.AggregateVal[i].IntVal,
1085 4 : (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1086 12 : }
1087 4 : }
1088 12 : break;
1089 4 : }
1090 4 :
1091 4 : if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
1092 : // Host and target are different endian - reverse the stored bytes.
1093 3 : std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1094 : }
1095 :
1096 : /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1097 93 : /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1098 : static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1099 0 : assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1100 93 : uint8_t *Dst = reinterpret_cast<uint8_t *>(
1101 : const_cast<uint64_t *>(IntVal.getRawData()));
1102 :
1103 : if (sys::IsLittleEndianHost)
1104 : // Little-endian host - the destination must be ordered from LSB to MSB.
1105 : // The source is ordered from LSB to MSB: Do a straight copy.
1106 : memcpy(Dst, Src, LoadBytes);
1107 : else {
1108 : // Big-endian - the destination is an array of 64 bit words ordered from
1109 : // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1110 : // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1111 : // a word.
1112 19 : while (LoadBytes > sizeof(uint64_t)) {
1113 : LoadBytes -= sizeof(uint64_t);
1114 : // May not be aligned so use memcpy.
1115 : memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1116 : Dst += sizeof(uint64_t);
1117 : }
1118 :
1119 : memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1120 : }
1121 : }
1122 :
1123 : /// FIXME: document
1124 : ///
1125 : void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1126 : GenericValue *Ptr,
1127 : Type *Ty) {
1128 : const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
1129 :
1130 : switch (Ty->getTypeID()) {
1131 30 : case Type::IntegerTyID:
1132 : // An APInt with all words initially zero.
1133 : Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1134 : LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1135 : break;
1136 30 : case Type::FloatTyID:
1137 : Result.FloatVal = *((float*)Ptr);
1138 : break;
1139 19 : case Type::DoubleTyID:
1140 : Result.DoubleVal = *((double*)Ptr);
1141 : break;
1142 4 : case Type::PointerTyID:
1143 4 : Result.PointerVal = *((PointerTy*)Ptr);
1144 4 : break;
1145 4 : case Type::X86_FP80TyID: {
1146 4 : // This is endian dependent, but it will only work on x86 anyway.
1147 4 : // FIXME: Will not trap if loading a signaling NaN.
1148 0 : uint64_t y[2];
1149 0 : memcpy(y, Ptr, 10);
1150 0 : Result.IntVal = APInt(80, y);
1151 0 : break;
1152 : }
1153 : case Type::VectorTyID: {
1154 : auto *VT = cast<VectorType>(Ty);
1155 0 : Type *ElemT = VT->getElementType();
1156 0 : const unsigned numElems = VT->getNumElements();
1157 : if (ElemT->isFloatTy()) {
1158 : Result.AggregateVal.resize(numElems);
1159 : for (unsigned i = 0; i < numElems; ++i)
1160 : Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1161 3 : }
1162 3 : if (ElemT->isDoubleTy()) {
1163 3 : Result.AggregateVal.resize(numElems);
1164 1 : for (unsigned i = 0; i < numElems; ++i)
1165 5 : Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1166 8 : }
1167 : if (ElemT->isIntegerTy()) {
1168 3 : GenericValue intZero;
1169 1 : const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1170 5 : intZero.IntVal = APInt(elemBitWidth, 0);
1171 8 : Result.AggregateVal.resize(numElems, intZero);
1172 : for (unsigned i = 0; i < numElems; ++i)
1173 3 : LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1174 1 : (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1175 : }
1176 1 : break;
1177 1 : }
1178 5 : default:
1179 8 : SmallString<256> Msg;
1180 4 : raw_svector_ostream OS(Msg);
1181 : OS << "Cannot load value of type " << *Ty << "!";
1182 : report_fatal_error(OS.str());
1183 : }
1184 : }
1185 :
1186 : void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1187 0 : LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1188 0 : LLVM_DEBUG(Init->dump());
1189 : if (isa<UndefValue>(Init))
1190 30 : return;
1191 :
1192 13 : if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1193 : unsigned ElementSize =
1194 : getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
1195 13 : for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1196 : InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1197 : return;
1198 : }
1199 :
1200 0 : if (isa<ConstantAggregateZero>(Init)) {
1201 0 : memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
1202 0 : return;
1203 : }
1204 :
1205 : if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1206 13 : unsigned ElementSize =
1207 1 : getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
1208 1 : for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1209 : InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1210 : return;
1211 : }
1212 :
1213 0 : if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1214 0 : const StructLayout *SL =
1215 0 : getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
1216 : for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1217 : InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1218 : return;
1219 : }
1220 :
1221 0 : if (const ConstantDataSequential *CDS =
1222 0 : dyn_cast<ConstantDataSequential>(Init)) {
1223 0 : // CDS is already laid out in host memory order.
1224 : StringRef Data = CDS->getRawDataValues();
1225 : memcpy(Addr, Data.data(), Data.size());
1226 : return;
1227 : }
1228 :
1229 : if (Init->getType()->isFirstClassType()) {
1230 11 : GenericValue Val = getConstantValue(Init);
1231 11 : StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1232 : return;
1233 : }
1234 :
1235 1 : LLVM_DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1236 2 : llvm_unreachable("Unknown constant type to initialize memory with!");
1237 1 : }
1238 :
1239 : /// EmitGlobals - Emit all of the global variables to memory, storing their
1240 : /// addresses into GlobalAddress. This must make sure to copy the contents of
1241 : /// their initializers into the memory.
1242 0 : void ExecutionEngine::emitGlobals() {
1243 : // Loop over all of the global variables in the program, allocating the memory
1244 : // to hold them. If there is more than one module, do a prepass over globals
1245 : // to figure out how the different modules should link together.
1246 : std::map<std::pair<std::string, Type*>,
1247 : const GlobalValue*> LinkedGlobalsMap;
1248 24 :
1249 : if (Modules.size() != 1) {
1250 : for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1251 : Module &M = *Modules[m];
1252 : for (const auto &GV : M.globals()) {
1253 : if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1254 : GV.hasAppendingLinkage() || !GV.hasName())
1255 24 : continue;// Ignore external globals and globals with internal linkage.
1256 0 :
1257 0 : const GlobalValue *&GVEntry =
1258 0 : LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1259 0 :
1260 0 : // If this is the first time we've seen this global, it is the canonical
1261 0 : // version.
1262 : if (!GVEntry) {
1263 : GVEntry = &GV;
1264 0 : continue;
1265 : }
1266 :
1267 : // If the existing global is strong, never replace it.
1268 0 : if (GVEntry->hasExternalLinkage())
1269 0 : continue;
1270 0 :
1271 : // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1272 : // symbol. FIXME is this right for common?
1273 : if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1274 0 : GVEntry = &GV;
1275 : }
1276 : }
1277 : }
1278 :
1279 0 : std::vector<const GlobalValue*> NonCanonicalGlobals;
1280 0 : for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1281 : Module &M = *Modules[m];
1282 : for (const auto &GV : M.globals()) {
1283 : // In the multi-module case, see what this global maps to.
1284 : if (!LinkedGlobalsMap.empty()) {
1285 : if (const GlobalValue *GVEntry =
1286 48 : LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1287 24 : // If something else is the canonical global, ignore this one.
1288 36 : if (GVEntry != &GV) {
1289 : NonCanonicalGlobals.push_back(&GV);
1290 12 : continue;
1291 0 : }
1292 0 : }
1293 : }
1294 0 :
1295 0 : if (!GV.isDeclaration()) {
1296 0 : addGlobalMapping(&GV, getMemoryForGV(&GV));
1297 : } else {
1298 : // External variable reference. Try to use the dynamic loader to
1299 : // get a pointer to it.
1300 : if (void *SymAddr =
1301 12 : sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1302 12 : addGlobalMapping(&GV, SymAddr);
1303 : else {
1304 : report_fatal_error("Could not resolve external global address: "
1305 : +GV.getName());
1306 0 : }
1307 0 : }
1308 0 : }
1309 :
1310 0 : // If there are multiple modules, map the non-canonical globals to their
1311 0 : // canonical location.
1312 : if (!NonCanonicalGlobals.empty()) {
1313 : for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1314 : const GlobalValue *GV = NonCanonicalGlobals[i];
1315 : const GlobalValue *CGV =
1316 : LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1317 : void *Ptr = getPointerToGlobalIfAvailable(CGV);
1318 24 : assert(Ptr && "Canonical global wasn't codegen'd!");
1319 0 : addGlobalMapping(GV, Ptr);
1320 0 : }
1321 : }
1322 0 :
1323 0 : // Now that all of the globals are set up in memory, loop through them all
1324 : // and initialize their contents.
1325 0 : for (const auto &GV : M.globals()) {
1326 : if (!GV.isDeclaration()) {
1327 : if (!LinkedGlobalsMap.empty()) {
1328 : if (const GlobalValue *GVEntry =
1329 : LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1330 : if (GVEntry != &GV) // Not the canonical variable.
1331 36 : continue;
1332 12 : }
1333 12 : EmitGlobalVariable(&GV);
1334 0 : }
1335 0 : }
1336 0 : }
1337 : }
1338 :
1339 12 : // EmitGlobalVariable - This method emits the specified global variable to the
1340 : // address specified in GlobalAddresses, or allocates new memory if it's not
1341 : // already in the map.
1342 : void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1343 24 : void *GA = getPointerToGlobalIfAvailable(GV);
1344 :
1345 : if (!GA) {
1346 : // If it's not already specified, allocate memory for the global.
1347 : GA = getMemoryForGV(GV);
1348 13 :
1349 13 : // If we failed to allocate memory for this global, return.
1350 : if (!GA) return;
1351 13 :
1352 : addGlobalMapping(GV, GA);
1353 1 : }
1354 :
1355 : // Don't initialize if it's thread local, let the client do it.
1356 1 : if (!GV->isThreadLocal())
1357 : InitializeMemory(GV->getInitializer(), GA);
1358 1 :
1359 : Type *ElTy = GV->getValueType();
1360 : size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
1361 : NumInitBytes += (unsigned)GVSize;
1362 13 : ++NumGlobals;
1363 13 : }
|