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