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