ModuleMaker.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //===- ModuleMaker.cpp - Example project which creates modules --*- C++ -*-===//
  2. //
  3. // This programs is a simple example that creates an LLVM module "from scratch",
  4. // emitting it as a bytecode file to standard out. This is just to show how
  5. // LLVM projects work and to demonstrate some of the LLVM APIs.
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Module.h"
  9. #include "llvm/DerivedTypes.h"
  10. #include "llvm/Constants.h"
  11. #include "llvm/Instructions.h"
  12. #include "llvm/Bytecode/Writer.h"
  13. int main() {
  14. // Create the "module" or "program" or "translation unit" to hold the
  15. // function
  16. Module *M = new Module("test");
  17. // Create the main function: first create the type 'int ()'
  18. FunctionType *FT = FunctionType::get(Type::IntTy, std::vector<const Type*>(),
  19. /*not vararg*/false);
  20. // By passing a module as the last parameter to the Function constructor,
  21. // it automatically gets appended to the Module.
  22. Function *F = new Function(FT, Function::ExternalLinkage, "main", M);
  23. // Add a basic block to the function... again, it automatically inserts
  24. // because of the last argument.
  25. BasicBlock *BB = new BasicBlock("EntryBlock", F);
  26. // Get pointers to the constant integers...
  27. Value *Two = ConstantSInt::get(Type::IntTy, 2);
  28. Value *Three = ConstantSInt::get(Type::IntTy, 3);
  29. // Create the add instruction... does not insert...
  30. Instruction *Add = BinaryOperator::create(Instruction::Add, Two, Three,
  31. "addresult");
  32. // explicitly insert it into the basic block...
  33. BB->getInstList().push_back(Add);
  34. // Create the return instruction and add it to the basic block
  35. BB->getInstList().push_back(new ReturnInst(Add));
  36. // Output the bytecode file to stdout
  37. WriteBytecodeToFile(M, std::cout);
  38. // Delete the module and all of its contents.
  39. delete M;
  40. return 0;
  41. }