blob: a057a8c8a1046468f8d140d1e7439a7435c868ee [file] [log] [blame]
Reid Spencer66e7cd02004-09-11 20:30:11 +00001//===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
Chris Lattner8ca0eeb2003-08-21 22:29:52 +00002//
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
9#include "llvm/Module.h"
10#include "llvm/DerivedTypes.h"
11#include "llvm/Constants.h"
12#include "llvm/Instructions.h"
13#include "llvm/Bytecode/Writer.h"
Reid Spencer321f8312004-07-04 12:22:14 +000014#include <iostream>
Chris Lattner8ca0eeb2003-08-21 22:29:52 +000015
Brian Gaeked0fde302003-11-11 22:41:34 +000016using namespace llvm;
17
Chris Lattner8ca0eeb2003-08-21 22:29:52 +000018int main() {
19 // Create the "module" or "program" or "translation unit" to hold the
20 // function
21 Module *M = new Module("test");
22
23 // Create the main function: first create the type 'int ()'
24 FunctionType *FT = FunctionType::get(Type::IntTy, std::vector<const Type*>(),
25 /*not vararg*/false);
26
27 // By passing a module as the last parameter to the Function constructor,
28 // it automatically gets appended to the Module.
29 Function *F = new Function(FT, Function::ExternalLinkage, "main", M);
30
31 // Add a basic block to the function... again, it automatically inserts
32 // because of the last argument.
33 BasicBlock *BB = new BasicBlock("EntryBlock", F);
34
35 // Get pointers to the constant integers...
36 Value *Two = ConstantSInt::get(Type::IntTy, 2);
37 Value *Three = ConstantSInt::get(Type::IntTy, 3);
38
39 // Create the add instruction... does not insert...
40 Instruction *Add = BinaryOperator::create(Instruction::Add, Two, Three,
41 "addresult");
42
43 // explicitly insert it into the basic block...
44 BB->getInstList().push_back(Add);
45
46 // Create the return instruction and add it to the basic block
47 BB->getInstList().push_back(new ReturnInst(Add));
48
49 // Output the bytecode file to stdout
50 WriteBytecodeToFile(M, std::cout);
51
52 // Delete the module and all of its contents.
53 delete M;
54 return 0;
55}