1//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the common interface used by the various execution engine
10// subclasses.
11//
12// FIXME: This file needs to be updated to support scalable vectors
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ExecutionEngine/ExecutionEngine.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/MC/TargetRegistry.h"
31#include "llvm/Object/Archive.h"
32#include "llvm/Object/ObjectFile.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/DynamicLibrary.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/raw_ostream.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/TargetParser/Host.h"
39#include <cmath>
40#include <cstring>
41#include <mutex>
42using namespace llvm;
43
44#define DEBUG_TYPE "jit"
45
46STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
47STATISTIC(NumGlobals , "Number of global vars initialized");
48
49ExecutionEngine *(*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
55ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
56 std::string *ErrorStr) =nullptr;
57
58void JITEventListener::anchor() {}
59
60void ObjectCache::anchor() {}
61
62void ExecutionEngine::Init(std::unique_ptr<Module> M) {
63 CompilingLazily = false;
64 GVCompilationDisabled = false;
65 SymbolSearchingDisabled = false;
66
67 // IR module verification is enabled by default in debug builds, and disabled
68 // by default in release builds.
69#ifndef NDEBUG
70 VerifyModules = true;
71#else
72 VerifyModules = false;
73#endif
74
75 assert(M && "Module is null?");
76 Modules.push_back(Elt: std::move(M));
77}
78
79ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
80 : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
81 Init(M: std::move(M));
82}
83
84ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
85 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
86 Init(M: std::move(M));
87}
88
89ExecutionEngine::~ExecutionEngine() {
90 clearAllGlobalMappings();
91}
92
93namespace {
94/// Helper class which uses a value handler to automatically deletes the
95/// memory block when the GlobalVariable is destroyed.
96class GVMemoryBlock final : public CallbackVH {
97 GVMemoryBlock(const GlobalVariable *GV)
98 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
99
100public:
101 /// Returns the address the GlobalVariable should be written into. The
102 /// GVMemoryBlock object prefixes that.
103 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
104 Type *ElTy = GV->getValueType();
105 size_t GVSize = (size_t)TD.getTypeAllocSize(Ty: ElTy);
106 void *RawMemory = ::operator new(
107 alignTo(Size: sizeof(GVMemoryBlock), A: TD.getPreferredAlign(GV)) + GVSize);
108 new(RawMemory) GVMemoryBlock(GV);
109 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
110 }
111
112 void deleted() override {
113 // We allocated with operator new and with some extra memory hanging off the
114 // end, so don't just delete this. I'm not sure if this is actually
115 // required.
116 this->~GVMemoryBlock();
117 ::operator delete(this);
118 }
119};
120} // anonymous namespace
121
122char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
123 return GVMemoryBlock::Create(GV, TD: getDataLayout());
124}
125
126void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
127 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
128}
129
130void
131ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
132 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
133}
134
135void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
136 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
137}
138
139bool ExecutionEngine::removeModule(Module *M) {
140 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
141 Module *Found = I->get();
142 if (Found == M) {
143 I->release();
144 Modules.erase(CI: I);
145 clearGlobalMappingsFromModule(M);
146 return true;
147 }
148 }
149 return false;
150}
151
152Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
153 for (const auto &M : Modules) {
154 Function *F = M->getFunction(Name: FnName);
155 if (F && !F->isDeclaration())
156 return F;
157 }
158 return nullptr;
159}
160
161GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
162 for (const auto &M : Modules) {
163 GlobalVariable *GV = M->getGlobalVariable(Name, AllowInternal);
164 if (GV && !GV->isDeclaration())
165 return GV;
166 }
167 return nullptr;
168}
169
170uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
171 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Key: Name);
172 uint64_t OldVal;
173
174 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
175 // GlobalAddressMap.
176 if (I == GlobalAddressMap.end())
177 OldVal = 0;
178 else {
179 GlobalAddressReverseMap.erase(x: I->second);
180 OldVal = I->second;
181 GlobalAddressMap.erase(I);
182 }
183
184 return OldVal;
185}
186
187std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
188 assert(GV->hasName() && "Global must have name.");
189
190 std::lock_guard<sys::Mutex> locked(lock);
191 SmallString<128> FullName;
192
193 const DataLayout &DL =
194 GV->getDataLayout().isDefault()
195 ? getDataLayout()
196 : GV->getDataLayout();
197
198 Mangler::getNameWithPrefix(OutName&: FullName, GVName: GV->getName(), DL);
199 return std::string(FullName);
200}
201
202void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
203 std::lock_guard<sys::Mutex> locked(lock);
204 addGlobalMapping(Name: getMangledName(GV), Addr: (uint64_t) Addr);
205}
206
207void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
208 std::lock_guard<sys::Mutex> locked(lock);
209
210 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
211
212 LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
213 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
214 assert((!CurVal || !Addr) && "GlobalMapping already established!");
215 CurVal = Addr;
216
217 // If we are using the reverse mapping, add it too.
218 if (!EEState.getGlobalAddressReverseMap().empty()) {
219 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
220 assert((!V.empty() || !Name.empty()) &&
221 "GlobalMapping already established!");
222 V = std::string(Name);
223 }
224}
225
226void ExecutionEngine::clearAllGlobalMappings() {
227 std::lock_guard<sys::Mutex> locked(lock);
228
229 EEState.getGlobalAddressMap().clear();
230 EEState.getGlobalAddressReverseMap().clear();
231}
232
233void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
234 std::lock_guard<sys::Mutex> locked(lock);
235
236 for (GlobalObject &GO : M->global_objects())
237 EEState.RemoveMapping(Name: getMangledName(GV: &GO));
238}
239
240uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
241 void *Addr) {
242 std::lock_guard<sys::Mutex> locked(lock);
243 return updateGlobalMapping(Name: getMangledName(GV), Addr: (uint64_t) Addr);
244}
245
246uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
247 std::lock_guard<sys::Mutex> locked(lock);
248
249 ExecutionEngineState::GlobalAddressMapTy &Map =
250 EEState.getGlobalAddressMap();
251
252 // Deleting from the mapping?
253 if (!Addr)
254 return EEState.RemoveMapping(Name);
255
256 uint64_t &CurVal = Map[Name];
257 uint64_t OldVal = CurVal;
258
259 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
260 EEState.getGlobalAddressReverseMap().erase(x: CurVal);
261 CurVal = Addr;
262
263 // If we are using the reverse mapping, add it too.
264 if (!EEState.getGlobalAddressReverseMap().empty()) {
265 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
266 assert((!V.empty() || !Name.empty()) &&
267 "GlobalMapping already established!");
268 V = std::string(Name);
269 }
270 return OldVal;
271}
272
273uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
274 std::lock_guard<sys::Mutex> locked(lock);
275 uint64_t Address = 0;
276 ExecutionEngineState::GlobalAddressMapTy::iterator I =
277 EEState.getGlobalAddressMap().find(Key: S);
278 if (I != EEState.getGlobalAddressMap().end())
279 Address = I->second;
280 return Address;
281}
282
283
284void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
285 std::lock_guard<sys::Mutex> locked(lock);
286 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
287 return Address;
288 return nullptr;
289}
290
291void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
292 std::lock_guard<sys::Mutex> locked(lock);
293 return getPointerToGlobalIfAvailable(S: getMangledName(GV));
294}
295
296const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
297 std::lock_guard<sys::Mutex> locked(lock);
298
299 // If we haven't computed the reverse mapping yet, do so first.
300 if (EEState.getGlobalAddressReverseMap().empty()) {
301 for (ExecutionEngineState::GlobalAddressMapTy::iterator
302 I = EEState.getGlobalAddressMap().begin(),
303 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
304 StringRef Name = I->first();
305 uint64_t Addr = I->second;
306 EEState.getGlobalAddressReverseMap().insert(
307 x: std::make_pair(x&: Addr, y: std::string(Name)));
308 }
309 }
310
311 std::map<uint64_t, std::string>::iterator I =
312 EEState.getGlobalAddressReverseMap().find(x: (uint64_t) Addr);
313
314 if (I != EEState.getGlobalAddressReverseMap().end()) {
315 StringRef Name = I->second;
316 for (const auto &M : Modules)
317 if (GlobalValue *GV = M->getNamedValue(Name))
318 return GV;
319 }
320 return nullptr;
321}
322
323namespace {
324class ArgvArray {
325 std::unique_ptr<char[]> Array;
326 std::vector<std::unique_ptr<char[]>> Values;
327public:
328 /// Turn a vector of strings into a nice argv style array of pointers to null
329 /// terminated strings.
330 void *reset(LLVMContext &C, ExecutionEngine *EE,
331 const std::vector<std::string> &InputArgv);
332};
333} // anonymous namespace
334void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
335 const std::vector<std::string> &InputArgv) {
336 Values.clear(); // Free the old contents.
337 Values.reserve(n: InputArgv.size());
338 unsigned PtrSize = EE->getDataLayout().getPointerSize();
339 Array = std::make_unique<char[]>(num: (InputArgv.size()+1)*PtrSize);
340
341 LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array.get() << "\n");
342 Type *SBytePtr = PointerType::getUnqual(C);
343
344 for (unsigned i = 0; i != InputArgv.size(); ++i) {
345 unsigned Size = InputArgv[i].size()+1;
346 auto Dest = std::make_unique<char[]>(num: Size);
347 LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void *)Dest.get()
348 << "\n");
349
350 llvm::copy(Range: InputArgv[i], Out: Dest.get());
351 Dest[Size-1] = 0;
352
353 // Endian safe: Array[i] = (PointerTy)Dest;
354 EE->StoreValueToMemory(Val: PTOGV(P: Dest.get()),
355 Ptr: (GenericValue*)(&Array[i*PtrSize]), Ty: SBytePtr);
356 Values.push_back(x: std::move(Dest));
357 }
358
359 // Null terminate it
360 EE->StoreValueToMemory(Val: PTOGV(P: nullptr),
361 Ptr: (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
362 Ty: SBytePtr);
363 return Array.get();
364}
365
366void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
367 bool isDtors) {
368 StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");
369 GlobalVariable *GV = module.getNamedGlobal(Name);
370
371 // If this global has internal linkage, or if it has a use, then it must be
372 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
373 // this is the case, don't execute any of the global ctors, __main will do
374 // it.
375 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
376
377 // Should be an array of '{ i32, void ()* }' structs. The first value is
378 // the init priority, which we ignore.
379 ConstantArray *InitList = dyn_cast<ConstantArray>(Val: GV->getInitializer());
380 if (!InitList)
381 return;
382 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
383 ConstantStruct *CS = dyn_cast<ConstantStruct>(Val: InitList->getOperand(i_nocapture: i));
384 if (!CS) continue;
385
386 Constant *FP = CS->getOperand(i_nocapture: 1);
387 if (FP->isNullValue())
388 continue; // Found a sentinel value, ignore.
389
390 // Strip off constant expression casts.
391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: FP))
392 if (CE->isCast())
393 FP = CE->getOperand(i_nocapture: 0);
394
395 // Execute the ctor/dtor function!
396 if (Function *F = dyn_cast<Function>(Val: FP))
397 runFunction(F, ArgValues: {});
398
399 // FIXME: It is marginally lame that we just do nothing here if we see an
400 // entry we don't recognize. It might not be unreasonable for the verifier
401 // to not even allow this and just assert here.
402 }
403}
404
405void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
406 // Execute global ctors/dtors for each module in the program.
407 for (std::unique_ptr<Module> &M : Modules)
408 runStaticConstructorsDestructors(module&: *M, isDtors);
409}
410
411#ifndef NDEBUG
412/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
413static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
414 unsigned PtrSize = EE->getDataLayout().getPointerSize();
415 for (unsigned i = 0; i < PtrSize; ++i)
416 if (*(i + (uint8_t*)Loc))
417 return false;
418 return true;
419}
420#endif
421
422int ExecutionEngine::runFunctionAsMain(Function *Fn,
423 const std::vector<std::string> &argv,
424 const char * const * envp) {
425 std::vector<GenericValue> GVArgs;
426 GenericValue GVArgc;
427 GVArgc.IntVal = APInt(32, argv.size());
428
429 // Check main() type
430 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
431 FunctionType *FTy = Fn->getFunctionType();
432 Type *PPInt8Ty = PointerType::get(C&: Fn->getContext(), AddressSpace: 0);
433
434 // Check the argument types.
435 if (NumArgs > 3)
436 report_fatal_error(reason: "Invalid number of arguments of main() supplied");
437 if (NumArgs >= 3 && FTy->getParamType(i: 2) != PPInt8Ty)
438 report_fatal_error(reason: "Invalid type for third argument of main() supplied");
439 if (NumArgs >= 2 && FTy->getParamType(i: 1) != PPInt8Ty)
440 report_fatal_error(reason: "Invalid type for second argument of main() supplied");
441 if (NumArgs >= 1 && !FTy->getParamType(i: 0)->isIntegerTy(BitWidth: 32))
442 report_fatal_error(reason: "Invalid type for first argument of main() supplied");
443 if (!FTy->getReturnType()->isIntegerTy() &&
444 !FTy->getReturnType()->isVoidTy())
445 report_fatal_error(reason: "Invalid return type of main() supplied");
446
447 ArgvArray CArgv;
448 ArgvArray CEnv;
449 if (NumArgs) {
450 GVArgs.push_back(x: GVArgc); // Arg #0 = argc.
451 if (NumArgs > 1) {
452 // Arg #1 = argv.
453 GVArgs.push_back(x: PTOGV(P: CArgv.reset(C&: Fn->getContext(), EE: this, InputArgv: argv)));
454 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
455 "argv[0] was null after CreateArgv");
456 if (NumArgs > 2) {
457 std::vector<std::string> EnvVars;
458 for (unsigned i = 0; envp[i]; ++i)
459 EnvVars.emplace_back(args: envp[i]);
460 // Arg #2 = envp.
461 GVArgs.push_back(x: PTOGV(P: CEnv.reset(C&: Fn->getContext(), EE: this, InputArgv: EnvVars)));
462 }
463 }
464 }
465
466 return runFunction(F: Fn, ArgValues: GVArgs).IntVal.getZExtValue();
467}
468
469EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
470
471EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
472 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
473 OptLevel(CodeGenOptLevel::Default), MemMgr(nullptr), Resolver(nullptr) {
474// IR module verification is enabled by default in debug builds, and disabled
475// by default in release builds.
476#ifndef NDEBUG
477 VerifyModules = true;
478#else
479 VerifyModules = false;
480#endif
481}
482
483EngineBuilder::~EngineBuilder() = default;
484
485EngineBuilder &EngineBuilder::setMCJITMemoryManager(
486 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
487 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
488 MemMgr = SharedMM;
489 Resolver = std::move(SharedMM);
490 return *this;
491}
492
493EngineBuilder&
494EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
495 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
496 return *this;
497}
498
499EngineBuilder &
500EngineBuilder::setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR) {
501 Resolver = std::shared_ptr<LegacyJITSymbolResolver>(std::move(SR));
502 return *this;
503}
504
505ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
506 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
507
508 // Make sure we can resolve symbols in the program as well. The zero arg
509 // to the function tells DynamicLibrary to load the program, not a library.
510 if (sys::DynamicLibrary::LoadLibraryPermanently(Filename: nullptr, ErrMsg: ErrorStr))
511 return nullptr;
512
513 // If the user specified a memory manager but didn't specify which engine to
514 // create, we assume they only want the JIT, and we fail if they only want
515 // the interpreter.
516 if (MemMgr) {
517 if (WhichEngine & EngineKind::JIT)
518 WhichEngine = EngineKind::JIT;
519 else {
520 if (ErrorStr)
521 *ErrorStr = "Cannot create an interpreter with a memory manager.";
522 return nullptr;
523 }
524 }
525
526 // Unless the interpreter was explicitly selected or the JIT is not linked,
527 // try making a JIT.
528 if ((WhichEngine & EngineKind::JIT) && TheTM) {
529 if (!TM->getTarget().hasJIT()) {
530 errs() << "WARNING: This target JIT is not designed for the host"
531 << " you are running. If bad things happen, please choose"
532 << " a different -march switch.\n";
533 }
534
535 ExecutionEngine *EE = nullptr;
536 if (ExecutionEngine::MCJITCtor)
537 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
538 std::move(Resolver), std::move(TheTM));
539
540 if (EE) {
541 EE->setVerifyModules(VerifyModules);
542 return EE;
543 }
544 }
545
546 // If we can't make a JIT and we didn't request one specifically, try making
547 // an interpreter instead.
548 if (WhichEngine & EngineKind::Interpreter) {
549 if (ExecutionEngine::InterpCtor)
550 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
551 if (ErrorStr)
552 *ErrorStr = "Interpreter has not been linked in.";
553 return nullptr;
554 }
555
556 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
557 if (ErrorStr)
558 *ErrorStr = "JIT has not been linked in.";
559 }
560
561 return nullptr;
562}
563
564void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
565 if (Function *F = const_cast<Function*>(dyn_cast<Function>(Val: GV)))
566 return getPointerToFunction(F);
567
568 std::lock_guard<sys::Mutex> locked(lock);
569 if (void* P = getPointerToGlobalIfAvailable(GV))
570 return P;
571
572 // Global variable might have been added since interpreter started.
573 if (GlobalVariable *GVar =
574 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(Val: GV)))
575 emitGlobalVariable(GV: GVar);
576 else
577 llvm_unreachable("Global hasn't had an address allocated yet!");
578
579 return getPointerToGlobalIfAvailable(GV);
580}
581
582/// Converts a Constant* into a GenericValue, including handling of
583/// ConstantExpr values.
584GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
585 // If its undefined, return the garbage.
586 if (isa<UndefValue>(Val: C)) {
587 GenericValue Result;
588 switch (C->getType()->getTypeID()) {
589 default:
590 break;
591 case Type::IntegerTyID:
592 case Type::X86_FP80TyID:
593 case Type::FP128TyID:
594 case Type::PPC_FP128TyID:
595 // Although the value is undefined, we still have to construct an APInt
596 // with the correct bit width.
597 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
598 break;
599 case Type::StructTyID: {
600 // if the whole struct is 'undef' just reserve memory for the value.
601 if(StructType *STy = dyn_cast<StructType>(Val: C->getType())) {
602 unsigned int elemNum = STy->getNumElements();
603 Result.AggregateVal.resize(new_size: elemNum);
604 for (unsigned int i = 0; i < elemNum; ++i) {
605 Type *ElemTy = STy->getElementType(N: i);
606 if (ElemTy->isIntegerTy())
607 Result.AggregateVal[i].IntVal =
608 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
609 else if (ElemTy->isAggregateType()) {
610 const Constant *ElemUndef = UndefValue::get(T: ElemTy);
611 Result.AggregateVal[i] = getConstantValue(C: ElemUndef);
612 }
613 }
614 }
615 }
616 break;
617 case Type::ScalableVectorTyID:
618 report_fatal_error(
619 reason: "Scalable vector support not yet implemented in ExecutionEngine");
620 case Type::ArrayTyID: {
621 auto *ArrTy = cast<ArrayType>(Val: C->getType());
622 Type *ElemTy = ArrTy->getElementType();
623 unsigned int elemNum = ArrTy->getNumElements();
624 Result.AggregateVal.resize(new_size: elemNum);
625 if (ElemTy->isIntegerTy())
626 for (unsigned int i = 0; i < elemNum; ++i)
627 Result.AggregateVal[i].IntVal =
628 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
629 break;
630 }
631 case Type::FixedVectorTyID: {
632 // if the whole vector is 'undef' just reserve memory for the value.
633 auto *VTy = cast<FixedVectorType>(Val: C->getType());
634 Type *ElemTy = VTy->getElementType();
635 unsigned int elemNum = VTy->getNumElements();
636 Result.AggregateVal.resize(new_size: elemNum);
637 if (ElemTy->isIntegerTy())
638 for (unsigned int i = 0; i < elemNum; ++i)
639 Result.AggregateVal[i].IntVal =
640 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
641 break;
642 }
643 }
644 return Result;
645 }
646
647 // Otherwise, if the value is a ConstantExpr...
648 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: C)) {
649 Constant *Op0 = CE->getOperand(i_nocapture: 0);
650 switch (CE->getOpcode()) {
651 case Instruction::GetElementPtr: {
652 // Compute the index
653 GenericValue Result = getConstantValue(C: Op0);
654 APInt Offset(DL.getPointerSizeInBits(), 0);
655 cast<GEPOperator>(Val: CE)->accumulateConstantOffset(DL, Offset);
656
657 char* tmp = (char*) Result.PointerVal;
658 Result = PTOGV(P: tmp + Offset.getSExtValue());
659 return Result;
660 }
661 case Instruction::Trunc: {
662 GenericValue GV = getConstantValue(C: Op0);
663 uint32_t BitWidth = cast<IntegerType>(Val: CE->getType())->getBitWidth();
664 GV.IntVal = GV.IntVal.trunc(width: BitWidth);
665 return GV;
666 }
667 case Instruction::PtrToInt: {
668 GenericValue GV = getConstantValue(C: Op0);
669 uint32_t PtrWidth = DL.getTypeSizeInBits(Ty: Op0->getType());
670 assert(PtrWidth <= 64 && "Bad pointer width");
671 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
672 uint32_t IntWidth = DL.getTypeSizeInBits(Ty: CE->getType());
673 GV.IntVal = GV.IntVal.zextOrTrunc(width: IntWidth);
674 return GV;
675 }
676 case Instruction::IntToPtr: {
677 GenericValue GV = getConstantValue(C: Op0);
678 uint32_t PtrWidth = DL.getTypeSizeInBits(Ty: CE->getType());
679 GV.IntVal = GV.IntVal.zextOrTrunc(width: PtrWidth);
680 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
681 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
682 return GV;
683 }
684 case Instruction::BitCast: {
685 GenericValue GV = getConstantValue(C: Op0);
686 Type* DestTy = CE->getType();
687 switch (Op0->getType()->getTypeID()) {
688 default: llvm_unreachable("Invalid bitcast operand");
689 case Type::IntegerTyID:
690 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
691 if (DestTy->isFloatTy())
692 GV.FloatVal = GV.IntVal.bitsToFloat();
693 else if (DestTy->isDoubleTy())
694 GV.DoubleVal = GV.IntVal.bitsToDouble();
695 break;
696 case Type::FloatTyID:
697 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
698 GV.IntVal = APInt::floatToBits(V: GV.FloatVal);
699 break;
700 case Type::DoubleTyID:
701 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
702 GV.IntVal = APInt::doubleToBits(V: GV.DoubleVal);
703 break;
704 case Type::PointerTyID:
705 assert(DestTy->isPointerTy() && "Invalid bitcast");
706 break; // getConstantValue(Op0) above already converted it
707 }
708 return GV;
709 }
710 case Instruction::Add:
711 case Instruction::Sub:
712 case Instruction::Xor: {
713 assert(Op0->getType()->isIntegerTy() && "Bad binop type!");
714 GenericValue LHS = getConstantValue(C: Op0);
715 GenericValue RHS = getConstantValue(C: CE->getOperand(i_nocapture: 1));
716 GenericValue GV;
717 switch (CE->getOpcode()) {
718 default: llvm_unreachable("Invalid integer opcode");
719 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
720 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
721 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
722 }
723 return GV;
724 }
725 default:
726 break;
727 }
728
729 SmallString<256> Msg;
730 raw_svector_ostream OS(Msg);
731 OS << "ConstantExpr not handled: " << *CE;
732 report_fatal_error(reason: OS.str());
733 }
734
735 if (auto *TETy = dyn_cast<TargetExtType>(Val: C->getType())) {
736 assert(TETy->hasProperty(TargetExtType::HasZeroInit) && C->isNullValue() &&
737 "TargetExtType only supports null constant value");
738 C = Constant::getNullValue(Ty: TETy->getLayoutType());
739 }
740
741 // Otherwise, we have a simple constant.
742 GenericValue Result;
743 switch (C->getType()->getTypeID()) {
744 case Type::FloatTyID:
745 Result.FloatVal = cast<ConstantFP>(Val: C)->getValueAPF().convertToFloat();
746 break;
747 case Type::DoubleTyID:
748 Result.DoubleVal = cast<ConstantFP>(Val: C)->getValueAPF().convertToDouble();
749 break;
750 case Type::X86_FP80TyID:
751 case Type::FP128TyID:
752 case Type::PPC_FP128TyID:
753 Result.IntVal = cast <ConstantFP>(Val: C)->getValueAPF().bitcastToAPInt();
754 break;
755 case Type::IntegerTyID:
756 Result.IntVal = cast<ConstantInt>(Val: C)->getValue();
757 break;
758 case Type::PointerTyID:
759 while (auto *A = dyn_cast<GlobalAlias>(Val: C)) {
760 C = A->getAliasee();
761 }
762 if (isa<ConstantPointerNull>(Val: C))
763 Result.PointerVal = nullptr;
764 else if (const Function *F = dyn_cast<Function>(Val: C))
765 Result = PTOGV(P: getPointerToFunctionOrStub(F: const_cast<Function*>(F)));
766 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: C))
767 Result = PTOGV(P: getOrEmitGlobalVariable(GV: const_cast<GlobalVariable*>(GV)));
768 else
769 llvm_unreachable("Unknown constant pointer type!");
770 break;
771 case Type::ScalableVectorTyID:
772 report_fatal_error(
773 reason: "Scalable vector support not yet implemented in ExecutionEngine");
774 case Type::FixedVectorTyID: {
775 Type *ElemTy = cast<FixedVectorType>(Val: C->getType())->getElementType();
776 if (!ElemTy->isIntegerTy() && !ElemTy->isFloatTy() && !ElemTy->isDoubleTy())
777 llvm_unreachable("Unknown constant pointer type!");
778
779 unsigned ElemNum = cast<FixedVectorType>(Val: C->getType())->getNumElements();
780 Result.AggregateVal.resize(new_size: ElemNum);
781 for (unsigned I = 0; I < ElemNum; ++I) {
782 Constant *Elt = C->getAggregateElement(Elt: I);
783 if (!Elt)
784 llvm_unreachable("Failed to extract element from constant vector!");
785
786 if (auto *CI = dyn_cast<ConstantInt>(Val: Elt))
787 Result.AggregateVal[I].IntVal = CI->getValue();
788 else if (auto *CFP = dyn_cast<ConstantFP>(Val: Elt)) {
789 APFloat Val = CFP->getValueAPF();
790 if (ElemTy->isFloatTy())
791 Result.AggregateVal[I].FloatVal = Val.convertToFloat();
792 else
793 Result.AggregateVal[I].DoubleVal = Val.convertToDouble();
794 } else if (isa<UndefValue>(Val: Elt)) {
795 if (ElemTy->isIntegerTy())
796 Result.AggregateVal[I].IntVal =
797 APInt(ElemTy->getScalarSizeInBits(), 0ull);
798 } else
799 llvm_unreachable("Unknown constant pointer type!");
800 }
801 } break;
802
803 default:
804 SmallString<256> Msg;
805 raw_svector_ostream OS(Msg);
806 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
807 report_fatal_error(reason: OS.str());
808 }
809
810 return Result;
811}
812
813void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
814 GenericValue *Ptr, Type *Ty) {
815 // It is safe to treat TargetExtType as its layout type since the underlying
816 // bits are only copied and are not inspected.
817 if (auto *TETy = dyn_cast<TargetExtType>(Val: Ty))
818 Ty = TETy->getLayoutType();
819
820 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
821
822 switch (Ty->getTypeID()) {
823 default:
824 dbgs() << "Cannot store value of type " << *Ty << "!\n";
825 break;
826 case Type::IntegerTyID:
827 StoreIntToMemory(IntVal: Val.IntVal, Dst: (uint8_t*)Ptr, StoreBytes);
828 break;
829 case Type::FloatTyID:
830 *((float*)Ptr) = Val.FloatVal;
831 break;
832 case Type::DoubleTyID:
833 *((double*)Ptr) = Val.DoubleVal;
834 break;
835 case Type::X86_FP80TyID:
836 memcpy(dest: static_cast<void *>(Ptr), src: Val.IntVal.getRawData(), n: 10);
837 break;
838 case Type::PointerTyID:
839 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
840 if (StoreBytes != sizeof(PointerTy))
841 memset(s: &(Ptr->PointerVal), c: 0, n: StoreBytes);
842
843 *((PointerTy*)Ptr) = Val.PointerVal;
844 break;
845 case Type::FixedVectorTyID:
846 case Type::ScalableVectorTyID:
847 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
848 if (cast<VectorType>(Val: Ty)->getElementType()->isDoubleTy())
849 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
850 if (cast<VectorType>(Val: Ty)->getElementType()->isFloatTy())
851 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
852 if (cast<VectorType>(Val: Ty)->getElementType()->isIntegerTy()) {
853 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
854 StoreIntToMemory(IntVal: Val.AggregateVal[i].IntVal,
855 Dst: (uint8_t*)Ptr + numOfBytes*i, StoreBytes: numOfBytes);
856 }
857 }
858 break;
859 }
860
861 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
862 // Host and target are different endian - reverse the stored bytes.
863 std::reverse(first: (uint8_t*)Ptr, last: StoreBytes + (uint8_t*)Ptr);
864}
865
866/// FIXME: document
867///
868void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
869 GenericValue *Ptr,
870 Type *Ty) {
871 if (auto *TETy = dyn_cast<TargetExtType>(Val: Ty))
872 Ty = TETy->getLayoutType();
873
874 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
875
876 switch (Ty->getTypeID()) {
877 case Type::IntegerTyID:
878 // An APInt with all words initially zero.
879 Result.IntVal = APInt(cast<IntegerType>(Val: Ty)->getBitWidth(), 0);
880 LoadIntFromMemory(IntVal&: Result.IntVal, Src: (uint8_t*)Ptr, LoadBytes);
881 break;
882 case Type::FloatTyID:
883 Result.FloatVal = *((float*)Ptr);
884 break;
885 case Type::DoubleTyID:
886 Result.DoubleVal = *((double*)Ptr);
887 break;
888 case Type::PointerTyID:
889 Result.PointerVal = *((PointerTy*)Ptr);
890 break;
891 case Type::X86_FP80TyID: {
892 // This is endian dependent, but it will only work on x86 anyway.
893 // FIXME: Will not trap if loading a signaling NaN.
894 uint64_t y[2];
895 memcpy(dest: y, src: Ptr, n: 10);
896 Result.IntVal = APInt(80, y);
897 break;
898 }
899 case Type::ScalableVectorTyID:
900 report_fatal_error(
901 reason: "Scalable vector support not yet implemented in ExecutionEngine");
902 case Type::FixedVectorTyID: {
903 auto *VT = cast<FixedVectorType>(Val: Ty);
904 Type *ElemT = VT->getElementType();
905 const unsigned numElems = VT->getNumElements();
906 if (ElemT->isFloatTy()) {
907 Result.AggregateVal.resize(new_size: numElems);
908 for (unsigned i = 0; i < numElems; ++i)
909 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
910 }
911 if (ElemT->isDoubleTy()) {
912 Result.AggregateVal.resize(new_size: numElems);
913 for (unsigned i = 0; i < numElems; ++i)
914 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
915 }
916 if (ElemT->isIntegerTy()) {
917 GenericValue intZero;
918 const unsigned elemBitWidth = cast<IntegerType>(Val: ElemT)->getBitWidth();
919 intZero.IntVal = APInt(elemBitWidth, 0);
920 Result.AggregateVal.resize(new_size: numElems, x: intZero);
921 for (unsigned i = 0; i < numElems; ++i)
922 LoadIntFromMemory(IntVal&: Result.AggregateVal[i].IntVal,
923 Src: (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, LoadBytes: (elemBitWidth+7)/8);
924 }
925 break;
926 }
927 default:
928 SmallString<256> Msg;
929 raw_svector_ostream OS(Msg);
930 OS << "Cannot load value of type " << *Ty << "!";
931 report_fatal_error(reason: OS.str());
932 }
933}
934
935void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
936 LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
937 LLVM_DEBUG(Init->dump());
938 if (isa<UndefValue>(Val: Init))
939 return;
940
941 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Val: Init)) {
942 unsigned ElementSize =
943 getDataLayout().getTypeAllocSize(Ty: CP->getType()->getElementType());
944 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
945 InitializeMemory(Init: CP->getOperand(i_nocapture: i), Addr: (char*)Addr+i*ElementSize);
946 return;
947 }
948
949 if (isa<ConstantAggregateZero>(Val: Init)) {
950 memset(s: Addr, c: 0, n: (size_t)getDataLayout().getTypeAllocSize(Ty: Init->getType()));
951 return;
952 }
953
954 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Val: Init)) {
955 unsigned ElementSize =
956 getDataLayout().getTypeAllocSize(Ty: CPA->getType()->getElementType());
957 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
958 InitializeMemory(Init: CPA->getOperand(i_nocapture: i), Addr: (char*)Addr+i*ElementSize);
959 return;
960 }
961
962 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Val: Init)) {
963 const StructLayout *SL =
964 getDataLayout().getStructLayout(Ty: cast<StructType>(Val: CPS->getType()));
965 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
966 InitializeMemory(Init: CPS->getOperand(i_nocapture: i), Addr: (char*)Addr+SL->getElementOffset(Idx: i));
967 return;
968 }
969
970 if (const ConstantDataSequential *CDS =
971 dyn_cast<ConstantDataSequential>(Val: Init)) {
972 // CDS is already laid out in host memory order.
973 StringRef Data = CDS->getRawDataValues();
974 memcpy(dest: Addr, src: Data.data(), n: Data.size());
975 return;
976 }
977
978 if (Init->getType()->isFirstClassType()) {
979 GenericValue Val = getConstantValue(C: Init);
980 StoreValueToMemory(Val, Ptr: (GenericValue*)Addr, Ty: Init->getType());
981 return;
982 }
983
984 LLVM_DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
985 llvm_unreachable("Unknown constant type to initialize memory with!");
986}
987
988/// EmitGlobals - Emit all of the global variables to memory, storing their
989/// addresses into GlobalAddress. This must make sure to copy the contents of
990/// their initializers into the memory.
991void ExecutionEngine::emitGlobals() {
992 // Loop over all of the global variables in the program, allocating the memory
993 // to hold them. If there is more than one module, do a prepass over globals
994 // to figure out how the different modules should link together.
995 std::map<std::pair<std::string, Type*>,
996 const GlobalValue*> LinkedGlobalsMap;
997
998 if (Modules.size() != 1) {
999 for (const auto &M : Modules) {
1000 for (const auto &GV : M->globals()) {
1001 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1002 GV.hasAppendingLinkage() || !GV.hasName())
1003 continue;// Ignore external globals and globals with internal linkage.
1004
1005 const GlobalValue *&GVEntry = LinkedGlobalsMap[std::make_pair(
1006 x: std::string(GV.getName()), y: GV.getType())];
1007
1008 // If this is the first time we've seen this global, it is the canonical
1009 // version.
1010 if (!GVEntry) {
1011 GVEntry = &GV;
1012 continue;
1013 }
1014
1015 // If the existing global is strong, never replace it.
1016 if (GVEntry->hasExternalLinkage())
1017 continue;
1018
1019 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1020 // symbol. FIXME is this right for common?
1021 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1022 GVEntry = &GV;
1023 }
1024 }
1025 }
1026
1027 std::vector<const GlobalValue*> NonCanonicalGlobals;
1028 for (const auto &M : Modules) {
1029 for (const auto &GV : M->globals()) {
1030 // In the multi-module case, see what this global maps to.
1031 if (!LinkedGlobalsMap.empty()) {
1032 if (const GlobalValue *GVEntry = LinkedGlobalsMap[std::make_pair(
1033 x: std::string(GV.getName()), y: GV.getType())]) {
1034 // If something else is the canonical global, ignore this one.
1035 if (GVEntry != &GV) {
1036 NonCanonicalGlobals.push_back(x: &GV);
1037 continue;
1038 }
1039 }
1040 }
1041
1042 if (!GV.isDeclaration()) {
1043 addGlobalMapping(GV: &GV, Addr: getMemoryForGV(GV: &GV));
1044 } else {
1045 // External variable reference. Try to use the dynamic loader to
1046 // get a pointer to it.
1047 if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
1048 symbolName: std::string(GV.getName())))
1049 addGlobalMapping(GV: &GV, Addr: SymAddr);
1050 else {
1051 report_fatal_error(reason: "Could not resolve external global address: "
1052 +GV.getName());
1053 }
1054 }
1055 }
1056
1057 // If there are multiple modules, map the non-canonical globals to their
1058 // canonical location.
1059 if (!NonCanonicalGlobals.empty()) {
1060 for (const GlobalValue *GV : NonCanonicalGlobals) {
1061 const GlobalValue *CGV = LinkedGlobalsMap[std::make_pair(
1062 x: std::string(GV->getName()), y: GV->getType())];
1063 void *Ptr = getPointerToGlobalIfAvailable(GV: CGV);
1064 assert(Ptr && "Canonical global wasn't codegen'd!");
1065 addGlobalMapping(GV, Addr: Ptr);
1066 }
1067 }
1068
1069 // Now that all of the globals are set up in memory, loop through them all
1070 // and initialize their contents.
1071 for (const auto &GV : M->globals()) {
1072 if (!GV.isDeclaration()) {
1073 if (!LinkedGlobalsMap.empty()) {
1074 if (const GlobalValue *GVEntry = LinkedGlobalsMap[std::make_pair(
1075 x: std::string(GV.getName()), y: GV.getType())])
1076 if (GVEntry != &GV) // Not the canonical variable.
1077 continue;
1078 }
1079 emitGlobalVariable(GV: &GV);
1080 }
1081 }
1082 }
1083}
1084
1085// EmitGlobalVariable - This method emits the specified global variable to the
1086// address specified in GlobalAddresses, or allocates new memory if it's not
1087// already in the map.
1088void ExecutionEngine::emitGlobalVariable(const GlobalVariable *GV) {
1089 void *GA = getPointerToGlobalIfAvailable(GV);
1090
1091 if (!GA) {
1092 // If it's not already specified, allocate memory for the global.
1093 GA = getMemoryForGV(GV);
1094
1095 // If we failed to allocate memory for this global, return.
1096 if (!GA) return;
1097
1098 addGlobalMapping(GV, Addr: GA);
1099 }
1100
1101 // Don't initialize if it's thread local, let the client do it.
1102 if (!GV->isThreadLocal())
1103 InitializeMemory(Init: GV->getInitializer(), Addr: GA);
1104
1105 Type *ElTy = GV->getValueType();
1106 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(Ty: ElTy);
1107 NumInitBytes += (unsigned)GVSize;
1108 ++NumGlobals;
1109}
1110