ModuleMaker.cpp 2.2 KB

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