1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines the common interface used by the various execution engine
12 // FIXME: This file needs to be updated to support scalable vectors
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ExecutionEngine/ExecutionEngine.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ExecutionEngine/GenericValue.h"
21 #include "llvm/ExecutionEngine/JITEventListener.h"
22 #include "llvm/ExecutionEngine/ObjectCache.h"
23 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/MC/TargetRegistry.h"
32 #include "llvm/Object/Archive.h"
33 #include "llvm/Object/ObjectFile.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/DynamicLibrary.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/TargetParser/Host.h"
45 #define DEBUG_TYPE "jit"
47 STATISTIC(NumInitBytes
, "Number of bytes of global vars initialized");
48 STATISTIC(NumGlobals
, "Number of global vars initialized");
50 ExecutionEngine
*(*ExecutionEngine::MCJITCtor
)(
51 std::unique_ptr
<Module
> M
, std::string
*ErrorStr
,
52 std::shared_ptr
<MCJITMemoryManager
> MemMgr
,
53 std::shared_ptr
<LegacyJITSymbolResolver
> Resolver
,
54 std::unique_ptr
<TargetMachine
> TM
) = nullptr;
56 ExecutionEngine
*(*ExecutionEngine::InterpCtor
)(std::unique_ptr
<Module
> M
,
57 std::string
*ErrorStr
) =nullptr;
59 void JITEventListener::anchor() {}
61 void ObjectCache::anchor() {}
63 void ExecutionEngine::Init(std::unique_ptr
<Module
> M
) {
64 CompilingLazily
= false;
65 GVCompilationDisabled
= false;
66 SymbolSearchingDisabled
= false;
68 // IR module verification is enabled by default in debug builds, and disabled
69 // by default in release builds.
73 VerifyModules
= false;
76 assert(M
&& "Module is null?");
77 Modules
.push_back(std::move(M
));
80 ExecutionEngine::ExecutionEngine(std::unique_ptr
<Module
> M
)
81 : DL(M
->getDataLayout()), LazyFunctionCreator(nullptr) {
85 ExecutionEngine::ExecutionEngine(DataLayout DL
, std::unique_ptr
<Module
> M
)
86 : DL(std::move(DL
)), LazyFunctionCreator(nullptr) {
90 ExecutionEngine::~ExecutionEngine() {
91 clearAllGlobalMappings();
95 /// Helper class which uses a value handler to automatically deletes the
96 /// memory block when the GlobalVariable is destroyed.
97 class GVMemoryBlock final
: public CallbackVH
{
98 GVMemoryBlock(const GlobalVariable
*GV
)
99 : CallbackVH(const_cast<GlobalVariable
*>(GV
)) {}
102 /// Returns the address the GlobalVariable should be written into. The
103 /// GVMemoryBlock object prefixes that.
104 static char *Create(const GlobalVariable
*GV
, const DataLayout
& TD
) {
105 Type
*ElTy
= GV
->getValueType();
106 size_t GVSize
= (size_t)TD
.getTypeAllocSize(ElTy
);
107 void *RawMemory
= ::operator new(
108 alignTo(sizeof(GVMemoryBlock
), TD
.getPreferredAlign(GV
)) + GVSize
);
109 new(RawMemory
) GVMemoryBlock(GV
);
110 return static_cast<char*>(RawMemory
) + sizeof(GVMemoryBlock
);
113 void deleted() override
{
114 // We allocated with operator new and with some extra memory hanging off the
115 // end, so don't just delete this. I'm not sure if this is actually
117 this->~GVMemoryBlock();
118 ::operator delete(this);
121 } // anonymous namespace
123 char *ExecutionEngine::getMemoryForGV(const GlobalVariable
*GV
) {
124 return GVMemoryBlock::Create(GV
, getDataLayout());
127 void ExecutionEngine::addObjectFile(std::unique_ptr
<object::ObjectFile
> O
) {
128 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
132 ExecutionEngine::addObjectFile(object::OwningBinary
<object::ObjectFile
> O
) {
133 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
136 void ExecutionEngine::addArchive(object::OwningBinary
<object::Archive
> A
) {
137 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
140 bool ExecutionEngine::removeModule(Module
*M
) {
141 for (auto I
= Modules
.begin(), E
= Modules
.end(); I
!= E
; ++I
) {
142 Module
*Found
= I
->get();
146 clearGlobalMappingsFromModule(M
);
153 Function
*ExecutionEngine::FindFunctionNamed(StringRef FnName
) {
154 for (unsigned i
= 0, e
= Modules
.size(); i
!= e
; ++i
) {
155 Function
*F
= Modules
[i
]->getFunction(FnName
);
156 if (F
&& !F
->isDeclaration())
162 GlobalVariable
*ExecutionEngine::FindGlobalVariableNamed(StringRef Name
, bool AllowInternal
) {
163 for (unsigned i
= 0, e
= Modules
.size(); i
!= e
; ++i
) {
164 GlobalVariable
*GV
= Modules
[i
]->getGlobalVariable(Name
,AllowInternal
);
165 if (GV
&& !GV
->isDeclaration())
171 uint64_t ExecutionEngineState::RemoveMapping(StringRef Name
) {
172 GlobalAddressMapTy::iterator I
= GlobalAddressMap
.find(Name
);
175 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
177 if (I
== GlobalAddressMap
.end())
180 GlobalAddressReverseMap
.erase(I
->second
);
182 GlobalAddressMap
.erase(I
);
188 std::string
ExecutionEngine::getMangledName(const GlobalValue
*GV
) {
189 assert(GV
->hasName() && "Global must have name.");
191 std::lock_guard
<sys::Mutex
> locked(lock
);
192 SmallString
<128> FullName
;
194 const DataLayout
&DL
=
195 GV
->getParent()->getDataLayout().isDefault()
197 : GV
->getParent()->getDataLayout();
199 Mangler::getNameWithPrefix(FullName
, GV
->getName(), DL
);
200 return std::string(FullName
);
203 void ExecutionEngine::addGlobalMapping(const GlobalValue
*GV
, void *Addr
) {
204 std::lock_guard
<sys::Mutex
> locked(lock
);
205 addGlobalMapping(getMangledName(GV
), (uint64_t) Addr
);
208 void ExecutionEngine::addGlobalMapping(StringRef Name
, uint64_t Addr
) {
209 std::lock_guard
<sys::Mutex
> locked(lock
);
211 assert(!Name
.empty() && "Empty GlobalMapping symbol name!");
213 LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name
<< "\' to [" << Addr
<< "]\n";);
214 uint64_t &CurVal
= EEState
.getGlobalAddressMap()[Name
];
215 assert((!CurVal
|| !Addr
) && "GlobalMapping already established!");
218 // If we are using the reverse mapping, add it too.
219 if (!EEState
.getGlobalAddressReverseMap().empty()) {
220 std::string
&V
= EEState
.getGlobalAddressReverseMap()[CurVal
];
221 assert((!V
.empty() || !Name
.empty()) &&
222 "GlobalMapping already established!");
223 V
= std::string(Name
);
227 void ExecutionEngine::clearAllGlobalMappings() {
228 std::lock_guard
<sys::Mutex
> locked(lock
);
230 EEState
.getGlobalAddressMap().clear();
231 EEState
.getGlobalAddressReverseMap().clear();
234 void ExecutionEngine::clearGlobalMappingsFromModule(Module
*M
) {
235 std::lock_guard
<sys::Mutex
> locked(lock
);
237 for (GlobalObject
&GO
: M
->global_objects())
238 EEState
.RemoveMapping(getMangledName(&GO
));
241 uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue
*GV
,
243 std::lock_guard
<sys::Mutex
> locked(lock
);
244 return updateGlobalMapping(getMangledName(GV
), (uint64_t) Addr
);
247 uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name
, uint64_t Addr
) {
248 std::lock_guard
<sys::Mutex
> locked(lock
);
250 ExecutionEngineState::GlobalAddressMapTy
&Map
=
251 EEState
.getGlobalAddressMap();
253 // Deleting from the mapping?
255 return EEState
.RemoveMapping(Name
);
257 uint64_t &CurVal
= Map
[Name
];
258 uint64_t OldVal
= CurVal
;
260 if (CurVal
&& !EEState
.getGlobalAddressReverseMap().empty())
261 EEState
.getGlobalAddressReverseMap().erase(CurVal
);
264 // If we are using the reverse mapping, add it too.
265 if (!EEState
.getGlobalAddressReverseMap().empty()) {
266 std::string
&V
= EEState
.getGlobalAddressReverseMap()[CurVal
];
267 assert((!V
.empty() || !Name
.empty()) &&
268 "GlobalMapping already established!");
269 V
= std::string(Name
);
274 uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S
) {
275 std::lock_guard
<sys::Mutex
> locked(lock
);
276 uint64_t Address
= 0;
277 ExecutionEngineState::GlobalAddressMapTy::iterator I
=
278 EEState
.getGlobalAddressMap().find(S
);
279 if (I
!= EEState
.getGlobalAddressMap().end())
285 void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S
) {
286 std::lock_guard
<sys::Mutex
> locked(lock
);
287 if (void* Address
= (void *) getAddressToGlobalIfAvailable(S
))
292 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue
*GV
) {
293 std::lock_guard
<sys::Mutex
> locked(lock
);
294 return getPointerToGlobalIfAvailable(getMangledName(GV
));
297 const GlobalValue
*ExecutionEngine::getGlobalValueAtAddress(void *Addr
) {
298 std::lock_guard
<sys::Mutex
> locked(lock
);
300 // If we haven't computed the reverse mapping yet, do so first.
301 if (EEState
.getGlobalAddressReverseMap().empty()) {
302 for (ExecutionEngineState::GlobalAddressMapTy::iterator
303 I
= EEState
.getGlobalAddressMap().begin(),
304 E
= EEState
.getGlobalAddressMap().end(); I
!= E
; ++I
) {
305 StringRef Name
= I
->first();
306 uint64_t Addr
= I
->second
;
307 EEState
.getGlobalAddressReverseMap().insert(
308 std::make_pair(Addr
, std::string(Name
)));
312 std::map
<uint64_t, std::string
>::iterator I
=
313 EEState
.getGlobalAddressReverseMap().find((uint64_t) Addr
);
315 if (I
!= EEState
.getGlobalAddressReverseMap().end()) {
316 StringRef Name
= I
->second
;
317 for (unsigned i
= 0, e
= Modules
.size(); i
!= e
; ++i
)
318 if (GlobalValue
*GV
= Modules
[i
]->getNamedValue(Name
))
326 std::unique_ptr
<char[]> Array
;
327 std::vector
<std::unique_ptr
<char[]>> Values
;
329 /// Turn a vector of strings into a nice argv style array of pointers to null
330 /// terminated strings.
331 void *reset(LLVMContext
&C
, ExecutionEngine
*EE
,
332 const std::vector
<std::string
> &InputArgv
);
334 } // anonymous namespace
335 void *ArgvArray::reset(LLVMContext
&C
, ExecutionEngine
*EE
,
336 const std::vector
<std::string
> &InputArgv
) {
337 Values
.clear(); // Free the old contents.
338 Values
.reserve(InputArgv
.size());
339 unsigned PtrSize
= EE
->getDataLayout().getPointerSize();
340 Array
= std::make_unique
<char[]>((InputArgv
.size()+1)*PtrSize
);
342 LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array
.get() << "\n");
343 Type
*SBytePtr
= PointerType::getUnqual(C
);
345 for (unsigned i
= 0; i
!= InputArgv
.size(); ++i
) {
346 unsigned Size
= InputArgv
[i
].size()+1;
347 auto Dest
= std::make_unique
<char[]>(Size
);
348 LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i
<< "] = " << (void *)Dest
.get()
351 std::copy(InputArgv
[i
].begin(), InputArgv
[i
].end(), Dest
.get());
354 // Endian safe: Array[i] = (PointerTy)Dest;
355 EE
->StoreValueToMemory(PTOGV(Dest
.get()),
356 (GenericValue
*)(&Array
[i
*PtrSize
]), SBytePtr
);
357 Values
.push_back(std::move(Dest
));
361 EE
->StoreValueToMemory(PTOGV(nullptr),
362 (GenericValue
*)(&Array
[InputArgv
.size()*PtrSize
]),
367 void ExecutionEngine::runStaticConstructorsDestructors(Module
&module
,
369 StringRef
Name(isDtors
? "llvm.global_dtors" : "llvm.global_ctors");
370 GlobalVariable
*GV
= module
.getNamedGlobal(Name
);
372 // If this global has internal linkage, or if it has a use, then it must be
373 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
374 // this is the case, don't execute any of the global ctors, __main will do
376 if (!GV
|| GV
->isDeclaration() || GV
->hasLocalLinkage()) return;
378 // Should be an array of '{ i32, void ()* }' structs. The first value is
379 // the init priority, which we ignore.
380 ConstantArray
*InitList
= dyn_cast
<ConstantArray
>(GV
->getInitializer());
383 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
384 ConstantStruct
*CS
= dyn_cast
<ConstantStruct
>(InitList
->getOperand(i
));
387 Constant
*FP
= CS
->getOperand(1);
388 if (FP
->isNullValue())
389 continue; // Found a sentinel value, ignore.
391 // Strip off constant expression casts.
392 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(FP
))
394 FP
= CE
->getOperand(0);
396 // Execute the ctor/dtor function!
397 if (Function
*F
= dyn_cast
<Function
>(FP
))
398 runFunction(F
, std::nullopt
);
400 // FIXME: It is marginally lame that we just do nothing here if we see an
401 // entry we don't recognize. It might not be unreasonable for the verifier
402 // to not even allow this and just assert here.
406 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors
) {
407 // Execute global ctors/dtors for each module in the program.
408 for (std::unique_ptr
<Module
> &M
: Modules
)
409 runStaticConstructorsDestructors(*M
, isDtors
);
413 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
414 static bool isTargetNullPtr(ExecutionEngine
*EE
, void *Loc
) {
415 unsigned PtrSize
= EE
->getDataLayout().getPointerSize();
416 for (unsigned i
= 0; i
< PtrSize
; ++i
)
417 if (*(i
+ (uint8_t*)Loc
))
423 int ExecutionEngine::runFunctionAsMain(Function
*Fn
,
424 const std::vector
<std::string
> &argv
,
425 const char * const * envp
) {
426 std::vector
<GenericValue
> GVArgs
;
428 GVArgc
.IntVal
= APInt(32, argv
.size());
431 unsigned NumArgs
= Fn
->getFunctionType()->getNumParams();
432 FunctionType
*FTy
= Fn
->getFunctionType();
433 Type
*PPInt8Ty
= PointerType::get(Fn
->getContext(), 0);
435 // Check the argument types.
437 report_fatal_error("Invalid number of arguments of main() supplied");
438 if (NumArgs
>= 3 && FTy
->getParamType(2) != PPInt8Ty
)
439 report_fatal_error("Invalid type for third argument of main() supplied");
440 if (NumArgs
>= 2 && FTy
->getParamType(1) != PPInt8Ty
)
441 report_fatal_error("Invalid type for second argument of main() supplied");
442 if (NumArgs
>= 1 && !FTy
->getParamType(0)->isIntegerTy(32))
443 report_fatal_error("Invalid type for first argument of main() supplied");
444 if (!FTy
->getReturnType()->isIntegerTy() &&
445 !FTy
->getReturnType()->isVoidTy())
446 report_fatal_error("Invalid return type of main() supplied");
451 GVArgs
.push_back(GVArgc
); // Arg #0 = argc.
454 GVArgs
.push_back(PTOGV(CArgv
.reset(Fn
->getContext(), this, argv
)));
455 assert(!isTargetNullPtr(this, GVTOP(GVArgs
[1])) &&
456 "argv[0] was null after CreateArgv");
458 std::vector
<std::string
> EnvVars
;
459 for (unsigned i
= 0; envp
[i
]; ++i
)
460 EnvVars
.emplace_back(envp
[i
]);
462 GVArgs
.push_back(PTOGV(CEnv
.reset(Fn
->getContext(), this, EnvVars
)));
467 return runFunction(Fn
, GVArgs
).IntVal
.getZExtValue();
470 EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
472 EngineBuilder::EngineBuilder(std::unique_ptr
<Module
> M
)
473 : M(std::move(M
)), WhichEngine(EngineKind::Either
), ErrorStr(nullptr),
474 OptLevel(CodeGenOptLevel::Default
), MemMgr(nullptr), Resolver(nullptr) {
475 // IR module verification is enabled by default in debug builds, and disabled
476 // by default in release builds.
478 VerifyModules
= true;
480 VerifyModules
= false;
484 EngineBuilder::~EngineBuilder() = default;
486 EngineBuilder
&EngineBuilder::setMCJITMemoryManager(
487 std::unique_ptr
<RTDyldMemoryManager
> mcjmm
) {
488 auto SharedMM
= std::shared_ptr
<RTDyldMemoryManager
>(std::move(mcjmm
));
495 EngineBuilder::setMemoryManager(std::unique_ptr
<MCJITMemoryManager
> MM
) {
496 MemMgr
= std::shared_ptr
<MCJITMemoryManager
>(std::move(MM
));
501 EngineBuilder::setSymbolResolver(std::unique_ptr
<LegacyJITSymbolResolver
> SR
) {
502 Resolver
= std::shared_ptr
<LegacyJITSymbolResolver
>(std::move(SR
));
506 ExecutionEngine
*EngineBuilder::create(TargetMachine
*TM
) {
507 std::unique_ptr
<TargetMachine
> TheTM(TM
); // Take ownership.
509 // Make sure we can resolve symbols in the program as well. The zero arg
510 // to the function tells DynamicLibrary to load the program, not a library.
511 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr
))
514 // If the user specified a memory manager but didn't specify which engine to
515 // create, we assume they only want the JIT, and we fail if they only want
518 if (WhichEngine
& EngineKind::JIT
)
519 WhichEngine
= EngineKind::JIT
;
522 *ErrorStr
= "Cannot create an interpreter with a memory manager.";
527 // Unless the interpreter was explicitly selected or the JIT is not linked,
529 if ((WhichEngine
& EngineKind::JIT
) && TheTM
) {
530 if (!TM
->getTarget().hasJIT()) {
531 errs() << "WARNING: This target JIT is not designed for the host"
532 << " you are running. If bad things happen, please choose"
533 << " a different -march switch.\n";
536 ExecutionEngine
*EE
= nullptr;
537 if (ExecutionEngine::MCJITCtor
)
538 EE
= ExecutionEngine::MCJITCtor(std::move(M
), ErrorStr
, std::move(MemMgr
),
539 std::move(Resolver
), std::move(TheTM
));
542 EE
->setVerifyModules(VerifyModules
);
547 // If we can't make a JIT and we didn't request one specifically, try making
548 // an interpreter instead.
549 if (WhichEngine
& EngineKind::Interpreter
) {
550 if (ExecutionEngine::InterpCtor
)
551 return ExecutionEngine::InterpCtor(std::move(M
), ErrorStr
);
553 *ErrorStr
= "Interpreter has not been linked in.";
557 if ((WhichEngine
& EngineKind::JIT
) && !ExecutionEngine::MCJITCtor
) {
559 *ErrorStr
= "JIT has not been linked in.";
565 void *ExecutionEngine::getPointerToGlobal(const GlobalValue
*GV
) {
566 if (Function
*F
= const_cast<Function
*>(dyn_cast
<Function
>(GV
)))
567 return getPointerToFunction(F
);
569 std::lock_guard
<sys::Mutex
> locked(lock
);
570 if (void* P
= getPointerToGlobalIfAvailable(GV
))
573 // Global variable might have been added since interpreter started.
574 if (GlobalVariable
*GVar
=
575 const_cast<GlobalVariable
*>(dyn_cast
<GlobalVariable
>(GV
)))
576 emitGlobalVariable(GVar
);
578 llvm_unreachable("Global hasn't had an address allocated yet!");
580 return getPointerToGlobalIfAvailable(GV
);
583 /// Converts a Constant* into a GenericValue, including handling of
584 /// ConstantExpr values.
585 GenericValue
ExecutionEngine::getConstantValue(const Constant
*C
) {
586 // If its undefined, return the garbage.
587 if (isa
<UndefValue
>(C
)) {
589 switch (C
->getType()->getTypeID()) {
592 case Type::IntegerTyID
:
593 case Type::X86_FP80TyID
:
594 case Type::FP128TyID
:
595 case Type::PPC_FP128TyID
:
596 // Although the value is undefined, we still have to construct an APInt
597 // with the correct bit width.
598 Result
.IntVal
= APInt(C
->getType()->getPrimitiveSizeInBits(), 0);
600 case Type::StructTyID
: {
601 // if the whole struct is 'undef' just reserve memory for the value.
602 if(StructType
*STy
= dyn_cast
<StructType
>(C
->getType())) {
603 unsigned int elemNum
= STy
->getNumElements();
604 Result
.AggregateVal
.resize(elemNum
);
605 for (unsigned int i
= 0; i
< elemNum
; ++i
) {
606 Type
*ElemTy
= STy
->getElementType(i
);
607 if (ElemTy
->isIntegerTy())
608 Result
.AggregateVal
[i
].IntVal
=
609 APInt(ElemTy
->getPrimitiveSizeInBits(), 0);
610 else if (ElemTy
->isAggregateType()) {
611 const Constant
*ElemUndef
= UndefValue::get(ElemTy
);
612 Result
.AggregateVal
[i
] = getConstantValue(ElemUndef
);
618 case Type::ScalableVectorTyID
:
620 "Scalable vector support not yet implemented in ExecutionEngine");
621 case Type::ArrayTyID
: {
622 auto *ArrTy
= cast
<ArrayType
>(C
->getType());
623 Type
*ElemTy
= ArrTy
->getElementType();
624 unsigned int elemNum
= ArrTy
->getNumElements();
625 Result
.AggregateVal
.resize(elemNum
);
626 if (ElemTy
->isIntegerTy())
627 for (unsigned int i
= 0; i
< elemNum
; ++i
)
628 Result
.AggregateVal
[i
].IntVal
=
629 APInt(ElemTy
->getPrimitiveSizeInBits(), 0);
632 case Type::FixedVectorTyID
: {
633 // if the whole vector is 'undef' just reserve memory for the value.
634 auto *VTy
= cast
<FixedVectorType
>(C
->getType());
635 Type
*ElemTy
= VTy
->getElementType();
636 unsigned int elemNum
= VTy
->getNumElements();
637 Result
.AggregateVal
.resize(elemNum
);
638 if (ElemTy
->isIntegerTy())
639 for (unsigned int i
= 0; i
< elemNum
; ++i
)
640 Result
.AggregateVal
[i
].IntVal
=
641 APInt(ElemTy
->getPrimitiveSizeInBits(), 0);
648 // Otherwise, if the value is a ConstantExpr...
649 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
650 Constant
*Op0
= CE
->getOperand(0);
651 switch (CE
->getOpcode()) {
652 case Instruction::GetElementPtr
: {
654 GenericValue Result
= getConstantValue(Op0
);
655 APInt
Offset(DL
.getPointerSizeInBits(), 0);
656 cast
<GEPOperator
>(CE
)->accumulateConstantOffset(DL
, Offset
);
658 char* tmp
= (char*) Result
.PointerVal
;
659 Result
= PTOGV(tmp
+ Offset
.getSExtValue());
662 case Instruction::Trunc
: {
663 GenericValue GV
= getConstantValue(Op0
);
664 uint32_t BitWidth
= cast
<IntegerType
>(CE
->getType())->getBitWidth();
665 GV
.IntVal
= GV
.IntVal
.trunc(BitWidth
);
668 case Instruction::ZExt
: {
669 GenericValue GV
= getConstantValue(Op0
);
670 uint32_t BitWidth
= cast
<IntegerType
>(CE
->getType())->getBitWidth();
671 GV
.IntVal
= GV
.IntVal
.zext(BitWidth
);
674 case Instruction::SExt
: {
675 GenericValue GV
= getConstantValue(Op0
);
676 uint32_t BitWidth
= cast
<IntegerType
>(CE
->getType())->getBitWidth();
677 GV
.IntVal
= GV
.IntVal
.sext(BitWidth
);
680 case Instruction::FPTrunc
: {
682 GenericValue GV
= getConstantValue(Op0
);
683 GV
.FloatVal
= float(GV
.DoubleVal
);
686 case Instruction::FPExt
:{
688 GenericValue GV
= getConstantValue(Op0
);
689 GV
.DoubleVal
= double(GV
.FloatVal
);
692 case Instruction::UIToFP
: {
693 GenericValue GV
= getConstantValue(Op0
);
694 if (CE
->getType()->isFloatTy())
695 GV
.FloatVal
= float(GV
.IntVal
.roundToDouble());
696 else if (CE
->getType()->isDoubleTy())
697 GV
.DoubleVal
= GV
.IntVal
.roundToDouble();
698 else if (CE
->getType()->isX86_FP80Ty()) {
699 APFloat apf
= APFloat::getZero(APFloat::x87DoubleExtended());
700 (void)apf
.convertFromAPInt(GV
.IntVal
,
702 APFloat::rmNearestTiesToEven
);
703 GV
.IntVal
= apf
.bitcastToAPInt();
707 case Instruction::SIToFP
: {
708 GenericValue GV
= getConstantValue(Op0
);
709 if (CE
->getType()->isFloatTy())
710 GV
.FloatVal
= float(GV
.IntVal
.signedRoundToDouble());
711 else if (CE
->getType()->isDoubleTy())
712 GV
.DoubleVal
= GV
.IntVal
.signedRoundToDouble();
713 else if (CE
->getType()->isX86_FP80Ty()) {
714 APFloat apf
= APFloat::getZero(APFloat::x87DoubleExtended());
715 (void)apf
.convertFromAPInt(GV
.IntVal
,
717 APFloat::rmNearestTiesToEven
);
718 GV
.IntVal
= apf
.bitcastToAPInt();
722 case Instruction::FPToUI
: // double->APInt conversion handles sign
723 case Instruction::FPToSI
: {
724 GenericValue GV
= getConstantValue(Op0
);
725 uint32_t BitWidth
= cast
<IntegerType
>(CE
->getType())->getBitWidth();
726 if (Op0
->getType()->isFloatTy())
727 GV
.IntVal
= APIntOps::RoundFloatToAPInt(GV
.FloatVal
, BitWidth
);
728 else if (Op0
->getType()->isDoubleTy())
729 GV
.IntVal
= APIntOps::RoundDoubleToAPInt(GV
.DoubleVal
, BitWidth
);
730 else if (Op0
->getType()->isX86_FP80Ty()) {
731 APFloat apf
= APFloat(APFloat::x87DoubleExtended(), GV
.IntVal
);
734 (void)apf
.convertToInteger(MutableArrayRef(v
), BitWidth
,
735 CE
->getOpcode()==Instruction::FPToSI
,
736 APFloat::rmTowardZero
, &ignored
);
737 GV
.IntVal
= v
; // endian?
741 case Instruction::PtrToInt
: {
742 GenericValue GV
= getConstantValue(Op0
);
743 uint32_t PtrWidth
= DL
.getTypeSizeInBits(Op0
->getType());
744 assert(PtrWidth
<= 64 && "Bad pointer width");
745 GV
.IntVal
= APInt(PtrWidth
, uintptr_t(GV
.PointerVal
));
746 uint32_t IntWidth
= DL
.getTypeSizeInBits(CE
->getType());
747 GV
.IntVal
= GV
.IntVal
.zextOrTrunc(IntWidth
);
750 case Instruction::IntToPtr
: {
751 GenericValue GV
= getConstantValue(Op0
);
752 uint32_t PtrWidth
= DL
.getTypeSizeInBits(CE
->getType());
753 GV
.IntVal
= GV
.IntVal
.zextOrTrunc(PtrWidth
);
754 assert(GV
.IntVal
.getBitWidth() <= 64 && "Bad pointer width");
755 GV
.PointerVal
= PointerTy(uintptr_t(GV
.IntVal
.getZExtValue()));
758 case Instruction::BitCast
: {
759 GenericValue GV
= getConstantValue(Op0
);
760 Type
* DestTy
= CE
->getType();
761 switch (Op0
->getType()->getTypeID()) {
762 default: llvm_unreachable("Invalid bitcast operand");
763 case Type::IntegerTyID
:
764 assert(DestTy
->isFloatingPointTy() && "invalid bitcast");
765 if (DestTy
->isFloatTy())
766 GV
.FloatVal
= GV
.IntVal
.bitsToFloat();
767 else if (DestTy
->isDoubleTy())
768 GV
.DoubleVal
= GV
.IntVal
.bitsToDouble();
770 case Type::FloatTyID
:
771 assert(DestTy
->isIntegerTy(32) && "Invalid bitcast");
772 GV
.IntVal
= APInt::floatToBits(GV
.FloatVal
);
774 case Type::DoubleTyID
:
775 assert(DestTy
->isIntegerTy(64) && "Invalid bitcast");
776 GV
.IntVal
= APInt::doubleToBits(GV
.DoubleVal
);
778 case Type::PointerTyID
:
779 assert(DestTy
->isPointerTy() && "Invalid bitcast");
780 break; // getConstantValue(Op0) above already converted it
784 case Instruction::Add
:
785 case Instruction::FAdd
:
786 case Instruction::Sub
:
787 case Instruction::FSub
:
788 case Instruction::Mul
:
789 case Instruction::FMul
:
790 case Instruction::UDiv
:
791 case Instruction::SDiv
:
792 case Instruction::URem
:
793 case Instruction::SRem
:
794 case Instruction::And
:
795 case Instruction::Or
:
796 case Instruction::Xor
: {
797 GenericValue LHS
= getConstantValue(Op0
);
798 GenericValue RHS
= getConstantValue(CE
->getOperand(1));
800 switch (CE
->getOperand(0)->getType()->getTypeID()) {
801 default: llvm_unreachable("Bad add type!");
802 case Type::IntegerTyID
:
803 switch (CE
->getOpcode()) {
804 default: llvm_unreachable("Invalid integer opcode");
805 case Instruction::Add
: GV
.IntVal
= LHS
.IntVal
+ RHS
.IntVal
; break;
806 case Instruction::Sub
: GV
.IntVal
= LHS
.IntVal
- RHS
.IntVal
; break;
807 case Instruction::Mul
: GV
.IntVal
= LHS
.IntVal
* RHS
.IntVal
; break;
808 case Instruction::UDiv
:GV
.IntVal
= LHS
.IntVal
.udiv(RHS
.IntVal
); break;
809 case Instruction::SDiv
:GV
.IntVal
= LHS
.IntVal
.sdiv(RHS
.IntVal
); break;
810 case Instruction::URem
:GV
.IntVal
= LHS
.IntVal
.urem(RHS
.IntVal
); break;
811 case Instruction::SRem
:GV
.IntVal
= LHS
.IntVal
.srem(RHS
.IntVal
); break;
812 case Instruction::And
: GV
.IntVal
= LHS
.IntVal
& RHS
.IntVal
; break;
813 case Instruction::Or
: GV
.IntVal
= LHS
.IntVal
| RHS
.IntVal
; break;
814 case Instruction::Xor
: GV
.IntVal
= LHS
.IntVal
^ RHS
.IntVal
; break;
817 case Type::FloatTyID
:
818 switch (CE
->getOpcode()) {
819 default: llvm_unreachable("Invalid float opcode");
820 case Instruction::FAdd
:
821 GV
.FloatVal
= LHS
.FloatVal
+ RHS
.FloatVal
; break;
822 case Instruction::FSub
:
823 GV
.FloatVal
= LHS
.FloatVal
- RHS
.FloatVal
; break;
824 case Instruction::FMul
:
825 GV
.FloatVal
= LHS
.FloatVal
* RHS
.FloatVal
; break;
826 case Instruction::FDiv
:
827 GV
.FloatVal
= LHS
.FloatVal
/ RHS
.FloatVal
; break;
828 case Instruction::FRem
:
829 GV
.FloatVal
= std::fmod(LHS
.FloatVal
,RHS
.FloatVal
); break;
832 case Type::DoubleTyID
:
833 switch (CE
->getOpcode()) {
834 default: llvm_unreachable("Invalid double opcode");
835 case Instruction::FAdd
:
836 GV
.DoubleVal
= LHS
.DoubleVal
+ RHS
.DoubleVal
; break;
837 case Instruction::FSub
:
838 GV
.DoubleVal
= LHS
.DoubleVal
- RHS
.DoubleVal
; break;
839 case Instruction::FMul
:
840 GV
.DoubleVal
= LHS
.DoubleVal
* RHS
.DoubleVal
; break;
841 case Instruction::FDiv
:
842 GV
.DoubleVal
= LHS
.DoubleVal
/ RHS
.DoubleVal
; break;
843 case Instruction::FRem
:
844 GV
.DoubleVal
= std::fmod(LHS
.DoubleVal
,RHS
.DoubleVal
); break;
847 case Type::X86_FP80TyID
:
848 case Type::PPC_FP128TyID
:
849 case Type::FP128TyID
: {
850 const fltSemantics
&Sem
= CE
->getOperand(0)->getType()->getFltSemantics();
851 APFloat apfLHS
= APFloat(Sem
, LHS
.IntVal
);
852 switch (CE
->getOpcode()) {
853 default: llvm_unreachable("Invalid long double opcode");
854 case Instruction::FAdd
:
855 apfLHS
.add(APFloat(Sem
, RHS
.IntVal
), APFloat::rmNearestTiesToEven
);
856 GV
.IntVal
= apfLHS
.bitcastToAPInt();
858 case Instruction::FSub
:
859 apfLHS
.subtract(APFloat(Sem
, RHS
.IntVal
),
860 APFloat::rmNearestTiesToEven
);
861 GV
.IntVal
= apfLHS
.bitcastToAPInt();
863 case Instruction::FMul
:
864 apfLHS
.multiply(APFloat(Sem
, RHS
.IntVal
),
865 APFloat::rmNearestTiesToEven
);
866 GV
.IntVal
= apfLHS
.bitcastToAPInt();
868 case Instruction::FDiv
:
869 apfLHS
.divide(APFloat(Sem
, RHS
.IntVal
),
870 APFloat::rmNearestTiesToEven
);
871 GV
.IntVal
= apfLHS
.bitcastToAPInt();
873 case Instruction::FRem
:
874 apfLHS
.mod(APFloat(Sem
, RHS
.IntVal
));
875 GV
.IntVal
= apfLHS
.bitcastToAPInt();
887 SmallString
<256> Msg
;
888 raw_svector_ostream
OS(Msg
);
889 OS
<< "ConstantExpr not handled: " << *CE
;
890 report_fatal_error(OS
.str());
893 if (auto *TETy
= dyn_cast
<TargetExtType
>(C
->getType())) {
894 assert(TETy
->hasProperty(TargetExtType::HasZeroInit
) && C
->isNullValue() &&
895 "TargetExtType only supports null constant value");
896 C
= Constant::getNullValue(TETy
->getLayoutType());
899 // Otherwise, we have a simple constant.
901 switch (C
->getType()->getTypeID()) {
902 case Type::FloatTyID
:
903 Result
.FloatVal
= cast
<ConstantFP
>(C
)->getValueAPF().convertToFloat();
905 case Type::DoubleTyID
:
906 Result
.DoubleVal
= cast
<ConstantFP
>(C
)->getValueAPF().convertToDouble();
908 case Type::X86_FP80TyID
:
909 case Type::FP128TyID
:
910 case Type::PPC_FP128TyID
:
911 Result
.IntVal
= cast
<ConstantFP
>(C
)->getValueAPF().bitcastToAPInt();
913 case Type::IntegerTyID
:
914 Result
.IntVal
= cast
<ConstantInt
>(C
)->getValue();
916 case Type::PointerTyID
:
917 while (auto *A
= dyn_cast
<GlobalAlias
>(C
)) {
920 if (isa
<ConstantPointerNull
>(C
))
921 Result
.PointerVal
= nullptr;
922 else if (const Function
*F
= dyn_cast
<Function
>(C
))
923 Result
= PTOGV(getPointerToFunctionOrStub(const_cast<Function
*>(F
)));
924 else if (const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(C
))
925 Result
= PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable
*>(GV
)));
927 llvm_unreachable("Unknown constant pointer type!");
929 case Type::ScalableVectorTyID
:
931 "Scalable vector support not yet implemented in ExecutionEngine");
932 case Type::FixedVectorTyID
: {
935 const ConstantDataVector
*CDV
= dyn_cast
<ConstantDataVector
>(C
);
936 const ConstantVector
*CV
= dyn_cast
<ConstantVector
>(C
);
937 const ConstantAggregateZero
*CAZ
= dyn_cast
<ConstantAggregateZero
>(C
);
940 elemNum
= CDV
->getNumElements();
941 ElemTy
= CDV
->getElementType();
942 } else if (CV
|| CAZ
) {
943 auto *VTy
= cast
<FixedVectorType
>(C
->getType());
944 elemNum
= VTy
->getNumElements();
945 ElemTy
= VTy
->getElementType();
947 llvm_unreachable("Unknown constant vector type!");
950 Result
.AggregateVal
.resize(elemNum
);
951 // Check if vector holds floats.
952 if(ElemTy
->isFloatTy()) {
954 GenericValue floatZero
;
955 floatZero
.FloatVal
= 0.f
;
956 std::fill(Result
.AggregateVal
.begin(), Result
.AggregateVal
.end(),
961 for (unsigned i
= 0; i
< elemNum
; ++i
)
962 if (!isa
<UndefValue
>(CV
->getOperand(i
)))
963 Result
.AggregateVal
[i
].FloatVal
= cast
<ConstantFP
>(
964 CV
->getOperand(i
))->getValueAPF().convertToFloat();
968 for (unsigned i
= 0; i
< elemNum
; ++i
)
969 Result
.AggregateVal
[i
].FloatVal
= CDV
->getElementAsFloat(i
);
973 // Check if vector holds doubles.
974 if (ElemTy
->isDoubleTy()) {
976 GenericValue doubleZero
;
977 doubleZero
.DoubleVal
= 0.0;
978 std::fill(Result
.AggregateVal
.begin(), Result
.AggregateVal
.end(),
983 for (unsigned i
= 0; i
< elemNum
; ++i
)
984 if (!isa
<UndefValue
>(CV
->getOperand(i
)))
985 Result
.AggregateVal
[i
].DoubleVal
= cast
<ConstantFP
>(
986 CV
->getOperand(i
))->getValueAPF().convertToDouble();
990 for (unsigned i
= 0; i
< elemNum
; ++i
)
991 Result
.AggregateVal
[i
].DoubleVal
= CDV
->getElementAsDouble(i
);
995 // Check if vector holds integers.
996 if (ElemTy
->isIntegerTy()) {
998 GenericValue intZero
;
999 intZero
.IntVal
= APInt(ElemTy
->getScalarSizeInBits(), 0ull);
1000 std::fill(Result
.AggregateVal
.begin(), Result
.AggregateVal
.end(),
1005 for (unsigned i
= 0; i
< elemNum
; ++i
)
1006 if (!isa
<UndefValue
>(CV
->getOperand(i
)))
1007 Result
.AggregateVal
[i
].IntVal
= cast
<ConstantInt
>(
1008 CV
->getOperand(i
))->getValue();
1010 Result
.AggregateVal
[i
].IntVal
=
1011 APInt(CV
->getOperand(i
)->getType()->getPrimitiveSizeInBits(), 0);
1016 for (unsigned i
= 0; i
< elemNum
; ++i
)
1017 Result
.AggregateVal
[i
].IntVal
= APInt(
1018 CDV
->getElementType()->getPrimitiveSizeInBits(),
1019 CDV
->getElementAsInteger(i
));
1023 llvm_unreachable("Unknown constant pointer type!");
1027 SmallString
<256> Msg
;
1028 raw_svector_ostream
OS(Msg
);
1029 OS
<< "ERROR: Constant unimplemented for type: " << *C
->getType();
1030 report_fatal_error(OS
.str());
1036 void ExecutionEngine::StoreValueToMemory(const GenericValue
&Val
,
1037 GenericValue
*Ptr
, Type
*Ty
) {
1038 // It is safe to treat TargetExtType as its layout type since the underlying
1039 // bits are only copied and are not inspected.
1040 if (auto *TETy
= dyn_cast
<TargetExtType
>(Ty
))
1041 Ty
= TETy
->getLayoutType();
1043 const unsigned StoreBytes
= getDataLayout().getTypeStoreSize(Ty
);
1045 switch (Ty
->getTypeID()) {
1047 dbgs() << "Cannot store value of type " << *Ty
<< "!\n";
1049 case Type::IntegerTyID
:
1050 StoreIntToMemory(Val
.IntVal
, (uint8_t*)Ptr
, StoreBytes
);
1052 case Type::FloatTyID
:
1053 *((float*)Ptr
) = Val
.FloatVal
;
1055 case Type::DoubleTyID
:
1056 *((double*)Ptr
) = Val
.DoubleVal
;
1058 case Type::X86_FP80TyID
:
1059 memcpy(Ptr
, Val
.IntVal
.getRawData(), 10);
1061 case Type::PointerTyID
:
1062 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1063 if (StoreBytes
!= sizeof(PointerTy
))
1064 memset(&(Ptr
->PointerVal
), 0, StoreBytes
);
1066 *((PointerTy
*)Ptr
) = Val
.PointerVal
;
1068 case Type::FixedVectorTyID
:
1069 case Type::ScalableVectorTyID
:
1070 for (unsigned i
= 0; i
< Val
.AggregateVal
.size(); ++i
) {
1071 if (cast
<VectorType
>(Ty
)->getElementType()->isDoubleTy())
1072 *(((double*)Ptr
)+i
) = Val
.AggregateVal
[i
].DoubleVal
;
1073 if (cast
<VectorType
>(Ty
)->getElementType()->isFloatTy())
1074 *(((float*)Ptr
)+i
) = Val
.AggregateVal
[i
].FloatVal
;
1075 if (cast
<VectorType
>(Ty
)->getElementType()->isIntegerTy()) {
1076 unsigned numOfBytes
=(Val
.AggregateVal
[i
].IntVal
.getBitWidth()+7)/8;
1077 StoreIntToMemory(Val
.AggregateVal
[i
].IntVal
,
1078 (uint8_t*)Ptr
+ numOfBytes
*i
, numOfBytes
);
1084 if (sys::IsLittleEndianHost
!= getDataLayout().isLittleEndian())
1085 // Host and target are different endian - reverse the stored bytes.
1086 std::reverse((uint8_t*)Ptr
, StoreBytes
+ (uint8_t*)Ptr
);
1091 void ExecutionEngine::LoadValueFromMemory(GenericValue
&Result
,
1094 if (auto *TETy
= dyn_cast
<TargetExtType
>(Ty
))
1095 Ty
= TETy
->getLayoutType();
1097 const unsigned LoadBytes
= getDataLayout().getTypeStoreSize(Ty
);
1099 switch (Ty
->getTypeID()) {
1100 case Type::IntegerTyID
:
1101 // An APInt with all words initially zero.
1102 Result
.IntVal
= APInt(cast
<IntegerType
>(Ty
)->getBitWidth(), 0);
1103 LoadIntFromMemory(Result
.IntVal
, (uint8_t*)Ptr
, LoadBytes
);
1105 case Type::FloatTyID
:
1106 Result
.FloatVal
= *((float*)Ptr
);
1108 case Type::DoubleTyID
:
1109 Result
.DoubleVal
= *((double*)Ptr
);
1111 case Type::PointerTyID
:
1112 Result
.PointerVal
= *((PointerTy
*)Ptr
);
1114 case Type::X86_FP80TyID
: {
1115 // This is endian dependent, but it will only work on x86 anyway.
1116 // FIXME: Will not trap if loading a signaling NaN.
1119 Result
.IntVal
= APInt(80, y
);
1122 case Type::ScalableVectorTyID
:
1124 "Scalable vector support not yet implemented in ExecutionEngine");
1125 case Type::FixedVectorTyID
: {
1126 auto *VT
= cast
<FixedVectorType
>(Ty
);
1127 Type
*ElemT
= VT
->getElementType();
1128 const unsigned numElems
= VT
->getNumElements();
1129 if (ElemT
->isFloatTy()) {
1130 Result
.AggregateVal
.resize(numElems
);
1131 for (unsigned i
= 0; i
< numElems
; ++i
)
1132 Result
.AggregateVal
[i
].FloatVal
= *((float*)Ptr
+i
);
1134 if (ElemT
->isDoubleTy()) {
1135 Result
.AggregateVal
.resize(numElems
);
1136 for (unsigned i
= 0; i
< numElems
; ++i
)
1137 Result
.AggregateVal
[i
].DoubleVal
= *((double*)Ptr
+i
);
1139 if (ElemT
->isIntegerTy()) {
1140 GenericValue intZero
;
1141 const unsigned elemBitWidth
= cast
<IntegerType
>(ElemT
)->getBitWidth();
1142 intZero
.IntVal
= APInt(elemBitWidth
, 0);
1143 Result
.AggregateVal
.resize(numElems
, intZero
);
1144 for (unsigned i
= 0; i
< numElems
; ++i
)
1145 LoadIntFromMemory(Result
.AggregateVal
[i
].IntVal
,
1146 (uint8_t*)Ptr
+((elemBitWidth
+7)/8)*i
, (elemBitWidth
+7)/8);
1151 SmallString
<256> Msg
;
1152 raw_svector_ostream
OS(Msg
);
1153 OS
<< "Cannot load value of type " << *Ty
<< "!";
1154 report_fatal_error(OS
.str());
1158 void ExecutionEngine::InitializeMemory(const Constant
*Init
, void *Addr
) {
1159 LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr
<< " ");
1160 LLVM_DEBUG(Init
->dump());
1161 if (isa
<UndefValue
>(Init
))
1164 if (const ConstantVector
*CP
= dyn_cast
<ConstantVector
>(Init
)) {
1165 unsigned ElementSize
=
1166 getDataLayout().getTypeAllocSize(CP
->getType()->getElementType());
1167 for (unsigned i
= 0, e
= CP
->getNumOperands(); i
!= e
; ++i
)
1168 InitializeMemory(CP
->getOperand(i
), (char*)Addr
+i
*ElementSize
);
1172 if (isa
<ConstantAggregateZero
>(Init
)) {
1173 memset(Addr
, 0, (size_t)getDataLayout().getTypeAllocSize(Init
->getType()));
1177 if (const ConstantArray
*CPA
= dyn_cast
<ConstantArray
>(Init
)) {
1178 unsigned ElementSize
=
1179 getDataLayout().getTypeAllocSize(CPA
->getType()->getElementType());
1180 for (unsigned i
= 0, e
= CPA
->getNumOperands(); i
!= e
; ++i
)
1181 InitializeMemory(CPA
->getOperand(i
), (char*)Addr
+i
*ElementSize
);
1185 if (const ConstantStruct
*CPS
= dyn_cast
<ConstantStruct
>(Init
)) {
1186 const StructLayout
*SL
=
1187 getDataLayout().getStructLayout(cast
<StructType
>(CPS
->getType()));
1188 for (unsigned i
= 0, e
= CPS
->getNumOperands(); i
!= e
; ++i
)
1189 InitializeMemory(CPS
->getOperand(i
), (char*)Addr
+SL
->getElementOffset(i
));
1193 if (const ConstantDataSequential
*CDS
=
1194 dyn_cast
<ConstantDataSequential
>(Init
)) {
1195 // CDS is already laid out in host memory order.
1196 StringRef Data
= CDS
->getRawDataValues();
1197 memcpy(Addr
, Data
.data(), Data
.size());
1201 if (Init
->getType()->isFirstClassType()) {
1202 GenericValue Val
= getConstantValue(Init
);
1203 StoreValueToMemory(Val
, (GenericValue
*)Addr
, Init
->getType());
1207 LLVM_DEBUG(dbgs() << "Bad Type: " << *Init
->getType() << "\n");
1208 llvm_unreachable("Unknown constant type to initialize memory with!");
1211 /// EmitGlobals - Emit all of the global variables to memory, storing their
1212 /// addresses into GlobalAddress. This must make sure to copy the contents of
1213 /// their initializers into the memory.
1214 void ExecutionEngine::emitGlobals() {
1215 // Loop over all of the global variables in the program, allocating the memory
1216 // to hold them. If there is more than one module, do a prepass over globals
1217 // to figure out how the different modules should link together.
1218 std::map
<std::pair
<std::string
, Type
*>,
1219 const GlobalValue
*> LinkedGlobalsMap
;
1221 if (Modules
.size() != 1) {
1222 for (unsigned m
= 0, e
= Modules
.size(); m
!= e
; ++m
) {
1223 Module
&M
= *Modules
[m
];
1224 for (const auto &GV
: M
.globals()) {
1225 if (GV
.hasLocalLinkage() || GV
.isDeclaration() ||
1226 GV
.hasAppendingLinkage() || !GV
.hasName())
1227 continue;// Ignore external globals and globals with internal linkage.
1229 const GlobalValue
*&GVEntry
= LinkedGlobalsMap
[std::make_pair(
1230 std::string(GV
.getName()), GV
.getType())];
1232 // If this is the first time we've seen this global, it is the canonical
1239 // If the existing global is strong, never replace it.
1240 if (GVEntry
->hasExternalLinkage())
1243 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1244 // symbol. FIXME is this right for common?
1245 if (GV
.hasExternalLinkage() || GVEntry
->hasExternalWeakLinkage())
1251 std::vector
<const GlobalValue
*> NonCanonicalGlobals
;
1252 for (unsigned m
= 0, e
= Modules
.size(); m
!= e
; ++m
) {
1253 Module
&M
= *Modules
[m
];
1254 for (const auto &GV
: M
.globals()) {
1255 // In the multi-module case, see what this global maps to.
1256 if (!LinkedGlobalsMap
.empty()) {
1257 if (const GlobalValue
*GVEntry
= LinkedGlobalsMap
[std::make_pair(
1258 std::string(GV
.getName()), GV
.getType())]) {
1259 // If something else is the canonical global, ignore this one.
1260 if (GVEntry
!= &GV
) {
1261 NonCanonicalGlobals
.push_back(&GV
);
1267 if (!GV
.isDeclaration()) {
1268 addGlobalMapping(&GV
, getMemoryForGV(&GV
));
1270 // External variable reference. Try to use the dynamic loader to
1271 // get a pointer to it.
1272 if (void *SymAddr
= sys::DynamicLibrary::SearchForAddressOfSymbol(
1273 std::string(GV
.getName())))
1274 addGlobalMapping(&GV
, SymAddr
);
1276 report_fatal_error("Could not resolve external global address: "
1282 // If there are multiple modules, map the non-canonical globals to their
1283 // canonical location.
1284 if (!NonCanonicalGlobals
.empty()) {
1285 for (const GlobalValue
*GV
: NonCanonicalGlobals
) {
1286 const GlobalValue
*CGV
= LinkedGlobalsMap
[std::make_pair(
1287 std::string(GV
->getName()), GV
->getType())];
1288 void *Ptr
= getPointerToGlobalIfAvailable(CGV
);
1289 assert(Ptr
&& "Canonical global wasn't codegen'd!");
1290 addGlobalMapping(GV
, Ptr
);
1294 // Now that all of the globals are set up in memory, loop through them all
1295 // and initialize their contents.
1296 for (const auto &GV
: M
.globals()) {
1297 if (!GV
.isDeclaration()) {
1298 if (!LinkedGlobalsMap
.empty()) {
1299 if (const GlobalValue
*GVEntry
= LinkedGlobalsMap
[std::make_pair(
1300 std::string(GV
.getName()), GV
.getType())])
1301 if (GVEntry
!= &GV
) // Not the canonical variable.
1304 emitGlobalVariable(&GV
);
1310 // EmitGlobalVariable - This method emits the specified global variable to the
1311 // address specified in GlobalAddresses, or allocates new memory if it's not
1312 // already in the map.
1313 void ExecutionEngine::emitGlobalVariable(const GlobalVariable
*GV
) {
1314 void *GA
= getPointerToGlobalIfAvailable(GV
);
1317 // If it's not already specified, allocate memory for the global.
1318 GA
= getMemoryForGV(GV
);
1320 // If we failed to allocate memory for this global, return.
1323 addGlobalMapping(GV
, GA
);
1326 // Don't initialize if it's thread local, let the client do it.
1327 if (!GV
->isThreadLocal())
1328 InitializeMemory(GV
->getInitializer(), GA
);
1330 Type
*ElTy
= GV
->getValueType();
1331 size_t GVSize
= (size_t)getDataLayout().getTypeAllocSize(ElTy
);
1332 NumInitBytes
+= (unsigned)GVSize
;