• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
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 programs is a simple example that creates an LLVM module "from scratch",
11 // emitting it as a bitcode 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 
16 #include "llvm/Bitcode/BitcodeWriter.h"
17 #include "llvm/IR/BasicBlock.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/InstrTypes.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/Support/raw_ostream.h"
28 
29 using namespace llvm;
30 
main()31 int main() {
32   LLVMContext Context;
33 
34   // Create the "module" or "program" or "translation unit" to hold the
35   // function
36   Module *M = new Module("test", Context);
37 
38   // Create the main function: first create the type 'int ()'
39   FunctionType *FT =
40     FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);
41 
42   // By passing a module as the last parameter to the Function constructor,
43   // it automatically gets appended to the Module.
44   Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
45 
46   // Add a basic block to the function... again, it automatically inserts
47   // because of the last argument.
48   BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);
49 
50   // Get pointers to the constant integers...
51   Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
52   Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);
53 
54   // Create the add instruction... does not insert...
55   Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
56                                             "addresult");
57 
58   // explicitly insert it into the basic block...
59   BB->getInstList().push_back(Add);
60 
61   // Create the return instruction and add it to the basic block
62   BB->getInstList().push_back(ReturnInst::Create(Context, Add));
63 
64   // Output the bitcode file to stdout
65   WriteBitcodeToFile(*M, outs());
66 
67   // Delete the module and all of its contents.
68   delete M;
69   return 0;
70 }
71