ModuleUtils.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //===-- ModuleUtils.cpp - Functions to manipulate Modules -----------------===//
  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 family of functions perform manipulations on Modules.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/ModuleUtils.h"
  14. #include "llvm/DerivedTypes.h"
  15. #include "llvm/Function.h"
  16. #include "llvm/IRBuilder.h"
  17. #include "llvm/Module.h"
  18. using namespace llvm;
  19. static void appendToGlobalArray(const char *Array,
  20. Module &M, Function *F, int Priority) {
  21. IRBuilder<> IRB(M.getContext());
  22. FunctionType *FnTy = FunctionType::get(IRB.getVoidTy(), false);
  23. StructType *Ty = StructType::get(
  24. IRB.getInt32Ty(), PointerType::getUnqual(FnTy), NULL);
  25. Constant *RuntimeCtorInit = ConstantStruct::get(
  26. Ty, IRB.getInt32(Priority), F, NULL);
  27. // Get the current set of static global constructors and add the new ctor
  28. // to the list.
  29. SmallVector<Constant *, 16> CurrentCtors;
  30. if (GlobalVariable * GVCtor = M.getNamedGlobal(Array)) {
  31. if (Constant *Init = GVCtor->getInitializer()) {
  32. unsigned n = Init->getNumOperands();
  33. CurrentCtors.reserve(n + 1);
  34. for (unsigned i = 0; i != n; ++i)
  35. CurrentCtors.push_back(cast<Constant>(Init->getOperand(i)));
  36. }
  37. GVCtor->eraseFromParent();
  38. }
  39. CurrentCtors.push_back(RuntimeCtorInit);
  40. // Create a new initializer.
  41. ArrayType *AT = ArrayType::get(RuntimeCtorInit->getType(),
  42. CurrentCtors.size());
  43. Constant *NewInit = ConstantArray::get(AT, CurrentCtors);
  44. // Create the new global variable and replace all uses of
  45. // the old global variable with the new one.
  46. (void)new GlobalVariable(M, NewInit->getType(), false,
  47. GlobalValue::AppendingLinkage, NewInit, Array);
  48. }
  49. void llvm::appendToGlobalCtors(Module &M, Function *F, int Priority) {
  50. appendToGlobalArray("llvm.global_ctors", M, F, Priority);
  51. }
  52. void llvm::appendToGlobalDtors(Module &M, Function *F, int Priority) {
  53. appendToGlobalArray("llvm.global_dtors", M, F, Priority);
  54. }