LLVM API Documentation

ExecutionEngine.cpp
Go to the documentation of this file.
00001 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the common interface used by the various execution engine
00011 // subclasses.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/ExecutionEngine/ExecutionEngine.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/ADT/Statistic.h"
00018 #include "llvm/ExecutionEngine/GenericValue.h"
00019 #include "llvm/ExecutionEngine/JITMemoryManager.h"
00020 #include "llvm/ExecutionEngine/ObjectCache.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/Module.h"
00025 #include "llvm/IR/Operator.h"
00026 #include "llvm/IR/ValueHandle.h"
00027 #include "llvm/Object/Archive.h"
00028 #include "llvm/Object/ObjectFile.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/DynamicLibrary.h"
00031 #include "llvm/Support/ErrorHandling.h"
00032 #include "llvm/Support/Host.h"
00033 #include "llvm/Support/MutexGuard.h"
00034 #include "llvm/Support/TargetRegistry.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetMachine.h"
00037 #include <cmath>
00038 #include <cstring>
00039 using namespace llvm;
00040 
00041 #define DEBUG_TYPE "jit"
00042 
00043 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
00044 STATISTIC(NumGlobals  , "Number of global vars initialized");
00045 
00046 // Pin the vtable to this file.
00047 void ObjectCache::anchor() {}
00048 void ObjectBuffer::anchor() {}
00049 void ObjectBufferStream::anchor() {}
00050 
00051 ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
00052     std::unique_ptr<Module> M, std::string *ErrorStr,
00053     RTDyldMemoryManager *MCJMM, std::unique_ptr<TargetMachine> TM) = nullptr;
00054 ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
00055                                                 std::string *ErrorStr) =nullptr;
00056 
00057 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
00058   : EEState(*this),
00059     LazyFunctionCreator(nullptr) {
00060   CompilingLazily         = false;
00061   GVCompilationDisabled   = false;
00062   SymbolSearchingDisabled = false;
00063 
00064   // IR module verification is enabled by default in debug builds, and disabled
00065   // by default in release builds.
00066 #ifndef NDEBUG
00067   VerifyModules = true;
00068 #else
00069   VerifyModules = false;
00070 #endif
00071 
00072   assert(M && "Module is null?");
00073   Modules.push_back(std::move(M));
00074 }
00075 
00076 ExecutionEngine::~ExecutionEngine() {
00077   clearAllGlobalMappings();
00078 }
00079 
00080 namespace {
00081 /// \brief Helper class which uses a value handler to automatically deletes the
00082 /// memory block when the GlobalVariable is destroyed.
00083 class GVMemoryBlock : public CallbackVH {
00084   GVMemoryBlock(const GlobalVariable *GV)
00085     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
00086 
00087 public:
00088   /// \brief Returns the address the GlobalVariable should be written into.  The
00089   /// GVMemoryBlock object prefixes that.
00090   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
00091     Type *ElTy = GV->getType()->getElementType();
00092     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
00093     void *RawMemory = ::operator new(
00094       DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
00095                                    TD.getPreferredAlignment(GV))
00096       + GVSize);
00097     new(RawMemory) GVMemoryBlock(GV);
00098     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
00099   }
00100 
00101   void deleted() override {
00102     // We allocated with operator new and with some extra memory hanging off the
00103     // end, so don't just delete this.  I'm not sure if this is actually
00104     // required.
00105     this->~GVMemoryBlock();
00106     ::operator delete(this);
00107   }
00108 };
00109 }  // anonymous namespace
00110 
00111 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
00112   return GVMemoryBlock::Create(GV, *getDataLayout());
00113 }
00114 
00115 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
00116   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
00117 }
00118 
00119 void
00120 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
00121   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
00122 }
00123 
00124 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
00125   llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
00126 }
00127 
00128 bool ExecutionEngine::removeModule(Module *M) {
00129   for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
00130     Module *Found = I->get();
00131     if (Found == M) {
00132       I->release();
00133       Modules.erase(I);
00134       clearGlobalMappingsFromModule(M);
00135       return true;
00136     }
00137   }
00138   return false;
00139 }
00140 
00141 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
00142   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
00143     if (Function *F = Modules[i]->getFunction(FnName))
00144       return F;
00145   }
00146   return nullptr;
00147 }
00148 
00149 
00150 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
00151   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
00152   void *OldVal;
00153 
00154   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
00155   // GlobalAddressMap.
00156   if (I == GlobalAddressMap.end())
00157     OldVal = nullptr;
00158   else {
00159     OldVal = I->second;
00160     GlobalAddressMap.erase(I);
00161   }
00162 
00163   GlobalAddressReverseMap.erase(OldVal);
00164   return OldVal;
00165 }
00166 
00167 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
00168   MutexGuard locked(lock);
00169 
00170   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
00171         << "\' to [" << Addr << "]\n";);
00172   void *&CurVal = EEState.getGlobalAddressMap()[GV];
00173   assert((!CurVal || !Addr) && "GlobalMapping already established!");
00174   CurVal = Addr;
00175 
00176   // If we are using the reverse mapping, add it too.
00177   if (!EEState.getGlobalAddressReverseMap().empty()) {
00178     AssertingVH<const GlobalValue> &V =
00179       EEState.getGlobalAddressReverseMap()[Addr];
00180     assert((!V || !GV) && "GlobalMapping already established!");
00181     V = GV;
00182   }
00183 }
00184 
00185 void ExecutionEngine::clearAllGlobalMappings() {
00186   MutexGuard locked(lock);
00187 
00188   EEState.getGlobalAddressMap().clear();
00189   EEState.getGlobalAddressReverseMap().clear();
00190 }
00191 
00192 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
00193   MutexGuard locked(lock);
00194 
00195   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
00196     EEState.RemoveMapping(FI);
00197   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
00198        GI != GE; ++GI)
00199     EEState.RemoveMapping(GI);
00200 }
00201 
00202 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
00203   MutexGuard locked(lock);
00204 
00205   ExecutionEngineState::GlobalAddressMapTy &Map =
00206     EEState.getGlobalAddressMap();
00207 
00208   // Deleting from the mapping?
00209   if (!Addr)
00210     return EEState.RemoveMapping(GV);
00211 
00212   void *&CurVal = Map[GV];
00213   void *OldVal = CurVal;
00214 
00215   if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
00216     EEState.getGlobalAddressReverseMap().erase(CurVal);
00217   CurVal = Addr;
00218 
00219   // If we are using the reverse mapping, add it too.
00220   if (!EEState.getGlobalAddressReverseMap().empty()) {
00221     AssertingVH<const GlobalValue> &V =
00222       EEState.getGlobalAddressReverseMap()[Addr];
00223     assert((!V || !GV) && "GlobalMapping already established!");
00224     V = GV;
00225   }
00226   return OldVal;
00227 }
00228 
00229 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
00230   MutexGuard locked(lock);
00231 
00232   ExecutionEngineState::GlobalAddressMapTy::iterator I =
00233     EEState.getGlobalAddressMap().find(GV);
00234   return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
00235 }
00236 
00237 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
00238   MutexGuard locked(lock);
00239 
00240   // If we haven't computed the reverse mapping yet, do so first.
00241   if (EEState.getGlobalAddressReverseMap().empty()) {
00242     for (ExecutionEngineState::GlobalAddressMapTy::iterator
00243          I = EEState.getGlobalAddressMap().begin(),
00244          E = EEState.getGlobalAddressMap().end(); I != E; ++I)
00245       EEState.getGlobalAddressReverseMap().insert(std::make_pair(
00246                                                           I->second, I->first));
00247   }
00248 
00249   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
00250     EEState.getGlobalAddressReverseMap().find(Addr);
00251   return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
00252 }
00253 
00254 namespace {
00255 class ArgvArray {
00256   std::unique_ptr<char[]> Array;
00257   std::vector<std::unique_ptr<char[]>> Values;
00258 public:
00259   /// Turn a vector of strings into a nice argv style array of pointers to null
00260   /// terminated strings.
00261   void *reset(LLVMContext &C, ExecutionEngine *EE,
00262               const std::vector<std::string> &InputArgv);
00263 };
00264 }  // anonymous namespace
00265 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
00266                        const std::vector<std::string> &InputArgv) {
00267   Values.clear();  // Free the old contents.
00268   Values.reserve(InputArgv.size());
00269   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
00270   Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
00271 
00272   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
00273   Type *SBytePtr = Type::getInt8PtrTy(C);
00274 
00275   for (unsigned i = 0; i != InputArgv.size(); ++i) {
00276     unsigned Size = InputArgv[i].size()+1;
00277     auto Dest = make_unique<char[]>(Size);
00278     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
00279 
00280     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
00281     Dest[Size-1] = 0;
00282 
00283     // Endian safe: Array[i] = (PointerTy)Dest;
00284     EE->StoreValueToMemory(PTOGV(Dest.get()),
00285                            (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
00286     Values.push_back(std::move(Dest));
00287   }
00288 
00289   // Null terminate it
00290   EE->StoreValueToMemory(PTOGV(nullptr),
00291                          (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
00292                          SBytePtr);
00293   return Array.get();
00294 }
00295 
00296 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
00297                                                        bool isDtors) {
00298   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
00299   GlobalVariable *GV = module.getNamedGlobal(Name);
00300 
00301   // If this global has internal linkage, or if it has a use, then it must be
00302   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
00303   // this is the case, don't execute any of the global ctors, __main will do
00304   // it.
00305   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
00306 
00307   // Should be an array of '{ i32, void ()* }' structs.  The first value is
00308   // the init priority, which we ignore.
00309   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
00310   if (!InitList)
00311     return;
00312   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
00313     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
00314     if (!CS) continue;
00315 
00316     Constant *FP = CS->getOperand(1);
00317     if (FP->isNullValue())
00318       continue;  // Found a sentinal value, ignore.
00319 
00320     // Strip off constant expression casts.
00321     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
00322       if (CE->isCast())
00323         FP = CE->getOperand(0);
00324 
00325     // Execute the ctor/dtor function!
00326     if (Function *F = dyn_cast<Function>(FP))
00327       runFunction(F, std::vector<GenericValue>());
00328 
00329     // FIXME: It is marginally lame that we just do nothing here if we see an
00330     // entry we don't recognize. It might not be unreasonable for the verifier
00331     // to not even allow this and just assert here.
00332   }
00333 }
00334 
00335 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
00336   // Execute global ctors/dtors for each module in the program.
00337   for (std::unique_ptr<Module> &M : Modules)
00338     runStaticConstructorsDestructors(*M, isDtors);
00339 }
00340 
00341 #ifndef NDEBUG
00342 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
00343 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
00344   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
00345   for (unsigned i = 0; i < PtrSize; ++i)
00346     if (*(i + (uint8_t*)Loc))
00347       return false;
00348   return true;
00349 }
00350 #endif
00351 
00352 int ExecutionEngine::runFunctionAsMain(Function *Fn,
00353                                        const std::vector<std::string> &argv,
00354                                        const char * const * envp) {
00355   std::vector<GenericValue> GVArgs;
00356   GenericValue GVArgc;
00357   GVArgc.IntVal = APInt(32, argv.size());
00358 
00359   // Check main() type
00360   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
00361   FunctionType *FTy = Fn->getFunctionType();
00362   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
00363 
00364   // Check the argument types.
00365   if (NumArgs > 3)
00366     report_fatal_error("Invalid number of arguments of main() supplied");
00367   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
00368     report_fatal_error("Invalid type for third argument of main() supplied");
00369   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
00370     report_fatal_error("Invalid type for second argument of main() supplied");
00371   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
00372     report_fatal_error("Invalid type for first argument of main() supplied");
00373   if (!FTy->getReturnType()->isIntegerTy() &&
00374       !FTy->getReturnType()->isVoidTy())
00375     report_fatal_error("Invalid return type of main() supplied");
00376 
00377   ArgvArray CArgv;
00378   ArgvArray CEnv;
00379   if (NumArgs) {
00380     GVArgs.push_back(GVArgc); // Arg #0 = argc.
00381     if (NumArgs > 1) {
00382       // Arg #1 = argv.
00383       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
00384       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
00385              "argv[0] was null after CreateArgv");
00386       if (NumArgs > 2) {
00387         std::vector<std::string> EnvVars;
00388         for (unsigned i = 0; envp[i]; ++i)
00389           EnvVars.push_back(envp[i]);
00390         // Arg #2 = envp.
00391         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
00392       }
00393     }
00394   }
00395 
00396   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
00397 }
00398 
00399 void EngineBuilder::InitEngine() {
00400   WhichEngine = EngineKind::Either;
00401   ErrorStr = nullptr;
00402   OptLevel = CodeGenOpt::Default;
00403   MCJMM = nullptr;
00404   JMM = nullptr;
00405   Options = TargetOptions();
00406   RelocModel = Reloc::Default;
00407   CMModel = CodeModel::JITDefault;
00408 
00409 // IR module verification is enabled by default in debug builds, and disabled
00410 // by default in release builds.
00411 #ifndef NDEBUG
00412   VerifyModules = true;
00413 #else
00414   VerifyModules = false;
00415 #endif
00416 }
00417 
00418 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
00419   std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
00420 
00421   // Make sure we can resolve symbols in the program as well. The zero arg
00422   // to the function tells DynamicLibrary to load the program, not a library.
00423   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
00424     return nullptr;
00425 
00426   assert(!(JMM && MCJMM));
00427   
00428   // If the user specified a memory manager but didn't specify which engine to
00429   // create, we assume they only want the JIT, and we fail if they only want
00430   // the interpreter.
00431   if (JMM || MCJMM) {
00432     if (WhichEngine & EngineKind::JIT)
00433       WhichEngine = EngineKind::JIT;
00434     else {
00435       if (ErrorStr)
00436         *ErrorStr = "Cannot create an interpreter with a memory manager.";
00437       return nullptr;
00438     }
00439   }
00440 
00441   // Unless the interpreter was explicitly selected or the JIT is not linked,
00442   // try making a JIT.
00443   if ((WhichEngine & EngineKind::JIT) && TheTM) {
00444     Triple TT(M->getTargetTriple());
00445     if (!TM->getTarget().hasJIT()) {
00446       errs() << "WARNING: This target JIT is not designed for the host"
00447              << " you are running.  If bad things happen, please choose"
00448              << " a different -march switch.\n";
00449     }
00450 
00451     ExecutionEngine *EE = nullptr;
00452     if (ExecutionEngine::MCJITCtor)
00453       EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr,
00454                                       MCJMM ? MCJMM : JMM, std::move(TheTM));
00455     if (EE) {
00456       EE->setVerifyModules(VerifyModules);
00457       return EE;
00458     }
00459   }
00460 
00461   // If we can't make a JIT and we didn't request one specifically, try making
00462   // an interpreter instead.
00463   if (WhichEngine & EngineKind::Interpreter) {
00464     if (ExecutionEngine::InterpCtor)
00465       return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
00466     if (ErrorStr)
00467       *ErrorStr = "Interpreter has not been linked in.";
00468     return nullptr;
00469   }
00470 
00471   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
00472     if (ErrorStr)
00473       *ErrorStr = "JIT has not been linked in.";
00474   }
00475 
00476   return nullptr;
00477 }
00478 
00479 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
00480   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
00481     return getPointerToFunction(F);
00482 
00483   MutexGuard locked(lock);
00484   if (void *P = EEState.getGlobalAddressMap()[GV])
00485     return P;
00486 
00487   // Global variable might have been added since interpreter started.
00488   if (GlobalVariable *GVar =
00489           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
00490     EmitGlobalVariable(GVar);
00491   else
00492     llvm_unreachable("Global hasn't had an address allocated yet!");
00493 
00494   return EEState.getGlobalAddressMap()[GV];
00495 }
00496 
00497 /// \brief Converts a Constant* into a GenericValue, including handling of
00498 /// ConstantExpr values.
00499 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
00500   // If its undefined, return the garbage.
00501   if (isa<UndefValue>(C)) {
00502     GenericValue Result;
00503     switch (C->getType()->getTypeID()) {
00504     default:
00505       break;
00506     case Type::IntegerTyID:
00507     case Type::X86_FP80TyID:
00508     case Type::FP128TyID:
00509     case Type::PPC_FP128TyID:
00510       // Although the value is undefined, we still have to construct an APInt
00511       // with the correct bit width.
00512       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
00513       break;
00514     case Type::StructTyID: {
00515       // if the whole struct is 'undef' just reserve memory for the value.
00516       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
00517         unsigned int elemNum = STy->getNumElements();
00518         Result.AggregateVal.resize(elemNum);
00519         for (unsigned int i = 0; i < elemNum; ++i) {
00520           Type *ElemTy = STy->getElementType(i);
00521           if (ElemTy->isIntegerTy())
00522             Result.AggregateVal[i].IntVal = 
00523               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
00524           else if (ElemTy->isAggregateType()) {
00525               const Constant *ElemUndef = UndefValue::get(ElemTy);
00526               Result.AggregateVal[i] = getConstantValue(ElemUndef);
00527             }
00528           }
00529         }
00530       }
00531       break;
00532     case Type::VectorTyID:
00533       // if the whole vector is 'undef' just reserve memory for the value.
00534       const VectorType* VTy = dyn_cast<VectorType>(C->getType());
00535       const Type *ElemTy = VTy->getElementType();
00536       unsigned int elemNum = VTy->getNumElements();
00537       Result.AggregateVal.resize(elemNum);
00538       if (ElemTy->isIntegerTy())
00539         for (unsigned int i = 0; i < elemNum; ++i)
00540           Result.AggregateVal[i].IntVal =
00541             APInt(ElemTy->getPrimitiveSizeInBits(), 0);
00542       break;
00543     }
00544     return Result;
00545   }
00546 
00547   // Otherwise, if the value is a ConstantExpr...
00548   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00549     Constant *Op0 = CE->getOperand(0);
00550     switch (CE->getOpcode()) {
00551     case Instruction::GetElementPtr: {
00552       // Compute the index
00553       GenericValue Result = getConstantValue(Op0);
00554       APInt Offset(DL->getPointerSizeInBits(), 0);
00555       cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
00556 
00557       char* tmp = (char*) Result.PointerVal;
00558       Result = PTOGV(tmp + Offset.getSExtValue());
00559       return Result;
00560     }
00561     case Instruction::Trunc: {
00562       GenericValue GV = getConstantValue(Op0);
00563       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00564       GV.IntVal = GV.IntVal.trunc(BitWidth);
00565       return GV;
00566     }
00567     case Instruction::ZExt: {
00568       GenericValue GV = getConstantValue(Op0);
00569       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00570       GV.IntVal = GV.IntVal.zext(BitWidth);
00571       return GV;
00572     }
00573     case Instruction::SExt: {
00574       GenericValue GV = getConstantValue(Op0);
00575       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00576       GV.IntVal = GV.IntVal.sext(BitWidth);
00577       return GV;
00578     }
00579     case Instruction::FPTrunc: {
00580       // FIXME long double
00581       GenericValue GV = getConstantValue(Op0);
00582       GV.FloatVal = float(GV.DoubleVal);
00583       return GV;
00584     }
00585     case Instruction::FPExt:{
00586       // FIXME long double
00587       GenericValue GV = getConstantValue(Op0);
00588       GV.DoubleVal = double(GV.FloatVal);
00589       return GV;
00590     }
00591     case Instruction::UIToFP: {
00592       GenericValue GV = getConstantValue(Op0);
00593       if (CE->getType()->isFloatTy())
00594         GV.FloatVal = float(GV.IntVal.roundToDouble());
00595       else if (CE->getType()->isDoubleTy())
00596         GV.DoubleVal = GV.IntVal.roundToDouble();
00597       else if (CE->getType()->isX86_FP80Ty()) {
00598         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
00599         (void)apf.convertFromAPInt(GV.IntVal,
00600                                    false,
00601                                    APFloat::rmNearestTiesToEven);
00602         GV.IntVal = apf.bitcastToAPInt();
00603       }
00604       return GV;
00605     }
00606     case Instruction::SIToFP: {
00607       GenericValue GV = getConstantValue(Op0);
00608       if (CE->getType()->isFloatTy())
00609         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
00610       else if (CE->getType()->isDoubleTy())
00611         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
00612       else if (CE->getType()->isX86_FP80Ty()) {
00613         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
00614         (void)apf.convertFromAPInt(GV.IntVal,
00615                                    true,
00616                                    APFloat::rmNearestTiesToEven);
00617         GV.IntVal = apf.bitcastToAPInt();
00618       }
00619       return GV;
00620     }
00621     case Instruction::FPToUI: // double->APInt conversion handles sign
00622     case Instruction::FPToSI: {
00623       GenericValue GV = getConstantValue(Op0);
00624       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00625       if (Op0->getType()->isFloatTy())
00626         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
00627       else if (Op0->getType()->isDoubleTy())
00628         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
00629       else if (Op0->getType()->isX86_FP80Ty()) {
00630         APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
00631         uint64_t v;
00632         bool ignored;
00633         (void)apf.convertToInteger(&v, BitWidth,
00634                                    CE->getOpcode()==Instruction::FPToSI,
00635                                    APFloat::rmTowardZero, &ignored);
00636         GV.IntVal = v; // endian?
00637       }
00638       return GV;
00639     }
00640     case Instruction::PtrToInt: {
00641       GenericValue GV = getConstantValue(Op0);
00642       uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
00643       assert(PtrWidth <= 64 && "Bad pointer width");
00644       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
00645       uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
00646       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
00647       return GV;
00648     }
00649     case Instruction::IntToPtr: {
00650       GenericValue GV = getConstantValue(Op0);
00651       uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
00652       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
00653       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
00654       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
00655       return GV;
00656     }
00657     case Instruction::BitCast: {
00658       GenericValue GV = getConstantValue(Op0);
00659       Type* DestTy = CE->getType();
00660       switch (Op0->getType()->getTypeID()) {
00661         default: llvm_unreachable("Invalid bitcast operand");
00662         case Type::IntegerTyID:
00663           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
00664           if (DestTy->isFloatTy())
00665             GV.FloatVal = GV.IntVal.bitsToFloat();
00666           else if (DestTy->isDoubleTy())
00667             GV.DoubleVal = GV.IntVal.bitsToDouble();
00668           break;
00669         case Type::FloatTyID:
00670           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
00671           GV.IntVal = APInt::floatToBits(GV.FloatVal);
00672           break;
00673         case Type::DoubleTyID:
00674           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
00675           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
00676           break;
00677         case Type::PointerTyID:
00678           assert(DestTy->isPointerTy() && "Invalid bitcast");
00679           break; // getConstantValue(Op0)  above already converted it
00680       }
00681       return GV;
00682     }
00683     case Instruction::Add:
00684     case Instruction::FAdd:
00685     case Instruction::Sub:
00686     case Instruction::FSub:
00687     case Instruction::Mul:
00688     case Instruction::FMul:
00689     case Instruction::UDiv:
00690     case Instruction::SDiv:
00691     case Instruction::URem:
00692     case Instruction::SRem:
00693     case Instruction::And:
00694     case Instruction::Or:
00695     case Instruction::Xor: {
00696       GenericValue LHS = getConstantValue(Op0);
00697       GenericValue RHS = getConstantValue(CE->getOperand(1));
00698       GenericValue GV;
00699       switch (CE->getOperand(0)->getType()->getTypeID()) {
00700       default: llvm_unreachable("Bad add type!");
00701       case Type::IntegerTyID:
00702         switch (CE->getOpcode()) {
00703           default: llvm_unreachable("Invalid integer opcode");
00704           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
00705           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
00706           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
00707           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
00708           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
00709           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
00710           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
00711           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
00712           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
00713           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
00714         }
00715         break;
00716       case Type::FloatTyID:
00717         switch (CE->getOpcode()) {
00718           default: llvm_unreachable("Invalid float opcode");
00719           case Instruction::FAdd:
00720             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
00721           case Instruction::FSub:
00722             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
00723           case Instruction::FMul:
00724             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
00725           case Instruction::FDiv:
00726             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
00727           case Instruction::FRem:
00728             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
00729         }
00730         break;
00731       case Type::DoubleTyID:
00732         switch (CE->getOpcode()) {
00733           default: llvm_unreachable("Invalid double opcode");
00734           case Instruction::FAdd:
00735             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
00736           case Instruction::FSub:
00737             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
00738           case Instruction::FMul:
00739             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
00740           case Instruction::FDiv:
00741             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
00742           case Instruction::FRem:
00743             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
00744         }
00745         break;
00746       case Type::X86_FP80TyID:
00747       case Type::PPC_FP128TyID:
00748       case Type::FP128TyID: {
00749         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
00750         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
00751         switch (CE->getOpcode()) {
00752           default: llvm_unreachable("Invalid long double opcode");
00753           case Instruction::FAdd:
00754             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
00755             GV.IntVal = apfLHS.bitcastToAPInt();
00756             break;
00757           case Instruction::FSub:
00758             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
00759                             APFloat::rmNearestTiesToEven);
00760             GV.IntVal = apfLHS.bitcastToAPInt();
00761             break;
00762           case Instruction::FMul:
00763             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
00764                             APFloat::rmNearestTiesToEven);
00765             GV.IntVal = apfLHS.bitcastToAPInt();
00766             break;
00767           case Instruction::FDiv:
00768             apfLHS.divide(APFloat(Sem, RHS.IntVal),
00769                           APFloat::rmNearestTiesToEven);
00770             GV.IntVal = apfLHS.bitcastToAPInt();
00771             break;
00772           case Instruction::FRem:
00773             apfLHS.mod(APFloat(Sem, RHS.IntVal),
00774                        APFloat::rmNearestTiesToEven);
00775             GV.IntVal = apfLHS.bitcastToAPInt();
00776             break;
00777           }
00778         }
00779         break;
00780       }
00781       return GV;
00782     }
00783     default:
00784       break;
00785     }
00786 
00787     SmallString<256> Msg;
00788     raw_svector_ostream OS(Msg);
00789     OS << "ConstantExpr not handled: " << *CE;
00790     report_fatal_error(OS.str());
00791   }
00792 
00793   // Otherwise, we have a simple constant.
00794   GenericValue Result;
00795   switch (C->getType()->getTypeID()) {
00796   case Type::FloatTyID:
00797     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
00798     break;
00799   case Type::DoubleTyID:
00800     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
00801     break;
00802   case Type::X86_FP80TyID:
00803   case Type::FP128TyID:
00804   case Type::PPC_FP128TyID:
00805     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
00806     break;
00807   case Type::IntegerTyID:
00808     Result.IntVal = cast<ConstantInt>(C)->getValue();
00809     break;
00810   case Type::PointerTyID:
00811     if (isa<ConstantPointerNull>(C))
00812       Result.PointerVal = nullptr;
00813     else if (const Function *F = dyn_cast<Function>(C))
00814       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
00815     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
00816       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
00817     else
00818       llvm_unreachable("Unknown constant pointer type!");
00819     break;
00820   case Type::VectorTyID: {
00821     unsigned elemNum;
00822     Type* ElemTy;
00823     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
00824     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
00825     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
00826 
00827     if (CDV) {
00828         elemNum = CDV->getNumElements();
00829         ElemTy = CDV->getElementType();
00830     } else if (CV || CAZ) {
00831         VectorType* VTy = dyn_cast<VectorType>(C->getType());
00832         elemNum = VTy->getNumElements();
00833         ElemTy = VTy->getElementType();
00834     } else {
00835         llvm_unreachable("Unknown constant vector type!");
00836     }
00837 
00838     Result.AggregateVal.resize(elemNum);
00839     // Check if vector holds floats.
00840     if(ElemTy->isFloatTy()) {
00841       if (CAZ) {
00842         GenericValue floatZero;
00843         floatZero.FloatVal = 0.f;
00844         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
00845                   floatZero);
00846         break;
00847       }
00848       if(CV) {
00849         for (unsigned i = 0; i < elemNum; ++i)
00850           if (!isa<UndefValue>(CV->getOperand(i)))
00851             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
00852               CV->getOperand(i))->getValueAPF().convertToFloat();
00853         break;
00854       }
00855       if(CDV)
00856         for (unsigned i = 0; i < elemNum; ++i)
00857           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
00858 
00859       break;
00860     }
00861     // Check if vector holds doubles.
00862     if (ElemTy->isDoubleTy()) {
00863       if (CAZ) {
00864         GenericValue doubleZero;
00865         doubleZero.DoubleVal = 0.0;
00866         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
00867                   doubleZero);
00868         break;
00869       }
00870       if(CV) {
00871         for (unsigned i = 0; i < elemNum; ++i)
00872           if (!isa<UndefValue>(CV->getOperand(i)))
00873             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
00874               CV->getOperand(i))->getValueAPF().convertToDouble();
00875         break;
00876       }
00877       if(CDV)
00878         for (unsigned i = 0; i < elemNum; ++i)
00879           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
00880 
00881       break;
00882     }
00883     // Check if vector holds integers.
00884     if (ElemTy->isIntegerTy()) {
00885       if (CAZ) {
00886         GenericValue intZero;     
00887         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
00888         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
00889                   intZero);
00890         break;
00891       }
00892       if(CV) {
00893         for (unsigned i = 0; i < elemNum; ++i)
00894           if (!isa<UndefValue>(CV->getOperand(i)))
00895             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
00896                                             CV->getOperand(i))->getValue();
00897           else {
00898             Result.AggregateVal[i].IntVal =
00899               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
00900           }
00901         break;
00902       }
00903       if(CDV)
00904         for (unsigned i = 0; i < elemNum; ++i)
00905           Result.AggregateVal[i].IntVal = APInt(
00906             CDV->getElementType()->getPrimitiveSizeInBits(),
00907             CDV->getElementAsInteger(i));
00908 
00909       break;
00910     }
00911     llvm_unreachable("Unknown constant pointer type!");
00912   }
00913   break;
00914 
00915   default:
00916     SmallString<256> Msg;
00917     raw_svector_ostream OS(Msg);
00918     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
00919     report_fatal_error(OS.str());
00920   }
00921 
00922   return Result;
00923 }
00924 
00925 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
00926 /// with the integer held in IntVal.
00927 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
00928                              unsigned StoreBytes) {
00929   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
00930   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
00931 
00932   if (sys::IsLittleEndianHost) {
00933     // Little-endian host - the source is ordered from LSB to MSB.  Order the
00934     // destination from LSB to MSB: Do a straight copy.
00935     memcpy(Dst, Src, StoreBytes);
00936   } else {
00937     // Big-endian host - the source is an array of 64 bit words ordered from
00938     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
00939     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
00940     while (StoreBytes > sizeof(uint64_t)) {
00941       StoreBytes -= sizeof(uint64_t);
00942       // May not be aligned so use memcpy.
00943       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
00944       Src += sizeof(uint64_t);
00945     }
00946 
00947     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
00948   }
00949 }
00950 
00951 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
00952                                          GenericValue *Ptr, Type *Ty) {
00953   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
00954 
00955   switch (Ty->getTypeID()) {
00956   default:
00957     dbgs() << "Cannot store value of type " << *Ty << "!\n";
00958     break;
00959   case Type::IntegerTyID:
00960     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
00961     break;
00962   case Type::FloatTyID:
00963     *((float*)Ptr) = Val.FloatVal;
00964     break;
00965   case Type::DoubleTyID:
00966     *((double*)Ptr) = Val.DoubleVal;
00967     break;
00968   case Type::X86_FP80TyID:
00969     memcpy(Ptr, Val.IntVal.getRawData(), 10);
00970     break;
00971   case Type::PointerTyID:
00972     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
00973     if (StoreBytes != sizeof(PointerTy))
00974       memset(&(Ptr->PointerVal), 0, StoreBytes);
00975 
00976     *((PointerTy*)Ptr) = Val.PointerVal;
00977     break;
00978   case Type::VectorTyID:
00979     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
00980       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
00981         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
00982       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
00983         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
00984       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
00985         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
00986         StoreIntToMemory(Val.AggregateVal[i].IntVal, 
00987           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
00988       }
00989     }
00990     break;
00991   }
00992 
00993   if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
00994     // Host and target are different endian - reverse the stored bytes.
00995     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
00996 }
00997 
00998 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
00999 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
01000 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
01001   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
01002   uint8_t *Dst = reinterpret_cast<uint8_t *>(
01003                    const_cast<uint64_t *>(IntVal.getRawData()));
01004 
01005   if (sys::IsLittleEndianHost)
01006     // Little-endian host - the destination must be ordered from LSB to MSB.
01007     // The source is ordered from LSB to MSB: Do a straight copy.
01008     memcpy(Dst, Src, LoadBytes);
01009   else {
01010     // Big-endian - the destination is an array of 64 bit words ordered from
01011     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
01012     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
01013     // a word.
01014     while (LoadBytes > sizeof(uint64_t)) {
01015       LoadBytes -= sizeof(uint64_t);
01016       // May not be aligned so use memcpy.
01017       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
01018       Dst += sizeof(uint64_t);
01019     }
01020 
01021     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
01022   }
01023 }
01024 
01025 /// FIXME: document
01026 ///
01027 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
01028                                           GenericValue *Ptr,
01029                                           Type *Ty) {
01030   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
01031 
01032   switch (Ty->getTypeID()) {
01033   case Type::IntegerTyID:
01034     // An APInt with all words initially zero.
01035     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
01036     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
01037     break;
01038   case Type::FloatTyID:
01039     Result.FloatVal = *((float*)Ptr);
01040     break;
01041   case Type::DoubleTyID:
01042     Result.DoubleVal = *((double*)Ptr);
01043     break;
01044   case Type::PointerTyID:
01045     Result.PointerVal = *((PointerTy*)Ptr);
01046     break;
01047   case Type::X86_FP80TyID: {
01048     // This is endian dependent, but it will only work on x86 anyway.
01049     // FIXME: Will not trap if loading a signaling NaN.
01050     uint64_t y[2];
01051     memcpy(y, Ptr, 10);
01052     Result.IntVal = APInt(80, y);
01053     break;
01054   }
01055   case Type::VectorTyID: {
01056     const VectorType *VT = cast<VectorType>(Ty);
01057     const Type *ElemT = VT->getElementType();
01058     const unsigned numElems = VT->getNumElements();
01059     if (ElemT->isFloatTy()) {
01060       Result.AggregateVal.resize(numElems);
01061       for (unsigned i = 0; i < numElems; ++i)
01062         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
01063     }
01064     if (ElemT->isDoubleTy()) {
01065       Result.AggregateVal.resize(numElems);
01066       for (unsigned i = 0; i < numElems; ++i)
01067         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
01068     }
01069     if (ElemT->isIntegerTy()) {
01070       GenericValue intZero;
01071       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
01072       intZero.IntVal = APInt(elemBitWidth, 0);
01073       Result.AggregateVal.resize(numElems, intZero);
01074       for (unsigned i = 0; i < numElems; ++i)
01075         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
01076           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
01077     }
01078   break;
01079   }
01080   default:
01081     SmallString<256> Msg;
01082     raw_svector_ostream OS(Msg);
01083     OS << "Cannot load value of type " << *Ty << "!";
01084     report_fatal_error(OS.str());
01085   }
01086 }
01087 
01088 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
01089   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
01090   DEBUG(Init->dump());
01091   if (isa<UndefValue>(Init))
01092     return;
01093   
01094   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
01095     unsigned ElementSize =
01096       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
01097     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
01098       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
01099     return;
01100   }
01101   
01102   if (isa<ConstantAggregateZero>(Init)) {
01103     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
01104     return;
01105   }
01106   
01107   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
01108     unsigned ElementSize =
01109       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
01110     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
01111       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
01112     return;
01113   }
01114   
01115   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
01116     const StructLayout *SL =
01117       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
01118     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
01119       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
01120     return;
01121   }
01122 
01123   if (const ConstantDataSequential *CDS =
01124                dyn_cast<ConstantDataSequential>(Init)) {
01125     // CDS is already laid out in host memory order.
01126     StringRef Data = CDS->getRawDataValues();
01127     memcpy(Addr, Data.data(), Data.size());
01128     return;
01129   }
01130 
01131   if (Init->getType()->isFirstClassType()) {
01132     GenericValue Val = getConstantValue(Init);
01133     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
01134     return;
01135   }
01136 
01137   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
01138   llvm_unreachable("Unknown constant type to initialize memory with!");
01139 }
01140 
01141 /// EmitGlobals - Emit all of the global variables to memory, storing their
01142 /// addresses into GlobalAddress.  This must make sure to copy the contents of
01143 /// their initializers into the memory.
01144 void ExecutionEngine::emitGlobals() {
01145   // Loop over all of the global variables in the program, allocating the memory
01146   // to hold them.  If there is more than one module, do a prepass over globals
01147   // to figure out how the different modules should link together.
01148   std::map<std::pair<std::string, Type*>,
01149            const GlobalValue*> LinkedGlobalsMap;
01150 
01151   if (Modules.size() != 1) {
01152     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
01153       Module &M = *Modules[m];
01154       for (const auto &GV : M.globals()) {
01155         if (GV.hasLocalLinkage() || GV.isDeclaration() ||
01156             GV.hasAppendingLinkage() || !GV.hasName())
01157           continue;// Ignore external globals and globals with internal linkage.
01158 
01159         const GlobalValue *&GVEntry =
01160           LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
01161 
01162         // If this is the first time we've seen this global, it is the canonical
01163         // version.
01164         if (!GVEntry) {
01165           GVEntry = &GV;
01166           continue;
01167         }
01168 
01169         // If the existing global is strong, never replace it.
01170         if (GVEntry->hasExternalLinkage())
01171           continue;
01172 
01173         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
01174         // symbol.  FIXME is this right for common?
01175         if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
01176           GVEntry = &GV;
01177       }
01178     }
01179   }
01180 
01181   std::vector<const GlobalValue*> NonCanonicalGlobals;
01182   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
01183     Module &M = *Modules[m];
01184     for (const auto &GV : M.globals()) {
01185       // In the multi-module case, see what this global maps to.
01186       if (!LinkedGlobalsMap.empty()) {
01187         if (const GlobalValue *GVEntry =
01188               LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
01189           // If something else is the canonical global, ignore this one.
01190           if (GVEntry != &GV) {
01191             NonCanonicalGlobals.push_back(&GV);
01192             continue;
01193           }
01194         }
01195       }
01196 
01197       if (!GV.isDeclaration()) {
01198         addGlobalMapping(&GV, getMemoryForGV(&GV));
01199       } else {
01200         // External variable reference. Try to use the dynamic loader to
01201         // get a pointer to it.
01202         if (void *SymAddr =
01203             sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
01204           addGlobalMapping(&GV, SymAddr);
01205         else {
01206           report_fatal_error("Could not resolve external global address: "
01207                             +GV.getName());
01208         }
01209       }
01210     }
01211 
01212     // If there are multiple modules, map the non-canonical globals to their
01213     // canonical location.
01214     if (!NonCanonicalGlobals.empty()) {
01215       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
01216         const GlobalValue *GV = NonCanonicalGlobals[i];
01217         const GlobalValue *CGV =
01218           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
01219         void *Ptr = getPointerToGlobalIfAvailable(CGV);
01220         assert(Ptr && "Canonical global wasn't codegen'd!");
01221         addGlobalMapping(GV, Ptr);
01222       }
01223     }
01224 
01225     // Now that all of the globals are set up in memory, loop through them all
01226     // and initialize their contents.
01227     for (const auto &GV : M.globals()) {
01228       if (!GV.isDeclaration()) {
01229         if (!LinkedGlobalsMap.empty()) {
01230           if (const GlobalValue *GVEntry =
01231                 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
01232             if (GVEntry != &GV)  // Not the canonical variable.
01233               continue;
01234         }
01235         EmitGlobalVariable(&GV);
01236       }
01237     }
01238   }
01239 }
01240 
01241 // EmitGlobalVariable - This method emits the specified global variable to the
01242 // address specified in GlobalAddresses, or allocates new memory if it's not
01243 // already in the map.
01244 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
01245   void *GA = getPointerToGlobalIfAvailable(GV);
01246 
01247   if (!GA) {
01248     // If it's not already specified, allocate memory for the global.
01249     GA = getMemoryForGV(GV);
01250 
01251     // If we failed to allocate memory for this global, return.
01252     if (!GA) return;
01253 
01254     addGlobalMapping(GV, GA);
01255   }
01256 
01257   // Don't initialize if it's thread local, let the client do it.
01258   if (!GV->isThreadLocal())
01259     InitializeMemory(GV->getInitializer(), GA);
01260 
01261   Type *ElTy = GV->getType()->getElementType();
01262   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
01263   NumInitBytes += (unsigned)GVSize;
01264   ++NumGlobals;
01265 }
01266 
01267 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
01268   : EE(EE), GlobalAddressMap(this) {
01269 }
01270 
01271 sys::Mutex *
01272 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
01273   return &EES->EE.lock;
01274 }
01275 
01276 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
01277                                                       const GlobalValue *Old) {
01278   void *OldVal = EES->GlobalAddressMap.lookup(Old);
01279   EES->GlobalAddressReverseMap.erase(OldVal);
01280 }
01281 
01282 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
01283                                                     const GlobalValue *,
01284                                                     const GlobalValue *) {
01285   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
01286                    " RAUW on a value it has a global mapping for.");
01287 }