70 lines · cpp
1//===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This programs is a simple example that creates an LLVM module "from scratch",10// emitting it as a bitcode file to standard out. This is just to show how11// LLVM projects work and to demonstrate some of the LLVM APIs.12//13//===----------------------------------------------------------------------===//14 15#include "llvm/Bitcode/BitcodeWriter.h"16#include "llvm/IR/BasicBlock.h"17#include "llvm/IR/Constants.h"18#include "llvm/IR/DerivedTypes.h"19#include "llvm/IR/Function.h"20#include "llvm/IR/InstrTypes.h"21#include "llvm/IR/Instruction.h"22#include "llvm/IR/Instructions.h"23#include "llvm/IR/LLVMContext.h"24#include "llvm/IR/Module.h"25#include "llvm/IR/Type.h"26#include "llvm/Support/raw_ostream.h"27 28using namespace llvm;29 30int main() {31 LLVMContext Context;32 33 // Create the "module" or "program" or "translation unit" to hold the34 // function35 Module *M = new Module("test", Context);36 37 // Create the main function: first create the type 'int ()'38 FunctionType *FT =39 FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);40 41 // By passing a module as the last parameter to the Function constructor,42 // it automatically gets appended to the Module.43 Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);44 45 // Add a basic block to the function... again, it automatically inserts46 // because of the last argument.47 BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);48 49 // Get pointers to the constant integers...50 Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);51 Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);52 53 // Create the add instruction... does not insert...54 Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,55 "addresult");56 57 // explicitly insert it into the basic block...58 Add->insertInto(BB, BB->end());59 60 // Create the return instruction and add it to the basic block61 ReturnInst::Create(Context, Add)->insertInto(BB, BB->end());62 63 // Output the bitcode file to stdout64 WriteBitcodeToFile(*M, outs());65 66 // Delete the module and all of its contents.67 delete M;68 return 0;69}70