blob: e2584e7ff34dd57198960502f2108aca3e19b7e9 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner45ca7c12007-12-29 20:37:57 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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/Module.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
20#include "llvm/Bitcode/ReaderWriter.h"
21#include <iostream>
22using namespace llvm;
23
24int main() {
25 // Create the "module" or "program" or "translation unit" to hold the
26 // function
27 Module *M = new Module("test");
28
29 // Create the main function: first create the type 'int ()'
Chris Lattner3fd51c02009-07-01 04:13:31 +000030 FunctionType *FT = FunctionType::get(Type::Int32Ty, /*not vararg*/false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031
32 // By passing a module as the last parameter to the Function constructor,
33 // it automatically gets appended to the Module.
Gabor Greifd6da1d02008-04-06 20:25:17 +000034 Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035
36 // Add a basic block to the function... again, it automatically inserts
37 // because of the last argument.
Gabor Greifd6da1d02008-04-06 20:25:17 +000038 BasicBlock *BB = BasicBlock::Create("EntryBlock", F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039
40 // Get pointers to the constant integers...
41 Value *Two = ConstantInt::get(Type::Int32Ty, 2);
42 Value *Three = ConstantInt::get(Type::Int32Ty, 3);
43
44 // Create the add instruction... does not insert...
Gabor Greifa645dd32008-05-16 19:29:10 +000045 Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046 "addresult");
47
48 // explicitly insert it into the basic block...
49 BB->getInstList().push_back(Add);
50
51 // Create the return instruction and add it to the basic block
Gabor Greifd6da1d02008-04-06 20:25:17 +000052 BB->getInstList().push_back(ReturnInst::Create(Add));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053
54 // Output the bitcode file to stdout
55 WriteBitcodeToFile(M, std::cout);
56
57 // Delete the module and all of its contents.
58 delete M;
59 return 0;
60}