ModuleMaker.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #include <iostream>
  14. using namespace llvm;
  15. int main() {
  16. // Create the "module" or "program" or "translation unit" to hold the
  17. // function
  18. Module *M = new Module("test");
  19. // Create the main function: first create the type 'int ()'
  20. FunctionType *FT = FunctionType::get(Type::IntTy, std::vector<const Type*>(),
  21. /*not vararg*/false);
  22. // By passing a module as the last parameter to the Function constructor,
  23. // it automatically gets appended to the Module.
  24. Function *F = new Function(FT, Function::ExternalLinkage, "main", M);
  25. // Add a basic block to the function... again, it automatically inserts
  26. // because of the last argument.
  27. BasicBlock *BB = new BasicBlock("EntryBlock", F);
  28. // Get pointers to the constant integers...
  29. Value *Two = ConstantSInt::get(Type::IntTy, 2);
  30. Value *Three = ConstantSInt::get(Type::IntTy, 3);
  31. // Create the add instruction... does not insert...
  32. Instruction *Add = BinaryOperator::create(Instruction::Add, Two, Three,
  33. "addresult");
  34. // explicitly insert it into the basic block...
  35. BB->getInstList().push_back(Add);
  36. // Create the return instruction and add it to the basic block
  37. BB->getInstList().push_back(new ReturnInst(Add));
  38. // Output the bytecode file to stdout
  39. WriteBytecodeToFile(M, std::cout);
  40. // Delete the module and all of its contents.
  41. delete M;
  42. return 0;
  43. }