Remove unneeded directories.
Even though Roman removed these directories in his working copy, they weren't removed from the actual repository, also causing his working copy to be corrupted.
This commit is contained in:
parent
f22ef01c33
commit
bff23f82e5
@ -1,467 +0,0 @@
|
||||
//===-- BrainF.cpp - BrainF compiler example ----------------------------===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file is distributed under the University of Illinois Open Source
|
||||
// License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===--------------------------------------------------------------------===//
|
||||
//
|
||||
// This class compiles the BrainF language into LLVM assembly.
|
||||
//
|
||||
// The BrainF language has 8 commands:
|
||||
// Command Equivalent C Action
|
||||
// ------- ------------ ------
|
||||
// , *h=getchar(); Read a character from stdin, 255 on EOF
|
||||
// . putchar(*h); Write a character to stdout
|
||||
// - --*h; Decrement tape
|
||||
// + ++*h; Increment tape
|
||||
// < --h; Move head left
|
||||
// > ++h; Move head right
|
||||
// [ while(*h) { Start loop
|
||||
// ] } End loop
|
||||
//
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
#include "BrainF.h"
|
||||
#include "llvm/Constants.h"
|
||||
#include "llvm/Instructions.h"
|
||||
#include "llvm/Intrinsics.h"
|
||||
#include "llvm/ADT/STLExtras.h"
|
||||
#include <iostream>
|
||||
using namespace llvm;
|
||||
|
||||
//Set the constants for naming
|
||||
const char *BrainF::tapereg = "tape";
|
||||
const char *BrainF::headreg = "head";
|
||||
const char *BrainF::label = "brainf";
|
||||
const char *BrainF::testreg = "test";
|
||||
|
||||
Module *BrainF::parse(std::istream *in1, int mem, CompileFlags cf,
|
||||
LLVMContext& Context) {
|
||||
in = in1;
|
||||
memtotal = mem;
|
||||
comflag = cf;
|
||||
|
||||
header(Context);
|
||||
readloop(0, 0, 0, Context);
|
||||
delete builder;
|
||||
return module;
|
||||
}
|
||||
|
||||
void BrainF::header(LLVMContext& C) {
|
||||
module = new Module("BrainF", C);
|
||||
|
||||
//Function prototypes
|
||||
|
||||
//declare void @llvm.memset.i32(i8 *, i8, i32, i32)
|
||||
const Type *Tys[] = { Type::getInt32Ty(C) };
|
||||
Function *memset_func = Intrinsic::getDeclaration(module, Intrinsic::memset,
|
||||
Tys, 1);
|
||||
|
||||
//declare i32 @getchar()
|
||||
getchar_func = cast<Function>(module->
|
||||
getOrInsertFunction("getchar", IntegerType::getInt32Ty(C), NULL));
|
||||
|
||||
//declare i32 @putchar(i32)
|
||||
putchar_func = cast<Function>(module->
|
||||
getOrInsertFunction("putchar", IntegerType::getInt32Ty(C),
|
||||
IntegerType::getInt32Ty(C), NULL));
|
||||
|
||||
|
||||
//Function header
|
||||
|
||||
//define void @brainf()
|
||||
brainf_func = cast<Function>(module->
|
||||
getOrInsertFunction("brainf", Type::getVoidTy(C), NULL));
|
||||
|
||||
builder = new IRBuilder<>(BasicBlock::Create(C, label, brainf_func));
|
||||
|
||||
//%arr = malloc i8, i32 %d
|
||||
ConstantInt *val_mem = ConstantInt::get(C, APInt(32, memtotal));
|
||||
BasicBlock* BB = builder->GetInsertBlock();
|
||||
const Type* IntPtrTy = IntegerType::getInt32Ty(C);
|
||||
const Type* Int8Ty = IntegerType::getInt8Ty(C);
|
||||
Constant* allocsize = ConstantExpr::getSizeOf(Int8Ty);
|
||||
allocsize = ConstantExpr::getTruncOrBitCast(allocsize, IntPtrTy);
|
||||
ptr_arr = CallInst::CreateMalloc(BB, IntPtrTy, Int8Ty, allocsize, val_mem,
|
||||
NULL, "arr");
|
||||
BB->getInstList().push_back(cast<Instruction>(ptr_arr));
|
||||
|
||||
//call void @llvm.memset.i32(i8 *%arr, i8 0, i32 %d, i32 1)
|
||||
{
|
||||
Value *memset_params[] = {
|
||||
ptr_arr,
|
||||
ConstantInt::get(C, APInt(8, 0)),
|
||||
val_mem,
|
||||
ConstantInt::get(C, APInt(32, 1))
|
||||
};
|
||||
|
||||
CallInst *memset_call = builder->
|
||||
CreateCall(memset_func, memset_params, array_endof(memset_params));
|
||||
memset_call->setTailCall(false);
|
||||
}
|
||||
|
||||
//%arrmax = getelementptr i8 *%arr, i32 %d
|
||||
if (comflag & flag_arraybounds) {
|
||||
ptr_arrmax = builder->
|
||||
CreateGEP(ptr_arr, ConstantInt::get(C, APInt(32, memtotal)), "arrmax");
|
||||
}
|
||||
|
||||
//%head.%d = getelementptr i8 *%arr, i32 %d
|
||||
curhead = builder->CreateGEP(ptr_arr,
|
||||
ConstantInt::get(C, APInt(32, memtotal/2)),
|
||||
headreg);
|
||||
|
||||
|
||||
|
||||
//Function footer
|
||||
|
||||
//brainf.end:
|
||||
endbb = BasicBlock::Create(C, label, brainf_func);
|
||||
|
||||
//call free(i8 *%arr)
|
||||
endbb->getInstList().push_back(CallInst::CreateFree(ptr_arr, endbb));
|
||||
|
||||
//ret void
|
||||
ReturnInst::Create(C, endbb);
|
||||
|
||||
|
||||
|
||||
//Error block for array out of bounds
|
||||
if (comflag & flag_arraybounds)
|
||||
{
|
||||
//@aberrormsg = internal constant [%d x i8] c"\00"
|
||||
Constant *msg_0 =
|
||||
ConstantArray::get(C, "Error: The head has left the tape.", true);
|
||||
|
||||
GlobalVariable *aberrormsg = new GlobalVariable(
|
||||
*module,
|
||||
msg_0->getType(),
|
||||
true,
|
||||
GlobalValue::InternalLinkage,
|
||||
msg_0,
|
||||
"aberrormsg");
|
||||
|
||||
//declare i32 @puts(i8 *)
|
||||
Function *puts_func = cast<Function>(module->
|
||||
getOrInsertFunction("puts", IntegerType::getInt32Ty(C),
|
||||
PointerType::getUnqual(IntegerType::getInt8Ty(C)), NULL));
|
||||
|
||||
//brainf.aberror:
|
||||
aberrorbb = BasicBlock::Create(C, label, brainf_func);
|
||||
|
||||
//call i32 @puts(i8 *getelementptr([%d x i8] *@aberrormsg, i32 0, i32 0))
|
||||
{
|
||||
Constant *zero_32 = Constant::getNullValue(IntegerType::getInt32Ty(C));
|
||||
|
||||
Constant *gep_params[] = {
|
||||
zero_32,
|
||||
zero_32
|
||||
};
|
||||
|
||||
Constant *msgptr = ConstantExpr::
|
||||
getGetElementPtr(aberrormsg, gep_params,
|
||||
array_lengthof(gep_params));
|
||||
|
||||
Value *puts_params[] = {
|
||||
msgptr
|
||||
};
|
||||
|
||||
CallInst *puts_call =
|
||||
CallInst::Create(puts_func,
|
||||
puts_params, array_endof(puts_params),
|
||||
"", aberrorbb);
|
||||
puts_call->setTailCall(false);
|
||||
}
|
||||
|
||||
//br label %brainf.end
|
||||
BranchInst::Create(endbb, aberrorbb);
|
||||
}
|
||||
}
|
||||
|
||||
void BrainF::readloop(PHINode *phi, BasicBlock *oldbb, BasicBlock *testbb,
|
||||
LLVMContext &C) {
|
||||
Symbol cursym = SYM_NONE;
|
||||
int curvalue = 0;
|
||||
Symbol nextsym = SYM_NONE;
|
||||
int nextvalue = 0;
|
||||
char c;
|
||||
int loop;
|
||||
int direction;
|
||||
|
||||
while(cursym != SYM_EOF && cursym != SYM_ENDLOOP) {
|
||||
// Write out commands
|
||||
switch(cursym) {
|
||||
case SYM_NONE:
|
||||
// Do nothing
|
||||
break;
|
||||
|
||||
case SYM_READ:
|
||||
{
|
||||
//%tape.%d = call i32 @getchar()
|
||||
CallInst *getchar_call = builder->CreateCall(getchar_func, tapereg);
|
||||
getchar_call->setTailCall(false);
|
||||
Value *tape_0 = getchar_call;
|
||||
|
||||
//%tape.%d = trunc i32 %tape.%d to i8
|
||||
Value *tape_1 = builder->
|
||||
CreateTrunc(tape_0, IntegerType::getInt8Ty(C), tapereg);
|
||||
|
||||
//store i8 %tape.%d, i8 *%head.%d
|
||||
builder->CreateStore(tape_1, curhead);
|
||||
}
|
||||
break;
|
||||
|
||||
case SYM_WRITE:
|
||||
{
|
||||
//%tape.%d = load i8 *%head.%d
|
||||
LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
|
||||
|
||||
//%tape.%d = sext i8 %tape.%d to i32
|
||||
Value *tape_1 = builder->
|
||||
CreateSExt(tape_0, IntegerType::getInt32Ty(C), tapereg);
|
||||
|
||||
//call i32 @putchar(i32 %tape.%d)
|
||||
Value *putchar_params[] = {
|
||||
tape_1
|
||||
};
|
||||
CallInst *putchar_call = builder->
|
||||
CreateCall(putchar_func,
|
||||
putchar_params, array_endof(putchar_params));
|
||||
putchar_call->setTailCall(false);
|
||||
}
|
||||
break;
|
||||
|
||||
case SYM_MOVE:
|
||||
{
|
||||
//%head.%d = getelementptr i8 *%head.%d, i32 %d
|
||||
curhead = builder->
|
||||
CreateGEP(curhead, ConstantInt::get(C, APInt(32, curvalue)),
|
||||
headreg);
|
||||
|
||||
//Error block for array out of bounds
|
||||
if (comflag & flag_arraybounds)
|
||||
{
|
||||
//%test.%d = icmp uge i8 *%head.%d, %arrmax
|
||||
Value *test_0 = builder->
|
||||
CreateICmpUGE(curhead, ptr_arrmax, testreg);
|
||||
|
||||
//%test.%d = icmp ult i8 *%head.%d, %arr
|
||||
Value *test_1 = builder->
|
||||
CreateICmpULT(curhead, ptr_arr, testreg);
|
||||
|
||||
//%test.%d = or i1 %test.%d, %test.%d
|
||||
Value *test_2 = builder->
|
||||
CreateOr(test_0, test_1, testreg);
|
||||
|
||||
//br i1 %test.%d, label %main.%d, label %main.%d
|
||||
BasicBlock *nextbb = BasicBlock::Create(C, label, brainf_func);
|
||||
builder->CreateCondBr(test_2, aberrorbb, nextbb);
|
||||
|
||||
//main.%d:
|
||||
builder->SetInsertPoint(nextbb);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case SYM_CHANGE:
|
||||
{
|
||||
//%tape.%d = load i8 *%head.%d
|
||||
LoadInst *tape_0 = builder->CreateLoad(curhead, tapereg);
|
||||
|
||||
//%tape.%d = add i8 %tape.%d, %d
|
||||
Value *tape_1 = builder->
|
||||
CreateAdd(tape_0, ConstantInt::get(C, APInt(8, curvalue)), tapereg);
|
||||
|
||||
//store i8 %tape.%d, i8 *%head.%d\n"
|
||||
builder->CreateStore(tape_1, curhead);
|
||||
}
|
||||
break;
|
||||
|
||||
case SYM_LOOP:
|
||||
{
|
||||
//br label %main.%d
|
||||
BasicBlock *testbb = BasicBlock::Create(C, label, brainf_func);
|
||||
builder->CreateBr(testbb);
|
||||
|
||||
//main.%d:
|
||||
BasicBlock *bb_0 = builder->GetInsertBlock();
|
||||
BasicBlock *bb_1 = BasicBlock::Create(C, label, brainf_func);
|
||||
builder->SetInsertPoint(bb_1);
|
||||
|
||||
// Make part of PHI instruction now, wait until end of loop to finish
|
||||
PHINode *phi_0 =
|
||||
PHINode::Create(PointerType::getUnqual(IntegerType::getInt8Ty(C)),
|
||||
headreg, testbb);
|
||||
phi_0->reserveOperandSpace(2);
|
||||
phi_0->addIncoming(curhead, bb_0);
|
||||
curhead = phi_0;
|
||||
|
||||
readloop(phi_0, bb_1, testbb, C);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
std::cerr << "Error: Unknown symbol.\n";
|
||||
abort();
|
||||
break;
|
||||
}
|
||||
|
||||
cursym = nextsym;
|
||||
curvalue = nextvalue;
|
||||
nextsym = SYM_NONE;
|
||||
|
||||
// Reading stdin loop
|
||||
loop = (cursym == SYM_NONE)
|
||||
|| (cursym == SYM_MOVE)
|
||||
|| (cursym == SYM_CHANGE);
|
||||
while(loop) {
|
||||
*in>>c;
|
||||
if (in->eof()) {
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_EOF;
|
||||
} else {
|
||||
nextsym = SYM_EOF;
|
||||
}
|
||||
loop = 0;
|
||||
} else {
|
||||
direction = 1;
|
||||
switch(c) {
|
||||
case '-':
|
||||
direction = -1;
|
||||
// Fall through
|
||||
|
||||
case '+':
|
||||
if (cursym == SYM_CHANGE) {
|
||||
curvalue += direction;
|
||||
// loop = 1
|
||||
} else {
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_CHANGE;
|
||||
curvalue = direction;
|
||||
// loop = 1
|
||||
} else {
|
||||
nextsym = SYM_CHANGE;
|
||||
nextvalue = direction;
|
||||
loop = 0;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case '<':
|
||||
direction = -1;
|
||||
// Fall through
|
||||
|
||||
case '>':
|
||||
if (cursym == SYM_MOVE) {
|
||||
curvalue += direction;
|
||||
// loop = 1
|
||||
} else {
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_MOVE;
|
||||
curvalue = direction;
|
||||
// loop = 1
|
||||
} else {
|
||||
nextsym = SYM_MOVE;
|
||||
nextvalue = direction;
|
||||
loop = 0;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case ',':
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_READ;
|
||||
} else {
|
||||
nextsym = SYM_READ;
|
||||
}
|
||||
loop = 0;
|
||||
break;
|
||||
|
||||
case '.':
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_WRITE;
|
||||
} else {
|
||||
nextsym = SYM_WRITE;
|
||||
}
|
||||
loop = 0;
|
||||
break;
|
||||
|
||||
case '[':
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_LOOP;
|
||||
} else {
|
||||
nextsym = SYM_LOOP;
|
||||
}
|
||||
loop = 0;
|
||||
break;
|
||||
|
||||
case ']':
|
||||
if (cursym == SYM_NONE) {
|
||||
cursym = SYM_ENDLOOP;
|
||||
} else {
|
||||
nextsym = SYM_ENDLOOP;
|
||||
}
|
||||
loop = 0;
|
||||
break;
|
||||
|
||||
// Ignore other characters
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cursym == SYM_ENDLOOP) {
|
||||
if (!phi) {
|
||||
std::cerr << "Error: Extra ']'\n";
|
||||
abort();
|
||||
}
|
||||
|
||||
// Write loop test
|
||||
{
|
||||
//br label %main.%d
|
||||
builder->CreateBr(testbb);
|
||||
|
||||
//main.%d:
|
||||
|
||||
//%head.%d = phi i8 *[%head.%d, %main.%d], [%head.%d, %main.%d]
|
||||
//Finish phi made at beginning of loop
|
||||
phi->addIncoming(curhead, builder->GetInsertBlock());
|
||||
Value *head_0 = phi;
|
||||
|
||||
//%tape.%d = load i8 *%head.%d
|
||||
LoadInst *tape_0 = new LoadInst(head_0, tapereg, testbb);
|
||||
|
||||
//%test.%d = icmp eq i8 %tape.%d, 0
|
||||
ICmpInst *test_0 = new ICmpInst(*testbb, ICmpInst::ICMP_EQ, tape_0,
|
||||
ConstantInt::get(C, APInt(8, 0)), testreg);
|
||||
|
||||
//br i1 %test.%d, label %main.%d, label %main.%d
|
||||
BasicBlock *bb_0 = BasicBlock::Create(C, label, brainf_func);
|
||||
BranchInst::Create(bb_0, oldbb, test_0, testbb);
|
||||
|
||||
//main.%d:
|
||||
builder->SetInsertPoint(bb_0);
|
||||
|
||||
//%head.%d = phi i8 *[%head.%d, %main.%d]
|
||||
PHINode *phi_1 = builder->
|
||||
CreatePHI(PointerType::getUnqual(IntegerType::getInt8Ty(C)), headreg);
|
||||
phi_1->reserveOperandSpace(1);
|
||||
phi_1->addIncoming(head_0, testbb);
|
||||
curhead = phi_1;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//End of the program, so go to return block
|
||||
builder->CreateBr(endbb);
|
||||
|
||||
if (phi) {
|
||||
std::cerr << "Error: Missing ']'\n";
|
||||
abort();
|
||||
}
|
||||
}
|
@ -1,94 +0,0 @@
|
||||
//===-- BrainF.h - BrainF compiler class ----------------------*- C++ -*-===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file is distributed under the University of Illinois Open Source
|
||||
// License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===--------------------------------------------------------------------===//
|
||||
//
|
||||
// This class stores the data for the BrainF compiler so it doesn't have
|
||||
// to pass all of it around. The main method is parse.
|
||||
//
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
#ifndef BRAINF_H
|
||||
#define BRAINF_H
|
||||
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/Support/IRBuilder.h"
|
||||
|
||||
using namespace llvm;
|
||||
|
||||
/// This class provides a parser for the BrainF language.
|
||||
/// The class itself is made to store values during
|
||||
/// parsing so they don't have to be passed around
|
||||
/// as much.
|
||||
class BrainF {
|
||||
public:
|
||||
/// Options for how BrainF should compile
|
||||
enum CompileFlags {
|
||||
flag_off = 0,
|
||||
flag_arraybounds = 1
|
||||
};
|
||||
|
||||
/// This is the main method. It parses BrainF from in1
|
||||
/// and returns the module with a function
|
||||
/// void brainf()
|
||||
/// containing the resulting code.
|
||||
/// On error, it calls abort.
|
||||
/// The caller must delete the returned module.
|
||||
Module *parse(std::istream *in1, int mem, CompileFlags cf,
|
||||
LLVMContext& C);
|
||||
|
||||
protected:
|
||||
/// The different symbols in the BrainF language
|
||||
enum Symbol {
|
||||
SYM_NONE,
|
||||
SYM_READ,
|
||||
SYM_WRITE,
|
||||
SYM_MOVE,
|
||||
SYM_CHANGE,
|
||||
SYM_LOOP,
|
||||
SYM_ENDLOOP,
|
||||
SYM_EOF
|
||||
};
|
||||
|
||||
/// Names of the different parts of the language.
|
||||
/// Tape is used for reading and writing the tape.
|
||||
/// headreg is used for the position of the head.
|
||||
/// label is used for the labels for the BasicBlocks.
|
||||
/// testreg is used for testing the loop exit condition.
|
||||
static const char *tapereg;
|
||||
static const char *headreg;
|
||||
static const char *label;
|
||||
static const char *testreg;
|
||||
|
||||
/// Put the brainf function preamble and other fixed pieces of code
|
||||
void header(LLVMContext& C);
|
||||
|
||||
/// The main loop for parsing. It calls itself recursively
|
||||
/// to handle the depth of nesting of "[]".
|
||||
void readloop(PHINode *phi, BasicBlock *oldbb,
|
||||
BasicBlock *testbb, LLVMContext &Context);
|
||||
|
||||
/// Constants during parsing
|
||||
int memtotal;
|
||||
CompileFlags comflag;
|
||||
std::istream *in;
|
||||
Module *module;
|
||||
Function *brainf_func;
|
||||
Function *getchar_func;
|
||||
Function *putchar_func;
|
||||
Value *ptr_arr;
|
||||
Value *ptr_arrmax;
|
||||
BasicBlock *endbb;
|
||||
BasicBlock *aberrorbb;
|
||||
|
||||
/// Variables
|
||||
IRBuilder<> *builder;
|
||||
Value *curhead;
|
||||
};
|
||||
|
||||
#endif
|
@ -1,160 +0,0 @@
|
||||
//===-- BrainFDriver.cpp - BrainF compiler driver -----------------------===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file is distributed under the University of Illinois Open Source
|
||||
// License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===--------------------------------------------------------------------===//
|
||||
//
|
||||
// This program converts the BrainF language into LLVM assembly,
|
||||
// which it can then run using the JIT or output as BitCode.
|
||||
//
|
||||
// This implementation has a tape of 65536 bytes,
|
||||
// with the head starting in the middle.
|
||||
// Range checking is off by default, so be careful.
|
||||
// It can be enabled with -abc.
|
||||
//
|
||||
// Use:
|
||||
// ./BrainF -jit prog.bf #Run program now
|
||||
// ./BrainF -jit -abc prog.bf #Run program now safely
|
||||
// ./BrainF prog.bf #Write as BitCode
|
||||
//
|
||||
// lli prog.bf.bc #Run generated BitCode
|
||||
// llvm-ld -native -o=prog prog.bf.bc #Compile BitCode into native executable
|
||||
//
|
||||
//===--------------------------------------------------------------------===//
|
||||
|
||||
#include "BrainF.h"
|
||||
#include "llvm/Constants.h"
|
||||
#include "llvm/Analysis/Verifier.h"
|
||||
#include "llvm/Bitcode/ReaderWriter.h"
|
||||
#include "llvm/ExecutionEngine/GenericValue.h"
|
||||
#include "llvm/ExecutionEngine/JIT.h"
|
||||
#include "llvm/Target/TargetSelect.h"
|
||||
#include "llvm/Support/CommandLine.h"
|
||||
#include "llvm/Support/ManagedStatic.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
using namespace llvm;
|
||||
|
||||
//Command line options
|
||||
|
||||
static cl::opt<std::string>
|
||||
InputFilename(cl::Positional, cl::desc("<input brainf>"));
|
||||
|
||||
static cl::opt<std::string>
|
||||
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
|
||||
|
||||
static cl::opt<bool>
|
||||
ArrayBoundsChecking("abc", cl::desc("Enable array bounds checking"));
|
||||
|
||||
static cl::opt<bool>
|
||||
JIT("jit", cl::desc("Run program Just-In-Time"));
|
||||
|
||||
|
||||
//Add main function so can be fully compiled
|
||||
void addMainFunction(Module *mod) {
|
||||
//define i32 @main(i32 %argc, i8 **%argv)
|
||||
Function *main_func = cast<Function>(mod->
|
||||
getOrInsertFunction("main", IntegerType::getInt32Ty(mod->getContext()),
|
||||
IntegerType::getInt32Ty(mod->getContext()),
|
||||
PointerType::getUnqual(PointerType::getUnqual(
|
||||
IntegerType::getInt8Ty(mod->getContext()))), NULL));
|
||||
{
|
||||
Function::arg_iterator args = main_func->arg_begin();
|
||||
Value *arg_0 = args++;
|
||||
arg_0->setName("argc");
|
||||
Value *arg_1 = args++;
|
||||
arg_1->setName("argv");
|
||||
}
|
||||
|
||||
//main.0:
|
||||
BasicBlock *bb = BasicBlock::Create(mod->getContext(), "main.0", main_func);
|
||||
|
||||
//call void @brainf()
|
||||
{
|
||||
CallInst *brainf_call = CallInst::Create(mod->getFunction("brainf"),
|
||||
"", bb);
|
||||
brainf_call->setTailCall(false);
|
||||
}
|
||||
|
||||
//ret i32 0
|
||||
ReturnInst::Create(mod->getContext(),
|
||||
ConstantInt::get(mod->getContext(), APInt(32, 0)), bb);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
cl::ParseCommandLineOptions(argc, argv, " BrainF compiler\n");
|
||||
|
||||
LLVMContext &Context = getGlobalContext();
|
||||
|
||||
if (InputFilename == "") {
|
||||
errs() << "Error: You must specify the filename of the program to "
|
||||
"be compiled. Use --help to see the options.\n";
|
||||
abort();
|
||||
}
|
||||
|
||||
//Get the output stream
|
||||
raw_ostream *out = &outs();
|
||||
if (!JIT) {
|
||||
if (OutputFilename == "") {
|
||||
std::string base = InputFilename;
|
||||
if (InputFilename == "-") { base = "a"; }
|
||||
|
||||
// Use default filename.
|
||||
OutputFilename = base+".bc";
|
||||
}
|
||||
if (OutputFilename != "-") {
|
||||
std::string ErrInfo;
|
||||
out = new raw_fd_ostream(OutputFilename.c_str(), ErrInfo,
|
||||
raw_fd_ostream::F_Binary);
|
||||
}
|
||||
}
|
||||
|
||||
//Get the input stream
|
||||
std::istream *in = &std::cin;
|
||||
if (InputFilename != "-")
|
||||
in = new std::ifstream(InputFilename.c_str());
|
||||
|
||||
//Gather the compile flags
|
||||
BrainF::CompileFlags cf = BrainF::flag_off;
|
||||
if (ArrayBoundsChecking)
|
||||
cf = BrainF::CompileFlags(cf | BrainF::flag_arraybounds);
|
||||
|
||||
//Read the BrainF program
|
||||
BrainF bf;
|
||||
Module *mod = bf.parse(in, 65536, cf, Context); //64 KiB
|
||||
if (in != &std::cin)
|
||||
delete in;
|
||||
addMainFunction(mod);
|
||||
|
||||
//Verify generated code
|
||||
if (verifyModule(*mod)) {
|
||||
errs() << "Error: module failed verification. This shouldn't happen.\n";
|
||||
abort();
|
||||
}
|
||||
|
||||
//Write it out
|
||||
if (JIT) {
|
||||
InitializeNativeTarget();
|
||||
|
||||
outs() << "------- Running JIT -------\n";
|
||||
ExecutionEngine *ee = EngineBuilder(mod).create();
|
||||
std::vector<GenericValue> args;
|
||||
Function *brainf_func = mod->getFunction("brainf");
|
||||
GenericValue gv = ee->runFunction(brainf_func, args);
|
||||
} else {
|
||||
WriteBitcodeToFile(mod, *out);
|
||||
}
|
||||
|
||||
//Clean up
|
||||
if (out != &outs())
|
||||
delete out;
|
||||
delete mod;
|
||||
|
||||
llvm_shutdown();
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS jit bitwriter nativecodegen interpreter)
|
||||
|
||||
add_llvm_example(BrainF
|
||||
BrainF.cpp
|
||||
BrainFDriver.cpp
|
||||
)
|
@ -1,15 +0,0 @@
|
||||
##===- examples/BrainF/Makefile ----------------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../..
|
||||
TOOLNAME = BrainF
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
LINK_COMPONENTS := jit bitwriter nativecodegen interpreter
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,16 +0,0 @@
|
||||
add_subdirectory(BrainF)
|
||||
add_subdirectory(Fibonacci)
|
||||
add_subdirectory(HowToUseJIT)
|
||||
add_subdirectory(Kaleidoscope)
|
||||
add_subdirectory(ModuleMaker)
|
||||
|
||||
if( NOT WIN32 )
|
||||
add_subdirectory(ExceptionDemo)
|
||||
endif()
|
||||
|
||||
include(CheckIncludeFile)
|
||||
check_include_file(pthread.h HAVE_PTHREAD_H)
|
||||
|
||||
if( HAVE_PTHREAD_H )
|
||||
add_subdirectory(ParallelJIT)
|
||||
endif( HAVE_PTHREAD_H )
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS jit nativecodegen)
|
||||
|
||||
add_llvm_example(ExceptionDemo
|
||||
ExceptionDemo.cpp
|
||||
)
|
File diff suppressed because it is too large
Load Diff
@ -1,16 +0,0 @@
|
||||
##===- examples/ExceptionDemo/Makefile --------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===---------------------------------------------------------------------===##
|
||||
LEVEL = ../..
|
||||
TOOLNAME = ExceptionDemo
|
||||
EXAMPLE_TOOL = 1
|
||||
REQUIRES_EH = 1
|
||||
|
||||
LINK_COMPONENTS := jit interpreter nativecodegen
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS jit interpreter nativecodegen)
|
||||
|
||||
add_llvm_example(Fibonacci
|
||||
fibonacci.cpp
|
||||
)
|
@ -1,17 +0,0 @@
|
||||
##===- examples/Fibonacci/Makefile -------------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL = ../..
|
||||
TOOLNAME = Fibonacci
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
# Link in JIT support
|
||||
LINK_COMPONENTS := jit interpreter nativecodegen
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,131 +0,0 @@
|
||||
//===--- examples/Fibonacci/fibonacci.cpp - An example use of the JIT -----===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file is distributed under the University of Illinois Open Source
|
||||
// License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This small program provides an example of how to build quickly a small module
|
||||
// with function Fibonacci and execute it with the JIT.
|
||||
//
|
||||
// The goal of this snippet is to create in the memory the LLVM module
|
||||
// consisting of one function as follow:
|
||||
//
|
||||
// int fib(int x) {
|
||||
// if(x<=2) return 1;
|
||||
// return fib(x-1)+fib(x-2);
|
||||
// }
|
||||
//
|
||||
// Once we have this, we compile the module via JIT, then execute the `fib'
|
||||
// function and return result to a driver, i.e. to a "host program".
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/Constants.h"
|
||||
#include "llvm/Instructions.h"
|
||||
#include "llvm/Analysis/Verifier.h"
|
||||
#include "llvm/ExecutionEngine/JIT.h"
|
||||
#include "llvm/ExecutionEngine/Interpreter.h"
|
||||
#include "llvm/ExecutionEngine/GenericValue.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
#include "llvm/Target/TargetSelect.h"
|
||||
using namespace llvm;
|
||||
|
||||
static Function *CreateFibFunction(Module *M, LLVMContext &Context) {
|
||||
// Create the fib function and insert it into module M. This function is said
|
||||
// to return an int and take an int parameter.
|
||||
Function *FibF =
|
||||
cast<Function>(M->getOrInsertFunction("fib", Type::getInt32Ty(Context),
|
||||
Type::getInt32Ty(Context),
|
||||
(Type *)0));
|
||||
|
||||
// Add a basic block to the function.
|
||||
BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", FibF);
|
||||
|
||||
// Get pointers to the constants.
|
||||
Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
|
||||
Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
|
||||
|
||||
// Get pointer to the integer argument of the add1 function...
|
||||
Argument *ArgX = FibF->arg_begin(); // Get the arg.
|
||||
ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
|
||||
|
||||
// Create the true_block.
|
||||
BasicBlock *RetBB = BasicBlock::Create(Context, "return", FibF);
|
||||
// Create an exit block.
|
||||
BasicBlock* RecurseBB = BasicBlock::Create(Context, "recurse", FibF);
|
||||
|
||||
// Create the "if (arg <= 2) goto exitbb"
|
||||
Value *CondInst = new ICmpInst(*BB, ICmpInst::ICMP_SLE, ArgX, Two, "cond");
|
||||
BranchInst::Create(RetBB, RecurseBB, CondInst, BB);
|
||||
|
||||
// Create: ret int 1
|
||||
ReturnInst::Create(Context, One, RetBB);
|
||||
|
||||
// create fib(x-1)
|
||||
Value *Sub = BinaryOperator::CreateSub(ArgX, One, "arg", RecurseBB);
|
||||
CallInst *CallFibX1 = CallInst::Create(FibF, Sub, "fibx1", RecurseBB);
|
||||
CallFibX1->setTailCall();
|
||||
|
||||
// create fib(x-2)
|
||||
Sub = BinaryOperator::CreateSub(ArgX, Two, "arg", RecurseBB);
|
||||
CallInst *CallFibX2 = CallInst::Create(FibF, Sub, "fibx2", RecurseBB);
|
||||
CallFibX2->setTailCall();
|
||||
|
||||
|
||||
// fib(x-1)+fib(x-2)
|
||||
Value *Sum = BinaryOperator::CreateAdd(CallFibX1, CallFibX2,
|
||||
"addresult", RecurseBB);
|
||||
|
||||
// Create the return instruction and add it to the basic block
|
||||
ReturnInst::Create(Context, Sum, RecurseBB);
|
||||
|
||||
return FibF;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int n = argc > 1 ? atol(argv[1]) : 24;
|
||||
|
||||
InitializeNativeTarget();
|
||||
LLVMContext Context;
|
||||
|
||||
// Create some module to put our function into it.
|
||||
Module *M = new Module("test", Context);
|
||||
|
||||
// We are about to create the "fib" function:
|
||||
Function *FibF = CreateFibFunction(M, Context);
|
||||
|
||||
// Now we going to create JIT
|
||||
std::string errStr;
|
||||
ExecutionEngine *EE = EngineBuilder(M).setErrorStr(&errStr).setEngineKind(EngineKind::JIT).create();
|
||||
|
||||
if (!EE) {
|
||||
errs() << argv[0] << ": Failed to construct ExecutionEngine: " << errStr << "\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
errs() << "verifying... ";
|
||||
if (verifyModule(*M)) {
|
||||
errs() << argv[0] << ": Error constructing function!\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
errs() << "OK\n";
|
||||
errs() << "We just constructed this LLVM module:\n\n---------\n" << *M;
|
||||
errs() << "---------\nstarting fibonacci(" << n << ") with JIT...\n";
|
||||
|
||||
// Call the Fibonacci function with argument n:
|
||||
std::vector<GenericValue> Args(1);
|
||||
Args[0].IntVal = APInt(32, n);
|
||||
GenericValue GV = EE->runFunction(FibF, Args);
|
||||
|
||||
// import result of execution
|
||||
outs() << "Result: " << GV.IntVal << "\n";
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS jit interpreter nativecodegen)
|
||||
|
||||
add_llvm_example(HowToUseJIT
|
||||
HowToUseJIT.cpp
|
||||
)
|
@ -1,124 +0,0 @@
|
||||
//===-- examples/HowToUseJIT/HowToUseJIT.cpp - An example use of the JIT --===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file is distributed under the University of Illinois Open Source
|
||||
// License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This small program provides an example of how to quickly build a small
|
||||
// module with two functions and execute it with the JIT.
|
||||
//
|
||||
// Goal:
|
||||
// The goal of this snippet is to create in the memory
|
||||
// the LLVM module consisting of two functions as follow:
|
||||
//
|
||||
// int add1(int x) {
|
||||
// return x+1;
|
||||
// }
|
||||
//
|
||||
// int foo() {
|
||||
// return add1(10);
|
||||
// }
|
||||
//
|
||||
// then compile the module via JIT, then execute the `foo'
|
||||
// function and return result to a driver, i.e. to a "host program".
|
||||
//
|
||||
// Some remarks and questions:
|
||||
//
|
||||
// - could we invoke some code using noname functions too?
|
||||
// e.g. evaluate "foo()+foo()" without fears to introduce
|
||||
// conflict of temporary function name with some real
|
||||
// existing function name?
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/Constants.h"
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/Instructions.h"
|
||||
#include "llvm/ExecutionEngine/JIT.h"
|
||||
#include "llvm/ExecutionEngine/Interpreter.h"
|
||||
#include "llvm/ExecutionEngine/GenericValue.h"
|
||||
#include "llvm/Target/TargetSelect.h"
|
||||
#include "llvm/Support/ManagedStatic.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
using namespace llvm;
|
||||
|
||||
int main() {
|
||||
|
||||
InitializeNativeTarget();
|
||||
|
||||
LLVMContext Context;
|
||||
|
||||
// Create some module to put our function into it.
|
||||
Module *M = new Module("test", Context);
|
||||
|
||||
// Create the add1 function entry and insert this entry into module M. The
|
||||
// function will have a return type of "int" and take an argument of "int".
|
||||
// The '0' terminates the list of argument types.
|
||||
Function *Add1F =
|
||||
cast<Function>(M->getOrInsertFunction("add1", Type::getInt32Ty(Context),
|
||||
Type::getInt32Ty(Context),
|
||||
(Type *)0));
|
||||
|
||||
// Add a basic block to the function. As before, it automatically inserts
|
||||
// because of the last argument.
|
||||
BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", Add1F);
|
||||
|
||||
// Get pointers to the constant `1'.
|
||||
Value *One = ConstantInt::get(Type::getInt32Ty(Context), 1);
|
||||
|
||||
// Get pointers to the integer argument of the add1 function...
|
||||
assert(Add1F->arg_begin() != Add1F->arg_end()); // Make sure there's an arg
|
||||
Argument *ArgX = Add1F->arg_begin(); // Get the arg
|
||||
ArgX->setName("AnArg"); // Give it a nice symbolic name for fun.
|
||||
|
||||
// Create the add instruction, inserting it into the end of BB.
|
||||
Instruction *Add = BinaryOperator::CreateAdd(One, ArgX, "addresult", BB);
|
||||
|
||||
// Create the return instruction and add it to the basic block
|
||||
ReturnInst::Create(Context, Add, BB);
|
||||
|
||||
// Now, function add1 is ready.
|
||||
|
||||
|
||||
// Now we going to create function `foo', which returns an int and takes no
|
||||
// arguments.
|
||||
Function *FooF =
|
||||
cast<Function>(M->getOrInsertFunction("foo", Type::getInt32Ty(Context),
|
||||
(Type *)0));
|
||||
|
||||
// Add a basic block to the FooF function.
|
||||
BB = BasicBlock::Create(Context, "EntryBlock", FooF);
|
||||
|
||||
// Get pointers to the constant `10'.
|
||||
Value *Ten = ConstantInt::get(Type::getInt32Ty(Context), 10);
|
||||
|
||||
// Pass Ten to the call call:
|
||||
CallInst *Add1CallRes = CallInst::Create(Add1F, Ten, "add1", BB);
|
||||
Add1CallRes->setTailCall(true);
|
||||
|
||||
// Create the return instruction and add it to the basic block.
|
||||
ReturnInst::Create(Context, Add1CallRes, BB);
|
||||
|
||||
// Now we create the JIT.
|
||||
ExecutionEngine* EE = EngineBuilder(M).create();
|
||||
|
||||
outs() << "We just constructed this LLVM module:\n\n" << *M;
|
||||
outs() << "\n\nRunning foo: ";
|
||||
outs().flush();
|
||||
|
||||
// Call the `foo' function with no arguments:
|
||||
std::vector<GenericValue> noargs;
|
||||
GenericValue gv = EE->runFunction(FooF, noargs);
|
||||
|
||||
// Import result of execution:
|
||||
outs() << "Result: " << gv.IntVal << "\n";
|
||||
EE->freeMachineCodeForFunction(FooF);
|
||||
delete EE;
|
||||
llvm_shutdown();
|
||||
return 0;
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
##===- examples/HowToUseJIT/Makefile -----------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../..
|
||||
TOOLNAME = HowToUseJIT
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
LINK_COMPONENTS := jit interpreter nativecodegen
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,6 +0,0 @@
|
||||
add_subdirectory(Chapter2)
|
||||
add_subdirectory(Chapter3)
|
||||
add_subdirectory(Chapter4)
|
||||
add_subdirectory(Chapter5)
|
||||
add_subdirectory(Chapter6)
|
||||
add_subdirectory(Chapter7)
|
@ -1,3 +0,0 @@
|
||||
add_llvm_example(Kaleidoscope-Ch2
|
||||
toy.cpp
|
||||
)
|
@ -1,13 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Chapter2/Makefile -------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../../..
|
||||
TOOLNAME = Kaleidoscope-Ch2
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,398 +0,0 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Lexer
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
|
||||
// of these for known things.
|
||||
enum Token {
|
||||
tok_eof = -1,
|
||||
|
||||
// commands
|
||||
tok_def = -2, tok_extern = -3,
|
||||
|
||||
// primary
|
||||
tok_identifier = -4, tok_number = -5
|
||||
};
|
||||
|
||||
static std::string IdentifierStr; // Filled in if tok_identifier
|
||||
static double NumVal; // Filled in if tok_number
|
||||
|
||||
/// gettok - Return the next token from standard input.
|
||||
static int gettok() {
|
||||
static int LastChar = ' ';
|
||||
|
||||
// Skip any whitespace.
|
||||
while (isspace(LastChar))
|
||||
LastChar = getchar();
|
||||
|
||||
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
|
||||
IdentifierStr = LastChar;
|
||||
while (isalnum((LastChar = getchar())))
|
||||
IdentifierStr += LastChar;
|
||||
|
||||
if (IdentifierStr == "def") return tok_def;
|
||||
if (IdentifierStr == "extern") return tok_extern;
|
||||
return tok_identifier;
|
||||
}
|
||||
|
||||
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
|
||||
std::string NumStr;
|
||||
do {
|
||||
NumStr += LastChar;
|
||||
LastChar = getchar();
|
||||
} while (isdigit(LastChar) || LastChar == '.');
|
||||
|
||||
NumVal = strtod(NumStr.c_str(), 0);
|
||||
return tok_number;
|
||||
}
|
||||
|
||||
if (LastChar == '#') {
|
||||
// Comment until end of line.
|
||||
do LastChar = getchar();
|
||||
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
|
||||
|
||||
if (LastChar != EOF)
|
||||
return gettok();
|
||||
}
|
||||
|
||||
// Check for end of file. Don't eat the EOF.
|
||||
if (LastChar == EOF)
|
||||
return tok_eof;
|
||||
|
||||
// Otherwise, just return the character as its ascii value.
|
||||
int ThisChar = LastChar;
|
||||
LastChar = getchar();
|
||||
return ThisChar;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Abstract Syntax Tree (aka Parse Tree)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// ExprAST - Base class for all expression nodes.
|
||||
class ExprAST {
|
||||
public:
|
||||
virtual ~ExprAST() {}
|
||||
};
|
||||
|
||||
/// NumberExprAST - Expression class for numeric literals like "1.0".
|
||||
class NumberExprAST : public ExprAST {
|
||||
double Val;
|
||||
public:
|
||||
NumberExprAST(double val) : Val(val) {}
|
||||
};
|
||||
|
||||
/// VariableExprAST - Expression class for referencing a variable, like "a".
|
||||
class VariableExprAST : public ExprAST {
|
||||
std::string Name;
|
||||
public:
|
||||
VariableExprAST(const std::string &name) : Name(name) {}
|
||||
};
|
||||
|
||||
/// BinaryExprAST - Expression class for a binary operator.
|
||||
class BinaryExprAST : public ExprAST {
|
||||
char Op;
|
||||
ExprAST *LHS, *RHS;
|
||||
public:
|
||||
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
|
||||
: Op(op), LHS(lhs), RHS(rhs) {}
|
||||
};
|
||||
|
||||
/// CallExprAST - Expression class for function calls.
|
||||
class CallExprAST : public ExprAST {
|
||||
std::string Callee;
|
||||
std::vector<ExprAST*> Args;
|
||||
public:
|
||||
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
|
||||
: Callee(callee), Args(args) {}
|
||||
};
|
||||
|
||||
/// PrototypeAST - This class represents the "prototype" for a function,
|
||||
/// which captures its name, and its argument names (thus implicitly the number
|
||||
/// of arguments the function takes).
|
||||
class PrototypeAST {
|
||||
std::string Name;
|
||||
std::vector<std::string> Args;
|
||||
public:
|
||||
PrototypeAST(const std::string &name, const std::vector<std::string> &args)
|
||||
: Name(name), Args(args) {}
|
||||
|
||||
};
|
||||
|
||||
/// FunctionAST - This class represents a function definition itself.
|
||||
class FunctionAST {
|
||||
PrototypeAST *Proto;
|
||||
ExprAST *Body;
|
||||
public:
|
||||
FunctionAST(PrototypeAST *proto, ExprAST *body)
|
||||
: Proto(proto), Body(body) {}
|
||||
|
||||
};
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Parser
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
|
||||
/// token the parser is looking at. getNextToken reads another token from the
|
||||
/// lexer and updates CurTok with its results.
|
||||
static int CurTok;
|
||||
static int getNextToken() {
|
||||
return CurTok = gettok();
|
||||
}
|
||||
|
||||
/// BinopPrecedence - This holds the precedence for each binary operator that is
|
||||
/// defined.
|
||||
static std::map<char, int> BinopPrecedence;
|
||||
|
||||
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
|
||||
static int GetTokPrecedence() {
|
||||
if (!isascii(CurTok))
|
||||
return -1;
|
||||
|
||||
// Make sure it's a declared binop.
|
||||
int TokPrec = BinopPrecedence[CurTok];
|
||||
if (TokPrec <= 0) return -1;
|
||||
return TokPrec;
|
||||
}
|
||||
|
||||
/// Error* - These are little helper functions for error handling.
|
||||
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
|
||||
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
|
||||
FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
static ExprAST *ParseExpression();
|
||||
|
||||
/// identifierexpr
|
||||
/// ::= identifier
|
||||
/// ::= identifier '(' expression* ')'
|
||||
static ExprAST *ParseIdentifierExpr() {
|
||||
std::string IdName = IdentifierStr;
|
||||
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '(') // Simple variable ref.
|
||||
return new VariableExprAST(IdName);
|
||||
|
||||
// Call.
|
||||
getNextToken(); // eat (
|
||||
std::vector<ExprAST*> Args;
|
||||
if (CurTok != ')') {
|
||||
while (1) {
|
||||
ExprAST *Arg = ParseExpression();
|
||||
if (!Arg) return 0;
|
||||
Args.push_back(Arg);
|
||||
|
||||
if (CurTok == ')') break;
|
||||
|
||||
if (CurTok != ',')
|
||||
return Error("Expected ')' or ',' in argument list");
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
// Eat the ')'.
|
||||
getNextToken();
|
||||
|
||||
return new CallExprAST(IdName, Args);
|
||||
}
|
||||
|
||||
/// numberexpr ::= number
|
||||
static ExprAST *ParseNumberExpr() {
|
||||
ExprAST *Result = new NumberExprAST(NumVal);
|
||||
getNextToken(); // consume the number
|
||||
return Result;
|
||||
}
|
||||
|
||||
/// parenexpr ::= '(' expression ')'
|
||||
static ExprAST *ParseParenExpr() {
|
||||
getNextToken(); // eat (.
|
||||
ExprAST *V = ParseExpression();
|
||||
if (!V) return 0;
|
||||
|
||||
if (CurTok != ')')
|
||||
return Error("expected ')'");
|
||||
getNextToken(); // eat ).
|
||||
return V;
|
||||
}
|
||||
|
||||
/// primary
|
||||
/// ::= identifierexpr
|
||||
/// ::= numberexpr
|
||||
/// ::= parenexpr
|
||||
static ExprAST *ParsePrimary() {
|
||||
switch (CurTok) {
|
||||
default: return Error("unknown token when expecting an expression");
|
||||
case tok_identifier: return ParseIdentifierExpr();
|
||||
case tok_number: return ParseNumberExpr();
|
||||
case '(': return ParseParenExpr();
|
||||
}
|
||||
}
|
||||
|
||||
/// binoprhs
|
||||
/// ::= ('+' primary)*
|
||||
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
|
||||
// If this is a binop, find its precedence.
|
||||
while (1) {
|
||||
int TokPrec = GetTokPrecedence();
|
||||
|
||||
// If this is a binop that binds at least as tightly as the current binop,
|
||||
// consume it, otherwise we are done.
|
||||
if (TokPrec < ExprPrec)
|
||||
return LHS;
|
||||
|
||||
// Okay, we know this is a binop.
|
||||
int BinOp = CurTok;
|
||||
getNextToken(); // eat binop
|
||||
|
||||
// Parse the primary expression after the binary operator.
|
||||
ExprAST *RHS = ParsePrimary();
|
||||
if (!RHS) return 0;
|
||||
|
||||
// If BinOp binds less tightly with RHS than the operator after RHS, let
|
||||
// the pending operator take RHS as its LHS.
|
||||
int NextPrec = GetTokPrecedence();
|
||||
if (TokPrec < NextPrec) {
|
||||
RHS = ParseBinOpRHS(TokPrec+1, RHS);
|
||||
if (RHS == 0) return 0;
|
||||
}
|
||||
|
||||
// Merge LHS/RHS.
|
||||
LHS = new BinaryExprAST(BinOp, LHS, RHS);
|
||||
}
|
||||
}
|
||||
|
||||
/// expression
|
||||
/// ::= primary binoprhs
|
||||
///
|
||||
static ExprAST *ParseExpression() {
|
||||
ExprAST *LHS = ParsePrimary();
|
||||
if (!LHS) return 0;
|
||||
|
||||
return ParseBinOpRHS(0, LHS);
|
||||
}
|
||||
|
||||
/// prototype
|
||||
/// ::= id '(' id* ')'
|
||||
static PrototypeAST *ParsePrototype() {
|
||||
if (CurTok != tok_identifier)
|
||||
return ErrorP("Expected function name in prototype");
|
||||
|
||||
std::string FnName = IdentifierStr;
|
||||
getNextToken();
|
||||
|
||||
if (CurTok != '(')
|
||||
return ErrorP("Expected '(' in prototype");
|
||||
|
||||
std::vector<std::string> ArgNames;
|
||||
while (getNextToken() == tok_identifier)
|
||||
ArgNames.push_back(IdentifierStr);
|
||||
if (CurTok != ')')
|
||||
return ErrorP("Expected ')' in prototype");
|
||||
|
||||
// success.
|
||||
getNextToken(); // eat ')'.
|
||||
|
||||
return new PrototypeAST(FnName, ArgNames);
|
||||
}
|
||||
|
||||
/// definition ::= 'def' prototype expression
|
||||
static FunctionAST *ParseDefinition() {
|
||||
getNextToken(); // eat def.
|
||||
PrototypeAST *Proto = ParsePrototype();
|
||||
if (Proto == 0) return 0;
|
||||
|
||||
if (ExprAST *E = ParseExpression())
|
||||
return new FunctionAST(Proto, E);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// toplevelexpr ::= expression
|
||||
static FunctionAST *ParseTopLevelExpr() {
|
||||
if (ExprAST *E = ParseExpression()) {
|
||||
// Make an anonymous proto.
|
||||
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
|
||||
return new FunctionAST(Proto, E);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// external ::= 'extern' prototype
|
||||
static PrototypeAST *ParseExtern() {
|
||||
getNextToken(); // eat extern.
|
||||
return ParsePrototype();
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Top-Level parsing
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static void HandleDefinition() {
|
||||
if (ParseDefinition()) {
|
||||
fprintf(stderr, "Parsed a function definition.\n");
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleExtern() {
|
||||
if (ParseExtern()) {
|
||||
fprintf(stderr, "Parsed an extern\n");
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleTopLevelExpression() {
|
||||
// Evaluate a top-level expression into an anonymous function.
|
||||
if (ParseTopLevelExpr()) {
|
||||
fprintf(stderr, "Parsed a top-level expr\n");
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
/// top ::= definition | external | expression | ';'
|
||||
static void MainLoop() {
|
||||
while (1) {
|
||||
fprintf(stderr, "ready> ");
|
||||
switch (CurTok) {
|
||||
case tok_eof: return;
|
||||
case ';': getNextToken(); break; // ignore top-level semicolons.
|
||||
case tok_def: HandleDefinition(); break;
|
||||
case tok_extern: HandleExtern(); break;
|
||||
default: HandleTopLevelExpression(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Main driver code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
int main() {
|
||||
// Install standard binary operators.
|
||||
// 1 is lowest precedence.
|
||||
BinopPrecedence['<'] = 10;
|
||||
BinopPrecedence['+'] = 20;
|
||||
BinopPrecedence['-'] = 20;
|
||||
BinopPrecedence['*'] = 40; // highest.
|
||||
|
||||
// Prime the first token.
|
||||
fprintf(stderr, "ready> ");
|
||||
getNextToken();
|
||||
|
||||
// Run the main "interpreter loop" now.
|
||||
MainLoop();
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS core)
|
||||
|
||||
add_llvm_example(Kaleidoscope-Ch3
|
||||
toy.cpp
|
||||
)
|
@ -1,15 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Chapter3/Makefile -------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../../..
|
||||
TOOLNAME = Kaleidoscope-Ch3
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
LINK_COMPONENTS := core
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,563 +0,0 @@
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/Analysis/Verifier.h"
|
||||
#include "llvm/Support/IRBuilder.h"
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
using namespace llvm;
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Lexer
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
|
||||
// of these for known things.
|
||||
enum Token {
|
||||
tok_eof = -1,
|
||||
|
||||
// commands
|
||||
tok_def = -2, tok_extern = -3,
|
||||
|
||||
// primary
|
||||
tok_identifier = -4, tok_number = -5
|
||||
};
|
||||
|
||||
static std::string IdentifierStr; // Filled in if tok_identifier
|
||||
static double NumVal; // Filled in if tok_number
|
||||
|
||||
/// gettok - Return the next token from standard input.
|
||||
static int gettok() {
|
||||
static int LastChar = ' ';
|
||||
|
||||
// Skip any whitespace.
|
||||
while (isspace(LastChar))
|
||||
LastChar = getchar();
|
||||
|
||||
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
|
||||
IdentifierStr = LastChar;
|
||||
while (isalnum((LastChar = getchar())))
|
||||
IdentifierStr += LastChar;
|
||||
|
||||
if (IdentifierStr == "def") return tok_def;
|
||||
if (IdentifierStr == "extern") return tok_extern;
|
||||
return tok_identifier;
|
||||
}
|
||||
|
||||
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
|
||||
std::string NumStr;
|
||||
do {
|
||||
NumStr += LastChar;
|
||||
LastChar = getchar();
|
||||
} while (isdigit(LastChar) || LastChar == '.');
|
||||
|
||||
NumVal = strtod(NumStr.c_str(), 0);
|
||||
return tok_number;
|
||||
}
|
||||
|
||||
if (LastChar == '#') {
|
||||
// Comment until end of line.
|
||||
do LastChar = getchar();
|
||||
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
|
||||
|
||||
if (LastChar != EOF)
|
||||
return gettok();
|
||||
}
|
||||
|
||||
// Check for end of file. Don't eat the EOF.
|
||||
if (LastChar == EOF)
|
||||
return tok_eof;
|
||||
|
||||
// Otherwise, just return the character as its ascii value.
|
||||
int ThisChar = LastChar;
|
||||
LastChar = getchar();
|
||||
return ThisChar;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Abstract Syntax Tree (aka Parse Tree)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// ExprAST - Base class for all expression nodes.
|
||||
class ExprAST {
|
||||
public:
|
||||
virtual ~ExprAST() {}
|
||||
virtual Value *Codegen() = 0;
|
||||
};
|
||||
|
||||
/// NumberExprAST - Expression class for numeric literals like "1.0".
|
||||
class NumberExprAST : public ExprAST {
|
||||
double Val;
|
||||
public:
|
||||
NumberExprAST(double val) : Val(val) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// VariableExprAST - Expression class for referencing a variable, like "a".
|
||||
class VariableExprAST : public ExprAST {
|
||||
std::string Name;
|
||||
public:
|
||||
VariableExprAST(const std::string &name) : Name(name) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// BinaryExprAST - Expression class for a binary operator.
|
||||
class BinaryExprAST : public ExprAST {
|
||||
char Op;
|
||||
ExprAST *LHS, *RHS;
|
||||
public:
|
||||
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
|
||||
: Op(op), LHS(lhs), RHS(rhs) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// CallExprAST - Expression class for function calls.
|
||||
class CallExprAST : public ExprAST {
|
||||
std::string Callee;
|
||||
std::vector<ExprAST*> Args;
|
||||
public:
|
||||
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
|
||||
: Callee(callee), Args(args) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// PrototypeAST - This class represents the "prototype" for a function,
|
||||
/// which captures its name, and its argument names (thus implicitly the number
|
||||
/// of arguments the function takes).
|
||||
class PrototypeAST {
|
||||
std::string Name;
|
||||
std::vector<std::string> Args;
|
||||
public:
|
||||
PrototypeAST(const std::string &name, const std::vector<std::string> &args)
|
||||
: Name(name), Args(args) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
/// FunctionAST - This class represents a function definition itself.
|
||||
class FunctionAST {
|
||||
PrototypeAST *Proto;
|
||||
ExprAST *Body;
|
||||
public:
|
||||
FunctionAST(PrototypeAST *proto, ExprAST *body)
|
||||
: Proto(proto), Body(body) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Parser
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
|
||||
/// token the parser is looking at. getNextToken reads another token from the
|
||||
/// lexer and updates CurTok with its results.
|
||||
static int CurTok;
|
||||
static int getNextToken() {
|
||||
return CurTok = gettok();
|
||||
}
|
||||
|
||||
/// BinopPrecedence - This holds the precedence for each binary operator that is
|
||||
/// defined.
|
||||
static std::map<char, int> BinopPrecedence;
|
||||
|
||||
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
|
||||
static int GetTokPrecedence() {
|
||||
if (!isascii(CurTok))
|
||||
return -1;
|
||||
|
||||
// Make sure it's a declared binop.
|
||||
int TokPrec = BinopPrecedence[CurTok];
|
||||
if (TokPrec <= 0) return -1;
|
||||
return TokPrec;
|
||||
}
|
||||
|
||||
/// Error* - These are little helper functions for error handling.
|
||||
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
|
||||
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
|
||||
FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
static ExprAST *ParseExpression();
|
||||
|
||||
/// identifierexpr
|
||||
/// ::= identifier
|
||||
/// ::= identifier '(' expression* ')'
|
||||
static ExprAST *ParseIdentifierExpr() {
|
||||
std::string IdName = IdentifierStr;
|
||||
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '(') // Simple variable ref.
|
||||
return new VariableExprAST(IdName);
|
||||
|
||||
// Call.
|
||||
getNextToken(); // eat (
|
||||
std::vector<ExprAST*> Args;
|
||||
if (CurTok != ')') {
|
||||
while (1) {
|
||||
ExprAST *Arg = ParseExpression();
|
||||
if (!Arg) return 0;
|
||||
Args.push_back(Arg);
|
||||
|
||||
if (CurTok == ')') break;
|
||||
|
||||
if (CurTok != ',')
|
||||
return Error("Expected ')' or ',' in argument list");
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
// Eat the ')'.
|
||||
getNextToken();
|
||||
|
||||
return new CallExprAST(IdName, Args);
|
||||
}
|
||||
|
||||
/// numberexpr ::= number
|
||||
static ExprAST *ParseNumberExpr() {
|
||||
ExprAST *Result = new NumberExprAST(NumVal);
|
||||
getNextToken(); // consume the number
|
||||
return Result;
|
||||
}
|
||||
|
||||
/// parenexpr ::= '(' expression ')'
|
||||
static ExprAST *ParseParenExpr() {
|
||||
getNextToken(); // eat (.
|
||||
ExprAST *V = ParseExpression();
|
||||
if (!V) return 0;
|
||||
|
||||
if (CurTok != ')')
|
||||
return Error("expected ')'");
|
||||
getNextToken(); // eat ).
|
||||
return V;
|
||||
}
|
||||
|
||||
/// primary
|
||||
/// ::= identifierexpr
|
||||
/// ::= numberexpr
|
||||
/// ::= parenexpr
|
||||
static ExprAST *ParsePrimary() {
|
||||
switch (CurTok) {
|
||||
default: return Error("unknown token when expecting an expression");
|
||||
case tok_identifier: return ParseIdentifierExpr();
|
||||
case tok_number: return ParseNumberExpr();
|
||||
case '(': return ParseParenExpr();
|
||||
}
|
||||
}
|
||||
|
||||
/// binoprhs
|
||||
/// ::= ('+' primary)*
|
||||
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
|
||||
// If this is a binop, find its precedence.
|
||||
while (1) {
|
||||
int TokPrec = GetTokPrecedence();
|
||||
|
||||
// If this is a binop that binds at least as tightly as the current binop,
|
||||
// consume it, otherwise we are done.
|
||||
if (TokPrec < ExprPrec)
|
||||
return LHS;
|
||||
|
||||
// Okay, we know this is a binop.
|
||||
int BinOp = CurTok;
|
||||
getNextToken(); // eat binop
|
||||
|
||||
// Parse the primary expression after the binary operator.
|
||||
ExprAST *RHS = ParsePrimary();
|
||||
if (!RHS) return 0;
|
||||
|
||||
// If BinOp binds less tightly with RHS than the operator after RHS, let
|
||||
// the pending operator take RHS as its LHS.
|
||||
int NextPrec = GetTokPrecedence();
|
||||
if (TokPrec < NextPrec) {
|
||||
RHS = ParseBinOpRHS(TokPrec+1, RHS);
|
||||
if (RHS == 0) return 0;
|
||||
}
|
||||
|
||||
// Merge LHS/RHS.
|
||||
LHS = new BinaryExprAST(BinOp, LHS, RHS);
|
||||
}
|
||||
}
|
||||
|
||||
/// expression
|
||||
/// ::= primary binoprhs
|
||||
///
|
||||
static ExprAST *ParseExpression() {
|
||||
ExprAST *LHS = ParsePrimary();
|
||||
if (!LHS) return 0;
|
||||
|
||||
return ParseBinOpRHS(0, LHS);
|
||||
}
|
||||
|
||||
/// prototype
|
||||
/// ::= id '(' id* ')'
|
||||
static PrototypeAST *ParsePrototype() {
|
||||
if (CurTok != tok_identifier)
|
||||
return ErrorP("Expected function name in prototype");
|
||||
|
||||
std::string FnName = IdentifierStr;
|
||||
getNextToken();
|
||||
|
||||
if (CurTok != '(')
|
||||
return ErrorP("Expected '(' in prototype");
|
||||
|
||||
std::vector<std::string> ArgNames;
|
||||
while (getNextToken() == tok_identifier)
|
||||
ArgNames.push_back(IdentifierStr);
|
||||
if (CurTok != ')')
|
||||
return ErrorP("Expected ')' in prototype");
|
||||
|
||||
// success.
|
||||
getNextToken(); // eat ')'.
|
||||
|
||||
return new PrototypeAST(FnName, ArgNames);
|
||||
}
|
||||
|
||||
/// definition ::= 'def' prototype expression
|
||||
static FunctionAST *ParseDefinition() {
|
||||
getNextToken(); // eat def.
|
||||
PrototypeAST *Proto = ParsePrototype();
|
||||
if (Proto == 0) return 0;
|
||||
|
||||
if (ExprAST *E = ParseExpression())
|
||||
return new FunctionAST(Proto, E);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// toplevelexpr ::= expression
|
||||
static FunctionAST *ParseTopLevelExpr() {
|
||||
if (ExprAST *E = ParseExpression()) {
|
||||
// Make an anonymous proto.
|
||||
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
|
||||
return new FunctionAST(Proto, E);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// external ::= 'extern' prototype
|
||||
static PrototypeAST *ParseExtern() {
|
||||
getNextToken(); // eat extern.
|
||||
return ParsePrototype();
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Code Generation
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static Module *TheModule;
|
||||
static IRBuilder<> Builder(getGlobalContext());
|
||||
static std::map<std::string, Value*> NamedValues;
|
||||
|
||||
Value *ErrorV(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
Value *NumberExprAST::Codegen() {
|
||||
return ConstantFP::get(getGlobalContext(), APFloat(Val));
|
||||
}
|
||||
|
||||
Value *VariableExprAST::Codegen() {
|
||||
// Look this variable up in the function.
|
||||
Value *V = NamedValues[Name];
|
||||
return V ? V : ErrorV("Unknown variable name");
|
||||
}
|
||||
|
||||
Value *BinaryExprAST::Codegen() {
|
||||
Value *L = LHS->Codegen();
|
||||
Value *R = RHS->Codegen();
|
||||
if (L == 0 || R == 0) return 0;
|
||||
|
||||
switch (Op) {
|
||||
case '+': return Builder.CreateAdd(L, R, "addtmp");
|
||||
case '-': return Builder.CreateSub(L, R, "subtmp");
|
||||
case '*': return Builder.CreateMul(L, R, "multmp");
|
||||
case '<':
|
||||
L = Builder.CreateFCmpULT(L, R, "cmptmp");
|
||||
// Convert bool 0/1 to double 0.0 or 1.0
|
||||
return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
|
||||
"booltmp");
|
||||
default: return ErrorV("invalid binary operator");
|
||||
}
|
||||
}
|
||||
|
||||
Value *CallExprAST::Codegen() {
|
||||
// Look up the name in the global module table.
|
||||
Function *CalleeF = TheModule->getFunction(Callee);
|
||||
if (CalleeF == 0)
|
||||
return ErrorV("Unknown function referenced");
|
||||
|
||||
// If argument mismatch error.
|
||||
if (CalleeF->arg_size() != Args.size())
|
||||
return ErrorV("Incorrect # arguments passed");
|
||||
|
||||
std::vector<Value*> ArgsV;
|
||||
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
|
||||
ArgsV.push_back(Args[i]->Codegen());
|
||||
if (ArgsV.back() == 0) return 0;
|
||||
}
|
||||
|
||||
return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
|
||||
}
|
||||
|
||||
Function *PrototypeAST::Codegen() {
|
||||
// Make the function type: double(double,double) etc.
|
||||
std::vector<const Type*> Doubles(Args.size(),
|
||||
Type::getDoubleTy(getGlobalContext()));
|
||||
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
|
||||
Doubles, false);
|
||||
|
||||
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
|
||||
|
||||
// If F conflicted, there was already something named 'Name'. If it has a
|
||||
// body, don't allow redefinition or reextern.
|
||||
if (F->getName() != Name) {
|
||||
// Delete the one we just made and get the existing one.
|
||||
F->eraseFromParent();
|
||||
F = TheModule->getFunction(Name);
|
||||
|
||||
// If F already has a body, reject this.
|
||||
if (!F->empty()) {
|
||||
ErrorF("redefinition of function");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If F took a different number of args, reject.
|
||||
if (F->arg_size() != Args.size()) {
|
||||
ErrorF("redefinition of function with different # args");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Set names for all arguments.
|
||||
unsigned Idx = 0;
|
||||
for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
|
||||
++AI, ++Idx) {
|
||||
AI->setName(Args[Idx]);
|
||||
|
||||
// Add arguments to variable symbol table.
|
||||
NamedValues[Args[Idx]] = AI;
|
||||
}
|
||||
|
||||
return F;
|
||||
}
|
||||
|
||||
Function *FunctionAST::Codegen() {
|
||||
NamedValues.clear();
|
||||
|
||||
Function *TheFunction = Proto->Codegen();
|
||||
if (TheFunction == 0)
|
||||
return 0;
|
||||
|
||||
// Create a new basic block to start insertion into.
|
||||
BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
|
||||
Builder.SetInsertPoint(BB);
|
||||
|
||||
if (Value *RetVal = Body->Codegen()) {
|
||||
// Finish off the function.
|
||||
Builder.CreateRet(RetVal);
|
||||
|
||||
// Validate the generated code, checking for consistency.
|
||||
verifyFunction(*TheFunction);
|
||||
|
||||
return TheFunction;
|
||||
}
|
||||
|
||||
// Error reading body, remove function.
|
||||
TheFunction->eraseFromParent();
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Top-Level parsing and JIT Driver
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static void HandleDefinition() {
|
||||
if (FunctionAST *F = ParseDefinition()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
fprintf(stderr, "Read function definition:");
|
||||
LF->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleExtern() {
|
||||
if (PrototypeAST *P = ParseExtern()) {
|
||||
if (Function *F = P->Codegen()) {
|
||||
fprintf(stderr, "Read extern: ");
|
||||
F->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleTopLevelExpression() {
|
||||
// Evaluate a top-level expression into an anonymous function.
|
||||
if (FunctionAST *F = ParseTopLevelExpr()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
fprintf(stderr, "Read top-level expression:");
|
||||
LF->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
/// top ::= definition | external | expression | ';'
|
||||
static void MainLoop() {
|
||||
while (1) {
|
||||
fprintf(stderr, "ready> ");
|
||||
switch (CurTok) {
|
||||
case tok_eof: return;
|
||||
case ';': getNextToken(); break; // ignore top-level semicolons.
|
||||
case tok_def: HandleDefinition(); break;
|
||||
case tok_extern: HandleExtern(); break;
|
||||
default: HandleTopLevelExpression(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// "Library" functions that can be "extern'd" from user code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// putchard - putchar that takes a double and returns 0.
|
||||
extern "C"
|
||||
double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Main driver code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
int main() {
|
||||
LLVMContext &Context = getGlobalContext();
|
||||
|
||||
// Install standard binary operators.
|
||||
// 1 is lowest precedence.
|
||||
BinopPrecedence['<'] = 10;
|
||||
BinopPrecedence['+'] = 20;
|
||||
BinopPrecedence['-'] = 20;
|
||||
BinopPrecedence['*'] = 40; // highest.
|
||||
|
||||
// Prime the first token.
|
||||
fprintf(stderr, "ready> ");
|
||||
getNextToken();
|
||||
|
||||
// Make the module, which holds all the code.
|
||||
TheModule = new Module("my cool jit", Context);
|
||||
|
||||
// Run the main "interpreter loop" now.
|
||||
MainLoop();
|
||||
|
||||
// Print out all of the generated code.
|
||||
TheModule->dump();
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS core jit interpreter native)
|
||||
|
||||
add_llvm_example(Kaleidoscope-Ch4
|
||||
toy.cpp
|
||||
)
|
@ -1,15 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Chapter4/Makefile -------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../../..
|
||||
TOOLNAME = Kaleidoscope-Ch4
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
LINK_COMPONENTS := core jit native
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,610 +0,0 @@
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/ExecutionEngine/ExecutionEngine.h"
|
||||
#include "llvm/ExecutionEngine/JIT.h"
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/PassManager.h"
|
||||
#include "llvm/Analysis/Verifier.h"
|
||||
#include "llvm/Target/TargetData.h"
|
||||
#include "llvm/Target/TargetSelect.h"
|
||||
#include "llvm/Transforms/Scalar.h"
|
||||
#include "llvm/Support/IRBuilder.h"
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
using namespace llvm;
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Lexer
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
|
||||
// of these for known things.
|
||||
enum Token {
|
||||
tok_eof = -1,
|
||||
|
||||
// commands
|
||||
tok_def = -2, tok_extern = -3,
|
||||
|
||||
// primary
|
||||
tok_identifier = -4, tok_number = -5
|
||||
};
|
||||
|
||||
static std::string IdentifierStr; // Filled in if tok_identifier
|
||||
static double NumVal; // Filled in if tok_number
|
||||
|
||||
/// gettok - Return the next token from standard input.
|
||||
static int gettok() {
|
||||
static int LastChar = ' ';
|
||||
|
||||
// Skip any whitespace.
|
||||
while (isspace(LastChar))
|
||||
LastChar = getchar();
|
||||
|
||||
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
|
||||
IdentifierStr = LastChar;
|
||||
while (isalnum((LastChar = getchar())))
|
||||
IdentifierStr += LastChar;
|
||||
|
||||
if (IdentifierStr == "def") return tok_def;
|
||||
if (IdentifierStr == "extern") return tok_extern;
|
||||
return tok_identifier;
|
||||
}
|
||||
|
||||
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
|
||||
std::string NumStr;
|
||||
do {
|
||||
NumStr += LastChar;
|
||||
LastChar = getchar();
|
||||
} while (isdigit(LastChar) || LastChar == '.');
|
||||
|
||||
NumVal = strtod(NumStr.c_str(), 0);
|
||||
return tok_number;
|
||||
}
|
||||
|
||||
if (LastChar == '#') {
|
||||
// Comment until end of line.
|
||||
do LastChar = getchar();
|
||||
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
|
||||
|
||||
if (LastChar != EOF)
|
||||
return gettok();
|
||||
}
|
||||
|
||||
// Check for end of file. Don't eat the EOF.
|
||||
if (LastChar == EOF)
|
||||
return tok_eof;
|
||||
|
||||
// Otherwise, just return the character as its ascii value.
|
||||
int ThisChar = LastChar;
|
||||
LastChar = getchar();
|
||||
return ThisChar;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Abstract Syntax Tree (aka Parse Tree)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// ExprAST - Base class for all expression nodes.
|
||||
class ExprAST {
|
||||
public:
|
||||
virtual ~ExprAST() {}
|
||||
virtual Value *Codegen() = 0;
|
||||
};
|
||||
|
||||
/// NumberExprAST - Expression class for numeric literals like "1.0".
|
||||
class NumberExprAST : public ExprAST {
|
||||
double Val;
|
||||
public:
|
||||
NumberExprAST(double val) : Val(val) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// VariableExprAST - Expression class for referencing a variable, like "a".
|
||||
class VariableExprAST : public ExprAST {
|
||||
std::string Name;
|
||||
public:
|
||||
VariableExprAST(const std::string &name) : Name(name) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// BinaryExprAST - Expression class for a binary operator.
|
||||
class BinaryExprAST : public ExprAST {
|
||||
char Op;
|
||||
ExprAST *LHS, *RHS;
|
||||
public:
|
||||
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
|
||||
: Op(op), LHS(lhs), RHS(rhs) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// CallExprAST - Expression class for function calls.
|
||||
class CallExprAST : public ExprAST {
|
||||
std::string Callee;
|
||||
std::vector<ExprAST*> Args;
|
||||
public:
|
||||
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
|
||||
: Callee(callee), Args(args) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// PrototypeAST - This class represents the "prototype" for a function,
|
||||
/// which captures its name, and its argument names (thus implicitly the number
|
||||
/// of arguments the function takes).
|
||||
class PrototypeAST {
|
||||
std::string Name;
|
||||
std::vector<std::string> Args;
|
||||
public:
|
||||
PrototypeAST(const std::string &name, const std::vector<std::string> &args)
|
||||
: Name(name), Args(args) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
/// FunctionAST - This class represents a function definition itself.
|
||||
class FunctionAST {
|
||||
PrototypeAST *Proto;
|
||||
ExprAST *Body;
|
||||
public:
|
||||
FunctionAST(PrototypeAST *proto, ExprAST *body)
|
||||
: Proto(proto), Body(body) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Parser
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
|
||||
/// token the parser is looking at. getNextToken reads another token from the
|
||||
/// lexer and updates CurTok with its results.
|
||||
static int CurTok;
|
||||
static int getNextToken() {
|
||||
return CurTok = gettok();
|
||||
}
|
||||
|
||||
/// BinopPrecedence - This holds the precedence for each binary operator that is
|
||||
/// defined.
|
||||
static std::map<char, int> BinopPrecedence;
|
||||
|
||||
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
|
||||
static int GetTokPrecedence() {
|
||||
if (!isascii(CurTok))
|
||||
return -1;
|
||||
|
||||
// Make sure it's a declared binop.
|
||||
int TokPrec = BinopPrecedence[CurTok];
|
||||
if (TokPrec <= 0) return -1;
|
||||
return TokPrec;
|
||||
}
|
||||
|
||||
/// Error* - These are little helper functions for error handling.
|
||||
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
|
||||
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
|
||||
FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
static ExprAST *ParseExpression();
|
||||
|
||||
/// identifierexpr
|
||||
/// ::= identifier
|
||||
/// ::= identifier '(' expression* ')'
|
||||
static ExprAST *ParseIdentifierExpr() {
|
||||
std::string IdName = IdentifierStr;
|
||||
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '(') // Simple variable ref.
|
||||
return new VariableExprAST(IdName);
|
||||
|
||||
// Call.
|
||||
getNextToken(); // eat (
|
||||
std::vector<ExprAST*> Args;
|
||||
if (CurTok != ')') {
|
||||
while (1) {
|
||||
ExprAST *Arg = ParseExpression();
|
||||
if (!Arg) return 0;
|
||||
Args.push_back(Arg);
|
||||
|
||||
if (CurTok == ')') break;
|
||||
|
||||
if (CurTok != ',')
|
||||
return Error("Expected ')' or ',' in argument list");
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
// Eat the ')'.
|
||||
getNextToken();
|
||||
|
||||
return new CallExprAST(IdName, Args);
|
||||
}
|
||||
|
||||
/// numberexpr ::= number
|
||||
static ExprAST *ParseNumberExpr() {
|
||||
ExprAST *Result = new NumberExprAST(NumVal);
|
||||
getNextToken(); // consume the number
|
||||
return Result;
|
||||
}
|
||||
|
||||
/// parenexpr ::= '(' expression ')'
|
||||
static ExprAST *ParseParenExpr() {
|
||||
getNextToken(); // eat (.
|
||||
ExprAST *V = ParseExpression();
|
||||
if (!V) return 0;
|
||||
|
||||
if (CurTok != ')')
|
||||
return Error("expected ')'");
|
||||
getNextToken(); // eat ).
|
||||
return V;
|
||||
}
|
||||
|
||||
/// primary
|
||||
/// ::= identifierexpr
|
||||
/// ::= numberexpr
|
||||
/// ::= parenexpr
|
||||
static ExprAST *ParsePrimary() {
|
||||
switch (CurTok) {
|
||||
default: return Error("unknown token when expecting an expression");
|
||||
case tok_identifier: return ParseIdentifierExpr();
|
||||
case tok_number: return ParseNumberExpr();
|
||||
case '(': return ParseParenExpr();
|
||||
}
|
||||
}
|
||||
|
||||
/// binoprhs
|
||||
/// ::= ('+' primary)*
|
||||
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
|
||||
// If this is a binop, find its precedence.
|
||||
while (1) {
|
||||
int TokPrec = GetTokPrecedence();
|
||||
|
||||
// If this is a binop that binds at least as tightly as the current binop,
|
||||
// consume it, otherwise we are done.
|
||||
if (TokPrec < ExprPrec)
|
||||
return LHS;
|
||||
|
||||
// Okay, we know this is a binop.
|
||||
int BinOp = CurTok;
|
||||
getNextToken(); // eat binop
|
||||
|
||||
// Parse the primary expression after the binary operator.
|
||||
ExprAST *RHS = ParsePrimary();
|
||||
if (!RHS) return 0;
|
||||
|
||||
// If BinOp binds less tightly with RHS than the operator after RHS, let
|
||||
// the pending operator take RHS as its LHS.
|
||||
int NextPrec = GetTokPrecedence();
|
||||
if (TokPrec < NextPrec) {
|
||||
RHS = ParseBinOpRHS(TokPrec+1, RHS);
|
||||
if (RHS == 0) return 0;
|
||||
}
|
||||
|
||||
// Merge LHS/RHS.
|
||||
LHS = new BinaryExprAST(BinOp, LHS, RHS);
|
||||
}
|
||||
}
|
||||
|
||||
/// expression
|
||||
/// ::= primary binoprhs
|
||||
///
|
||||
static ExprAST *ParseExpression() {
|
||||
ExprAST *LHS = ParsePrimary();
|
||||
if (!LHS) return 0;
|
||||
|
||||
return ParseBinOpRHS(0, LHS);
|
||||
}
|
||||
|
||||
/// prototype
|
||||
/// ::= id '(' id* ')'
|
||||
static PrototypeAST *ParsePrototype() {
|
||||
if (CurTok != tok_identifier)
|
||||
return ErrorP("Expected function name in prototype");
|
||||
|
||||
std::string FnName = IdentifierStr;
|
||||
getNextToken();
|
||||
|
||||
if (CurTok != '(')
|
||||
return ErrorP("Expected '(' in prototype");
|
||||
|
||||
std::vector<std::string> ArgNames;
|
||||
while (getNextToken() == tok_identifier)
|
||||
ArgNames.push_back(IdentifierStr);
|
||||
if (CurTok != ')')
|
||||
return ErrorP("Expected ')' in prototype");
|
||||
|
||||
// success.
|
||||
getNextToken(); // eat ')'.
|
||||
|
||||
return new PrototypeAST(FnName, ArgNames);
|
||||
}
|
||||
|
||||
/// definition ::= 'def' prototype expression
|
||||
static FunctionAST *ParseDefinition() {
|
||||
getNextToken(); // eat def.
|
||||
PrototypeAST *Proto = ParsePrototype();
|
||||
if (Proto == 0) return 0;
|
||||
|
||||
if (ExprAST *E = ParseExpression())
|
||||
return new FunctionAST(Proto, E);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// toplevelexpr ::= expression
|
||||
static FunctionAST *ParseTopLevelExpr() {
|
||||
if (ExprAST *E = ParseExpression()) {
|
||||
// Make an anonymous proto.
|
||||
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
|
||||
return new FunctionAST(Proto, E);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// external ::= 'extern' prototype
|
||||
static PrototypeAST *ParseExtern() {
|
||||
getNextToken(); // eat extern.
|
||||
return ParsePrototype();
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Code Generation
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static Module *TheModule;
|
||||
static IRBuilder<> Builder(getGlobalContext());
|
||||
static std::map<std::string, Value*> NamedValues;
|
||||
static FunctionPassManager *TheFPM;
|
||||
|
||||
Value *ErrorV(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
Value *NumberExprAST::Codegen() {
|
||||
return ConstantFP::get(getGlobalContext(), APFloat(Val));
|
||||
}
|
||||
|
||||
Value *VariableExprAST::Codegen() {
|
||||
// Look this variable up in the function.
|
||||
Value *V = NamedValues[Name];
|
||||
return V ? V : ErrorV("Unknown variable name");
|
||||
}
|
||||
|
||||
Value *BinaryExprAST::Codegen() {
|
||||
Value *L = LHS->Codegen();
|
||||
Value *R = RHS->Codegen();
|
||||
if (L == 0 || R == 0) return 0;
|
||||
|
||||
switch (Op) {
|
||||
case '+': return Builder.CreateAdd(L, R, "addtmp");
|
||||
case '-': return Builder.CreateSub(L, R, "subtmp");
|
||||
case '*': return Builder.CreateMul(L, R, "multmp");
|
||||
case '<':
|
||||
L = Builder.CreateFCmpULT(L, R, "cmptmp");
|
||||
// Convert bool 0/1 to double 0.0 or 1.0
|
||||
return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
|
||||
"booltmp");
|
||||
default: return ErrorV("invalid binary operator");
|
||||
}
|
||||
}
|
||||
|
||||
Value *CallExprAST::Codegen() {
|
||||
// Look up the name in the global module table.
|
||||
Function *CalleeF = TheModule->getFunction(Callee);
|
||||
if (CalleeF == 0)
|
||||
return ErrorV("Unknown function referenced");
|
||||
|
||||
// If argument mismatch error.
|
||||
if (CalleeF->arg_size() != Args.size())
|
||||
return ErrorV("Incorrect # arguments passed");
|
||||
|
||||
std::vector<Value*> ArgsV;
|
||||
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
|
||||
ArgsV.push_back(Args[i]->Codegen());
|
||||
if (ArgsV.back() == 0) return 0;
|
||||
}
|
||||
|
||||
return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
|
||||
}
|
||||
|
||||
Function *PrototypeAST::Codegen() {
|
||||
// Make the function type: double(double,double) etc.
|
||||
std::vector<const Type*> Doubles(Args.size(),
|
||||
Type::getDoubleTy(getGlobalContext()));
|
||||
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
|
||||
Doubles, false);
|
||||
|
||||
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
|
||||
|
||||
// If F conflicted, there was already something named 'Name'. If it has a
|
||||
// body, don't allow redefinition or reextern.
|
||||
if (F->getName() != Name) {
|
||||
// Delete the one we just made and get the existing one.
|
||||
F->eraseFromParent();
|
||||
F = TheModule->getFunction(Name);
|
||||
|
||||
// If F already has a body, reject this.
|
||||
if (!F->empty()) {
|
||||
ErrorF("redefinition of function");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If F took a different number of args, reject.
|
||||
if (F->arg_size() != Args.size()) {
|
||||
ErrorF("redefinition of function with different # args");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Set names for all arguments.
|
||||
unsigned Idx = 0;
|
||||
for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
|
||||
++AI, ++Idx) {
|
||||
AI->setName(Args[Idx]);
|
||||
|
||||
// Add arguments to variable symbol table.
|
||||
NamedValues[Args[Idx]] = AI;
|
||||
}
|
||||
|
||||
return F;
|
||||
}
|
||||
|
||||
Function *FunctionAST::Codegen() {
|
||||
NamedValues.clear();
|
||||
|
||||
Function *TheFunction = Proto->Codegen();
|
||||
if (TheFunction == 0)
|
||||
return 0;
|
||||
|
||||
// Create a new basic block to start insertion into.
|
||||
BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
|
||||
Builder.SetInsertPoint(BB);
|
||||
|
||||
if (Value *RetVal = Body->Codegen()) {
|
||||
// Finish off the function.
|
||||
Builder.CreateRet(RetVal);
|
||||
|
||||
// Validate the generated code, checking for consistency.
|
||||
verifyFunction(*TheFunction);
|
||||
|
||||
// Optimize the function.
|
||||
TheFPM->run(*TheFunction);
|
||||
|
||||
return TheFunction;
|
||||
}
|
||||
|
||||
// Error reading body, remove function.
|
||||
TheFunction->eraseFromParent();
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Top-Level parsing and JIT Driver
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static ExecutionEngine *TheExecutionEngine;
|
||||
|
||||
static void HandleDefinition() {
|
||||
if (FunctionAST *F = ParseDefinition()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
fprintf(stderr, "Read function definition:");
|
||||
LF->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleExtern() {
|
||||
if (PrototypeAST *P = ParseExtern()) {
|
||||
if (Function *F = P->Codegen()) {
|
||||
fprintf(stderr, "Read extern: ");
|
||||
F->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleTopLevelExpression() {
|
||||
// Evaluate a top-level expression into an anonymous function.
|
||||
if (FunctionAST *F = ParseTopLevelExpr()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
// JIT the function, returning a function pointer.
|
||||
void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
|
||||
|
||||
// Cast it to the right type (takes no arguments, returns a double) so we
|
||||
// can call it as a native function.
|
||||
double (*FP)() = (double (*)())(intptr_t)FPtr;
|
||||
fprintf(stderr, "Evaluated to %f\n", FP());
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
/// top ::= definition | external | expression | ';'
|
||||
static void MainLoop() {
|
||||
while (1) {
|
||||
fprintf(stderr, "ready> ");
|
||||
switch (CurTok) {
|
||||
case tok_eof: return;
|
||||
case ';': getNextToken(); break; // ignore top-level semicolons.
|
||||
case tok_def: HandleDefinition(); break;
|
||||
case tok_extern: HandleExtern(); break;
|
||||
default: HandleTopLevelExpression(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// "Library" functions that can be "extern'd" from user code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// putchard - putchar that takes a double and returns 0.
|
||||
extern "C"
|
||||
double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Main driver code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
int main() {
|
||||
InitializeNativeTarget();
|
||||
LLVMContext &Context = getGlobalContext();
|
||||
|
||||
// Install standard binary operators.
|
||||
// 1 is lowest precedence.
|
||||
BinopPrecedence['<'] = 10;
|
||||
BinopPrecedence['+'] = 20;
|
||||
BinopPrecedence['-'] = 20;
|
||||
BinopPrecedence['*'] = 40; // highest.
|
||||
|
||||
// Prime the first token.
|
||||
fprintf(stderr, "ready> ");
|
||||
getNextToken();
|
||||
|
||||
// Make the module, which holds all the code.
|
||||
TheModule = new Module("my cool jit", Context);
|
||||
|
||||
// Create the JIT. This takes ownership of the module.
|
||||
std::string ErrStr;
|
||||
TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
|
||||
if (!TheExecutionEngine) {
|
||||
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
FunctionPassManager OurFPM(TheModule);
|
||||
|
||||
// Set up the optimizer pipeline. Start with registering info about how the
|
||||
// target lays out data structures.
|
||||
OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
|
||||
// Do simple "peephole" optimizations and bit-twiddling optzns.
|
||||
OurFPM.add(createInstructionCombiningPass());
|
||||
// Reassociate expressions.
|
||||
OurFPM.add(createReassociatePass());
|
||||
// Eliminate Common SubExpressions.
|
||||
OurFPM.add(createGVNPass());
|
||||
// Simplify the control flow graph (deleting unreachable blocks, etc).
|
||||
OurFPM.add(createCFGSimplificationPass());
|
||||
|
||||
OurFPM.doInitialization();
|
||||
|
||||
// Set the global so the code gen can use this.
|
||||
TheFPM = &OurFPM;
|
||||
|
||||
// Run the main "interpreter loop" now.
|
||||
MainLoop();
|
||||
|
||||
TheFPM = 0;
|
||||
|
||||
// Print out all of the generated code.
|
||||
TheModule->dump();
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS core jit interpreter native)
|
||||
|
||||
add_llvm_example(Kaleidoscope-Ch5
|
||||
toy.cpp
|
||||
)
|
@ -1,15 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Chapter5/Makefile -------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../../..
|
||||
TOOLNAME = Kaleidoscope-Ch5
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
LINK_COMPONENTS := core jit native
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,855 +0,0 @@
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/ExecutionEngine/ExecutionEngine.h"
|
||||
#include "llvm/ExecutionEngine/JIT.h"
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/PassManager.h"
|
||||
#include "llvm/Analysis/Verifier.h"
|
||||
#include "llvm/Target/TargetData.h"
|
||||
#include "llvm/Target/TargetSelect.h"
|
||||
#include "llvm/Transforms/Scalar.h"
|
||||
#include "llvm/Support/IRBuilder.h"
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
using namespace llvm;
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Lexer
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
|
||||
// of these for known things.
|
||||
enum Token {
|
||||
tok_eof = -1,
|
||||
|
||||
// commands
|
||||
tok_def = -2, tok_extern = -3,
|
||||
|
||||
// primary
|
||||
tok_identifier = -4, tok_number = -5,
|
||||
|
||||
// control
|
||||
tok_if = -6, tok_then = -7, tok_else = -8,
|
||||
tok_for = -9, tok_in = -10
|
||||
};
|
||||
|
||||
static std::string IdentifierStr; // Filled in if tok_identifier
|
||||
static double NumVal; // Filled in if tok_number
|
||||
|
||||
/// gettok - Return the next token from standard input.
|
||||
static int gettok() {
|
||||
static int LastChar = ' ';
|
||||
|
||||
// Skip any whitespace.
|
||||
while (isspace(LastChar))
|
||||
LastChar = getchar();
|
||||
|
||||
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
|
||||
IdentifierStr = LastChar;
|
||||
while (isalnum((LastChar = getchar())))
|
||||
IdentifierStr += LastChar;
|
||||
|
||||
if (IdentifierStr == "def") return tok_def;
|
||||
if (IdentifierStr == "extern") return tok_extern;
|
||||
if (IdentifierStr == "if") return tok_if;
|
||||
if (IdentifierStr == "then") return tok_then;
|
||||
if (IdentifierStr == "else") return tok_else;
|
||||
if (IdentifierStr == "for") return tok_for;
|
||||
if (IdentifierStr == "in") return tok_in;
|
||||
return tok_identifier;
|
||||
}
|
||||
|
||||
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
|
||||
std::string NumStr;
|
||||
do {
|
||||
NumStr += LastChar;
|
||||
LastChar = getchar();
|
||||
} while (isdigit(LastChar) || LastChar == '.');
|
||||
|
||||
NumVal = strtod(NumStr.c_str(), 0);
|
||||
return tok_number;
|
||||
}
|
||||
|
||||
if (LastChar == '#') {
|
||||
// Comment until end of line.
|
||||
do LastChar = getchar();
|
||||
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
|
||||
|
||||
if (LastChar != EOF)
|
||||
return gettok();
|
||||
}
|
||||
|
||||
// Check for end of file. Don't eat the EOF.
|
||||
if (LastChar == EOF)
|
||||
return tok_eof;
|
||||
|
||||
// Otherwise, just return the character as its ascii value.
|
||||
int ThisChar = LastChar;
|
||||
LastChar = getchar();
|
||||
return ThisChar;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Abstract Syntax Tree (aka Parse Tree)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// ExprAST - Base class for all expression nodes.
|
||||
class ExprAST {
|
||||
public:
|
||||
virtual ~ExprAST() {}
|
||||
virtual Value *Codegen() = 0;
|
||||
};
|
||||
|
||||
/// NumberExprAST - Expression class for numeric literals like "1.0".
|
||||
class NumberExprAST : public ExprAST {
|
||||
double Val;
|
||||
public:
|
||||
NumberExprAST(double val) : Val(val) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// VariableExprAST - Expression class for referencing a variable, like "a".
|
||||
class VariableExprAST : public ExprAST {
|
||||
std::string Name;
|
||||
public:
|
||||
VariableExprAST(const std::string &name) : Name(name) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// BinaryExprAST - Expression class for a binary operator.
|
||||
class BinaryExprAST : public ExprAST {
|
||||
char Op;
|
||||
ExprAST *LHS, *RHS;
|
||||
public:
|
||||
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
|
||||
: Op(op), LHS(lhs), RHS(rhs) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// CallExprAST - Expression class for function calls.
|
||||
class CallExprAST : public ExprAST {
|
||||
std::string Callee;
|
||||
std::vector<ExprAST*> Args;
|
||||
public:
|
||||
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
|
||||
: Callee(callee), Args(args) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// IfExprAST - Expression class for if/then/else.
|
||||
class IfExprAST : public ExprAST {
|
||||
ExprAST *Cond, *Then, *Else;
|
||||
public:
|
||||
IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
|
||||
: Cond(cond), Then(then), Else(_else) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// ForExprAST - Expression class for for/in.
|
||||
class ForExprAST : public ExprAST {
|
||||
std::string VarName;
|
||||
ExprAST *Start, *End, *Step, *Body;
|
||||
public:
|
||||
ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
|
||||
ExprAST *step, ExprAST *body)
|
||||
: VarName(varname), Start(start), End(end), Step(step), Body(body) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// PrototypeAST - This class represents the "prototype" for a function,
|
||||
/// which captures its name, and its argument names (thus implicitly the number
|
||||
/// of arguments the function takes).
|
||||
class PrototypeAST {
|
||||
std::string Name;
|
||||
std::vector<std::string> Args;
|
||||
public:
|
||||
PrototypeAST(const std::string &name, const std::vector<std::string> &args)
|
||||
: Name(name), Args(args) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
/// FunctionAST - This class represents a function definition itself.
|
||||
class FunctionAST {
|
||||
PrototypeAST *Proto;
|
||||
ExprAST *Body;
|
||||
public:
|
||||
FunctionAST(PrototypeAST *proto, ExprAST *body)
|
||||
: Proto(proto), Body(body) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Parser
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
|
||||
/// token the parser is looking at. getNextToken reads another token from the
|
||||
/// lexer and updates CurTok with its results.
|
||||
static int CurTok;
|
||||
static int getNextToken() {
|
||||
return CurTok = gettok();
|
||||
}
|
||||
|
||||
/// BinopPrecedence - This holds the precedence for each binary operator that is
|
||||
/// defined.
|
||||
static std::map<char, int> BinopPrecedence;
|
||||
|
||||
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
|
||||
static int GetTokPrecedence() {
|
||||
if (!isascii(CurTok))
|
||||
return -1;
|
||||
|
||||
// Make sure it's a declared binop.
|
||||
int TokPrec = BinopPrecedence[CurTok];
|
||||
if (TokPrec <= 0) return -1;
|
||||
return TokPrec;
|
||||
}
|
||||
|
||||
/// Error* - These are little helper functions for error handling.
|
||||
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
|
||||
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
|
||||
FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
static ExprAST *ParseExpression();
|
||||
|
||||
/// identifierexpr
|
||||
/// ::= identifier
|
||||
/// ::= identifier '(' expression* ')'
|
||||
static ExprAST *ParseIdentifierExpr() {
|
||||
std::string IdName = IdentifierStr;
|
||||
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '(') // Simple variable ref.
|
||||
return new VariableExprAST(IdName);
|
||||
|
||||
// Call.
|
||||
getNextToken(); // eat (
|
||||
std::vector<ExprAST*> Args;
|
||||
if (CurTok != ')') {
|
||||
while (1) {
|
||||
ExprAST *Arg = ParseExpression();
|
||||
if (!Arg) return 0;
|
||||
Args.push_back(Arg);
|
||||
|
||||
if (CurTok == ')') break;
|
||||
|
||||
if (CurTok != ',')
|
||||
return Error("Expected ')' or ',' in argument list");
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
// Eat the ')'.
|
||||
getNextToken();
|
||||
|
||||
return new CallExprAST(IdName, Args);
|
||||
}
|
||||
|
||||
/// numberexpr ::= number
|
||||
static ExprAST *ParseNumberExpr() {
|
||||
ExprAST *Result = new NumberExprAST(NumVal);
|
||||
getNextToken(); // consume the number
|
||||
return Result;
|
||||
}
|
||||
|
||||
/// parenexpr ::= '(' expression ')'
|
||||
static ExprAST *ParseParenExpr() {
|
||||
getNextToken(); // eat (.
|
||||
ExprAST *V = ParseExpression();
|
||||
if (!V) return 0;
|
||||
|
||||
if (CurTok != ')')
|
||||
return Error("expected ')'");
|
||||
getNextToken(); // eat ).
|
||||
return V;
|
||||
}
|
||||
|
||||
/// ifexpr ::= 'if' expression 'then' expression 'else' expression
|
||||
static ExprAST *ParseIfExpr() {
|
||||
getNextToken(); // eat the if.
|
||||
|
||||
// condition.
|
||||
ExprAST *Cond = ParseExpression();
|
||||
if (!Cond) return 0;
|
||||
|
||||
if (CurTok != tok_then)
|
||||
return Error("expected then");
|
||||
getNextToken(); // eat the then
|
||||
|
||||
ExprAST *Then = ParseExpression();
|
||||
if (Then == 0) return 0;
|
||||
|
||||
if (CurTok != tok_else)
|
||||
return Error("expected else");
|
||||
|
||||
getNextToken();
|
||||
|
||||
ExprAST *Else = ParseExpression();
|
||||
if (!Else) return 0;
|
||||
|
||||
return new IfExprAST(Cond, Then, Else);
|
||||
}
|
||||
|
||||
/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
|
||||
static ExprAST *ParseForExpr() {
|
||||
getNextToken(); // eat the for.
|
||||
|
||||
if (CurTok != tok_identifier)
|
||||
return Error("expected identifier after for");
|
||||
|
||||
std::string IdName = IdentifierStr;
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '=')
|
||||
return Error("expected '=' after for");
|
||||
getNextToken(); // eat '='.
|
||||
|
||||
|
||||
ExprAST *Start = ParseExpression();
|
||||
if (Start == 0) return 0;
|
||||
if (CurTok != ',')
|
||||
return Error("expected ',' after for start value");
|
||||
getNextToken();
|
||||
|
||||
ExprAST *End = ParseExpression();
|
||||
if (End == 0) return 0;
|
||||
|
||||
// The step value is optional.
|
||||
ExprAST *Step = 0;
|
||||
if (CurTok == ',') {
|
||||
getNextToken();
|
||||
Step = ParseExpression();
|
||||
if (Step == 0) return 0;
|
||||
}
|
||||
|
||||
if (CurTok != tok_in)
|
||||
return Error("expected 'in' after for");
|
||||
getNextToken(); // eat 'in'.
|
||||
|
||||
ExprAST *Body = ParseExpression();
|
||||
if (Body == 0) return 0;
|
||||
|
||||
return new ForExprAST(IdName, Start, End, Step, Body);
|
||||
}
|
||||
|
||||
/// primary
|
||||
/// ::= identifierexpr
|
||||
/// ::= numberexpr
|
||||
/// ::= parenexpr
|
||||
/// ::= ifexpr
|
||||
/// ::= forexpr
|
||||
static ExprAST *ParsePrimary() {
|
||||
switch (CurTok) {
|
||||
default: return Error("unknown token when expecting an expression");
|
||||
case tok_identifier: return ParseIdentifierExpr();
|
||||
case tok_number: return ParseNumberExpr();
|
||||
case '(': return ParseParenExpr();
|
||||
case tok_if: return ParseIfExpr();
|
||||
case tok_for: return ParseForExpr();
|
||||
}
|
||||
}
|
||||
|
||||
/// binoprhs
|
||||
/// ::= ('+' primary)*
|
||||
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
|
||||
// If this is a binop, find its precedence.
|
||||
while (1) {
|
||||
int TokPrec = GetTokPrecedence();
|
||||
|
||||
// If this is a binop that binds at least as tightly as the current binop,
|
||||
// consume it, otherwise we are done.
|
||||
if (TokPrec < ExprPrec)
|
||||
return LHS;
|
||||
|
||||
// Okay, we know this is a binop.
|
||||
int BinOp = CurTok;
|
||||
getNextToken(); // eat binop
|
||||
|
||||
// Parse the primary expression after the binary operator.
|
||||
ExprAST *RHS = ParsePrimary();
|
||||
if (!RHS) return 0;
|
||||
|
||||
// If BinOp binds less tightly with RHS than the operator after RHS, let
|
||||
// the pending operator take RHS as its LHS.
|
||||
int NextPrec = GetTokPrecedence();
|
||||
if (TokPrec < NextPrec) {
|
||||
RHS = ParseBinOpRHS(TokPrec+1, RHS);
|
||||
if (RHS == 0) return 0;
|
||||
}
|
||||
|
||||
// Merge LHS/RHS.
|
||||
LHS = new BinaryExprAST(BinOp, LHS, RHS);
|
||||
}
|
||||
}
|
||||
|
||||
/// expression
|
||||
/// ::= primary binoprhs
|
||||
///
|
||||
static ExprAST *ParseExpression() {
|
||||
ExprAST *LHS = ParsePrimary();
|
||||
if (!LHS) return 0;
|
||||
|
||||
return ParseBinOpRHS(0, LHS);
|
||||
}
|
||||
|
||||
/// prototype
|
||||
/// ::= id '(' id* ')'
|
||||
static PrototypeAST *ParsePrototype() {
|
||||
if (CurTok != tok_identifier)
|
||||
return ErrorP("Expected function name in prototype");
|
||||
|
||||
std::string FnName = IdentifierStr;
|
||||
getNextToken();
|
||||
|
||||
if (CurTok != '(')
|
||||
return ErrorP("Expected '(' in prototype");
|
||||
|
||||
std::vector<std::string> ArgNames;
|
||||
while (getNextToken() == tok_identifier)
|
||||
ArgNames.push_back(IdentifierStr);
|
||||
if (CurTok != ')')
|
||||
return ErrorP("Expected ')' in prototype");
|
||||
|
||||
// success.
|
||||
getNextToken(); // eat ')'.
|
||||
|
||||
return new PrototypeAST(FnName, ArgNames);
|
||||
}
|
||||
|
||||
/// definition ::= 'def' prototype expression
|
||||
static FunctionAST *ParseDefinition() {
|
||||
getNextToken(); // eat def.
|
||||
PrototypeAST *Proto = ParsePrototype();
|
||||
if (Proto == 0) return 0;
|
||||
|
||||
if (ExprAST *E = ParseExpression())
|
||||
return new FunctionAST(Proto, E);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// toplevelexpr ::= expression
|
||||
static FunctionAST *ParseTopLevelExpr() {
|
||||
if (ExprAST *E = ParseExpression()) {
|
||||
// Make an anonymous proto.
|
||||
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
|
||||
return new FunctionAST(Proto, E);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// external ::= 'extern' prototype
|
||||
static PrototypeAST *ParseExtern() {
|
||||
getNextToken(); // eat extern.
|
||||
return ParsePrototype();
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Code Generation
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static Module *TheModule;
|
||||
static IRBuilder<> Builder(getGlobalContext());
|
||||
static std::map<std::string, Value*> NamedValues;
|
||||
static FunctionPassManager *TheFPM;
|
||||
|
||||
Value *ErrorV(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
Value *NumberExprAST::Codegen() {
|
||||
return ConstantFP::get(getGlobalContext(), APFloat(Val));
|
||||
}
|
||||
|
||||
Value *VariableExprAST::Codegen() {
|
||||
// Look this variable up in the function.
|
||||
Value *V = NamedValues[Name];
|
||||
return V ? V : ErrorV("Unknown variable name");
|
||||
}
|
||||
|
||||
Value *BinaryExprAST::Codegen() {
|
||||
Value *L = LHS->Codegen();
|
||||
Value *R = RHS->Codegen();
|
||||
if (L == 0 || R == 0) return 0;
|
||||
|
||||
switch (Op) {
|
||||
case '+': return Builder.CreateAdd(L, R, "addtmp");
|
||||
case '-': return Builder.CreateSub(L, R, "subtmp");
|
||||
case '*': return Builder.CreateMul(L, R, "multmp");
|
||||
case '<':
|
||||
L = Builder.CreateFCmpULT(L, R, "cmptmp");
|
||||
// Convert bool 0/1 to double 0.0 or 1.0
|
||||
return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
|
||||
"booltmp");
|
||||
default: return ErrorV("invalid binary operator");
|
||||
}
|
||||
}
|
||||
|
||||
Value *CallExprAST::Codegen() {
|
||||
// Look up the name in the global module table.
|
||||
Function *CalleeF = TheModule->getFunction(Callee);
|
||||
if (CalleeF == 0)
|
||||
return ErrorV("Unknown function referenced");
|
||||
|
||||
// If argument mismatch error.
|
||||
if (CalleeF->arg_size() != Args.size())
|
||||
return ErrorV("Incorrect # arguments passed");
|
||||
|
||||
std::vector<Value*> ArgsV;
|
||||
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
|
||||
ArgsV.push_back(Args[i]->Codegen());
|
||||
if (ArgsV.back() == 0) return 0;
|
||||
}
|
||||
|
||||
return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
|
||||
}
|
||||
|
||||
Value *IfExprAST::Codegen() {
|
||||
Value *CondV = Cond->Codegen();
|
||||
if (CondV == 0) return 0;
|
||||
|
||||
// Convert condition to a bool by comparing equal to 0.0.
|
||||
CondV = Builder.CreateFCmpONE(CondV,
|
||||
ConstantFP::get(getGlobalContext(), APFloat(0.0)),
|
||||
"ifcond");
|
||||
|
||||
Function *TheFunction = Builder.GetInsertBlock()->getParent();
|
||||
|
||||
// Create blocks for the then and else cases. Insert the 'then' block at the
|
||||
// end of the function.
|
||||
BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
|
||||
BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
|
||||
BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
|
||||
|
||||
Builder.CreateCondBr(CondV, ThenBB, ElseBB);
|
||||
|
||||
// Emit then value.
|
||||
Builder.SetInsertPoint(ThenBB);
|
||||
|
||||
Value *ThenV = Then->Codegen();
|
||||
if (ThenV == 0) return 0;
|
||||
|
||||
Builder.CreateBr(MergeBB);
|
||||
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
|
||||
ThenBB = Builder.GetInsertBlock();
|
||||
|
||||
// Emit else block.
|
||||
TheFunction->getBasicBlockList().push_back(ElseBB);
|
||||
Builder.SetInsertPoint(ElseBB);
|
||||
|
||||
Value *ElseV = Else->Codegen();
|
||||
if (ElseV == 0) return 0;
|
||||
|
||||
Builder.CreateBr(MergeBB);
|
||||
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
|
||||
ElseBB = Builder.GetInsertBlock();
|
||||
|
||||
// Emit merge block.
|
||||
TheFunction->getBasicBlockList().push_back(MergeBB);
|
||||
Builder.SetInsertPoint(MergeBB);
|
||||
PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
|
||||
"iftmp");
|
||||
|
||||
PN->addIncoming(ThenV, ThenBB);
|
||||
PN->addIncoming(ElseV, ElseBB);
|
||||
return PN;
|
||||
}
|
||||
|
||||
Value *ForExprAST::Codegen() {
|
||||
// Output this as:
|
||||
// ...
|
||||
// start = startexpr
|
||||
// goto loop
|
||||
// loop:
|
||||
// variable = phi [start, loopheader], [nextvariable, loopend]
|
||||
// ...
|
||||
// bodyexpr
|
||||
// ...
|
||||
// loopend:
|
||||
// step = stepexpr
|
||||
// nextvariable = variable + step
|
||||
// endcond = endexpr
|
||||
// br endcond, loop, endloop
|
||||
// outloop:
|
||||
|
||||
// Emit the start code first, without 'variable' in scope.
|
||||
Value *StartVal = Start->Codegen();
|
||||
if (StartVal == 0) return 0;
|
||||
|
||||
// Make the new basic block for the loop header, inserting after current
|
||||
// block.
|
||||
Function *TheFunction = Builder.GetInsertBlock()->getParent();
|
||||
BasicBlock *PreheaderBB = Builder.GetInsertBlock();
|
||||
BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
|
||||
|
||||
// Insert an explicit fall through from the current block to the LoopBB.
|
||||
Builder.CreateBr(LoopBB);
|
||||
|
||||
// Start insertion in LoopBB.
|
||||
Builder.SetInsertPoint(LoopBB);
|
||||
|
||||
// Start the PHI node with an entry for Start.
|
||||
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), VarName.c_str());
|
||||
Variable->addIncoming(StartVal, PreheaderBB);
|
||||
|
||||
// Within the loop, the variable is defined equal to the PHI node. If it
|
||||
// shadows an existing variable, we have to restore it, so save it now.
|
||||
Value *OldVal = NamedValues[VarName];
|
||||
NamedValues[VarName] = Variable;
|
||||
|
||||
// Emit the body of the loop. This, like any other expr, can change the
|
||||
// current BB. Note that we ignore the value computed by the body, but don't
|
||||
// allow an error.
|
||||
if (Body->Codegen() == 0)
|
||||
return 0;
|
||||
|
||||
// Emit the step value.
|
||||
Value *StepVal;
|
||||
if (Step) {
|
||||
StepVal = Step->Codegen();
|
||||
if (StepVal == 0) return 0;
|
||||
} else {
|
||||
// If not specified, use 1.0.
|
||||
StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
|
||||
}
|
||||
|
||||
Value *NextVar = Builder.CreateAdd(Variable, StepVal, "nextvar");
|
||||
|
||||
// Compute the end condition.
|
||||
Value *EndCond = End->Codegen();
|
||||
if (EndCond == 0) return EndCond;
|
||||
|
||||
// Convert condition to a bool by comparing equal to 0.0.
|
||||
EndCond = Builder.CreateFCmpONE(EndCond,
|
||||
ConstantFP::get(getGlobalContext(), APFloat(0.0)),
|
||||
"loopcond");
|
||||
|
||||
// Create the "after loop" block and insert it.
|
||||
BasicBlock *LoopEndBB = Builder.GetInsertBlock();
|
||||
BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
|
||||
|
||||
// Insert the conditional branch into the end of LoopEndBB.
|
||||
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
|
||||
|
||||
// Any new code will be inserted in AfterBB.
|
||||
Builder.SetInsertPoint(AfterBB);
|
||||
|
||||
// Add a new entry to the PHI node for the backedge.
|
||||
Variable->addIncoming(NextVar, LoopEndBB);
|
||||
|
||||
// Restore the unshadowed variable.
|
||||
if (OldVal)
|
||||
NamedValues[VarName] = OldVal;
|
||||
else
|
||||
NamedValues.erase(VarName);
|
||||
|
||||
|
||||
// for expr always returns 0.0.
|
||||
return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
|
||||
}
|
||||
|
||||
Function *PrototypeAST::Codegen() {
|
||||
// Make the function type: double(double,double) etc.
|
||||
std::vector<const Type*> Doubles(Args.size(),
|
||||
Type::getDoubleTy(getGlobalContext()));
|
||||
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
|
||||
Doubles, false);
|
||||
|
||||
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
|
||||
|
||||
// If F conflicted, there was already something named 'Name'. If it has a
|
||||
// body, don't allow redefinition or reextern.
|
||||
if (F->getName() != Name) {
|
||||
// Delete the one we just made and get the existing one.
|
||||
F->eraseFromParent();
|
||||
F = TheModule->getFunction(Name);
|
||||
|
||||
// If F already has a body, reject this.
|
||||
if (!F->empty()) {
|
||||
ErrorF("redefinition of function");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If F took a different number of args, reject.
|
||||
if (F->arg_size() != Args.size()) {
|
||||
ErrorF("redefinition of function with different # args");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Set names for all arguments.
|
||||
unsigned Idx = 0;
|
||||
for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
|
||||
++AI, ++Idx) {
|
||||
AI->setName(Args[Idx]);
|
||||
|
||||
// Add arguments to variable symbol table.
|
||||
NamedValues[Args[Idx]] = AI;
|
||||
}
|
||||
|
||||
return F;
|
||||
}
|
||||
|
||||
Function *FunctionAST::Codegen() {
|
||||
NamedValues.clear();
|
||||
|
||||
Function *TheFunction = Proto->Codegen();
|
||||
if (TheFunction == 0)
|
||||
return 0;
|
||||
|
||||
// Create a new basic block to start insertion into.
|
||||
BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
|
||||
Builder.SetInsertPoint(BB);
|
||||
|
||||
if (Value *RetVal = Body->Codegen()) {
|
||||
// Finish off the function.
|
||||
Builder.CreateRet(RetVal);
|
||||
|
||||
// Validate the generated code, checking for consistency.
|
||||
verifyFunction(*TheFunction);
|
||||
|
||||
// Optimize the function.
|
||||
TheFPM->run(*TheFunction);
|
||||
|
||||
return TheFunction;
|
||||
}
|
||||
|
||||
// Error reading body, remove function.
|
||||
TheFunction->eraseFromParent();
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Top-Level parsing and JIT Driver
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static ExecutionEngine *TheExecutionEngine;
|
||||
|
||||
static void HandleDefinition() {
|
||||
if (FunctionAST *F = ParseDefinition()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
fprintf(stderr, "Read function definition:");
|
||||
LF->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleExtern() {
|
||||
if (PrototypeAST *P = ParseExtern()) {
|
||||
if (Function *F = P->Codegen()) {
|
||||
fprintf(stderr, "Read extern: ");
|
||||
F->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleTopLevelExpression() {
|
||||
// Evaluate a top-level expression into an anonymous function.
|
||||
if (FunctionAST *F = ParseTopLevelExpr()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
// JIT the function, returning a function pointer.
|
||||
void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
|
||||
|
||||
// Cast it to the right type (takes no arguments, returns a double) so we
|
||||
// can call it as a native function.
|
||||
double (*FP)() = (double (*)())(intptr_t)FPtr;
|
||||
fprintf(stderr, "Evaluated to %f\n", FP());
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
/// top ::= definition | external | expression | ';'
|
||||
static void MainLoop() {
|
||||
while (1) {
|
||||
fprintf(stderr, "ready> ");
|
||||
switch (CurTok) {
|
||||
case tok_eof: return;
|
||||
case ';': getNextToken(); break; // ignore top-level semicolons.
|
||||
case tok_def: HandleDefinition(); break;
|
||||
case tok_extern: HandleExtern(); break;
|
||||
default: HandleTopLevelExpression(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// "Library" functions that can be "extern'd" from user code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// putchard - putchar that takes a double and returns 0.
|
||||
extern "C"
|
||||
double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Main driver code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
int main() {
|
||||
InitializeNativeTarget();
|
||||
LLVMContext &Context = getGlobalContext();
|
||||
|
||||
// Install standard binary operators.
|
||||
// 1 is lowest precedence.
|
||||
BinopPrecedence['<'] = 10;
|
||||
BinopPrecedence['+'] = 20;
|
||||
BinopPrecedence['-'] = 20;
|
||||
BinopPrecedence['*'] = 40; // highest.
|
||||
|
||||
// Prime the first token.
|
||||
fprintf(stderr, "ready> ");
|
||||
getNextToken();
|
||||
|
||||
// Make the module, which holds all the code.
|
||||
TheModule = new Module("my cool jit", Context);
|
||||
|
||||
// Create the JIT. This takes ownership of the module.
|
||||
std::string ErrStr;
|
||||
TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
|
||||
if (!TheExecutionEngine) {
|
||||
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
FunctionPassManager OurFPM(TheModule);
|
||||
|
||||
// Set up the optimizer pipeline. Start with registering info about how the
|
||||
// target lays out data structures.
|
||||
OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
|
||||
// Do simple "peephole" optimizations and bit-twiddling optzns.
|
||||
OurFPM.add(createInstructionCombiningPass());
|
||||
// Reassociate expressions.
|
||||
OurFPM.add(createReassociatePass());
|
||||
// Eliminate Common SubExpressions.
|
||||
OurFPM.add(createGVNPass());
|
||||
// Simplify the control flow graph (deleting unreachable blocks, etc).
|
||||
OurFPM.add(createCFGSimplificationPass());
|
||||
|
||||
OurFPM.doInitialization();
|
||||
|
||||
// Set the global so the code gen can use this.
|
||||
TheFPM = &OurFPM;
|
||||
|
||||
// Run the main "interpreter loop" now.
|
||||
MainLoop();
|
||||
|
||||
TheFPM = 0;
|
||||
|
||||
// Print out all of the generated code.
|
||||
TheModule->dump();
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS core jit interpreter native)
|
||||
|
||||
add_llvm_example(Kaleidoscope-Ch6
|
||||
toy.cpp
|
||||
)
|
@ -1,15 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Chapter6/Makefile -------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../../..
|
||||
TOOLNAME = Kaleidoscope-Ch6
|
||||
EXAMPLE_TOOL = 1
|
||||
|
||||
LINK_COMPONENTS := core jit native
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,973 +0,0 @@
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/ExecutionEngine/ExecutionEngine.h"
|
||||
#include "llvm/ExecutionEngine/JIT.h"
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/PassManager.h"
|
||||
#include "llvm/Analysis/Verifier.h"
|
||||
#include "llvm/Target/TargetData.h"
|
||||
#include "llvm/Target/TargetSelect.h"
|
||||
#include "llvm/Transforms/Scalar.h"
|
||||
#include "llvm/Support/IRBuilder.h"
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
using namespace llvm;
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Lexer
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
|
||||
// of these for known things.
|
||||
enum Token {
|
||||
tok_eof = -1,
|
||||
|
||||
// commands
|
||||
tok_def = -2, tok_extern = -3,
|
||||
|
||||
// primary
|
||||
tok_identifier = -4, tok_number = -5,
|
||||
|
||||
// control
|
||||
tok_if = -6, tok_then = -7, tok_else = -8,
|
||||
tok_for = -9, tok_in = -10,
|
||||
|
||||
// operators
|
||||
tok_binary = -11, tok_unary = -12
|
||||
};
|
||||
|
||||
static std::string IdentifierStr; // Filled in if tok_identifier
|
||||
static double NumVal; // Filled in if tok_number
|
||||
|
||||
/// gettok - Return the next token from standard input.
|
||||
static int gettok() {
|
||||
static int LastChar = ' ';
|
||||
|
||||
// Skip any whitespace.
|
||||
while (isspace(LastChar))
|
||||
LastChar = getchar();
|
||||
|
||||
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
|
||||
IdentifierStr = LastChar;
|
||||
while (isalnum((LastChar = getchar())))
|
||||
IdentifierStr += LastChar;
|
||||
|
||||
if (IdentifierStr == "def") return tok_def;
|
||||
if (IdentifierStr == "extern") return tok_extern;
|
||||
if (IdentifierStr == "if") return tok_if;
|
||||
if (IdentifierStr == "then") return tok_then;
|
||||
if (IdentifierStr == "else") return tok_else;
|
||||
if (IdentifierStr == "for") return tok_for;
|
||||
if (IdentifierStr == "in") return tok_in;
|
||||
if (IdentifierStr == "binary") return tok_binary;
|
||||
if (IdentifierStr == "unary") return tok_unary;
|
||||
return tok_identifier;
|
||||
}
|
||||
|
||||
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
|
||||
std::string NumStr;
|
||||
do {
|
||||
NumStr += LastChar;
|
||||
LastChar = getchar();
|
||||
} while (isdigit(LastChar) || LastChar == '.');
|
||||
|
||||
NumVal = strtod(NumStr.c_str(), 0);
|
||||
return tok_number;
|
||||
}
|
||||
|
||||
if (LastChar == '#') {
|
||||
// Comment until end of line.
|
||||
do LastChar = getchar();
|
||||
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
|
||||
|
||||
if (LastChar != EOF)
|
||||
return gettok();
|
||||
}
|
||||
|
||||
// Check for end of file. Don't eat the EOF.
|
||||
if (LastChar == EOF)
|
||||
return tok_eof;
|
||||
|
||||
// Otherwise, just return the character as its ascii value.
|
||||
int ThisChar = LastChar;
|
||||
LastChar = getchar();
|
||||
return ThisChar;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Abstract Syntax Tree (aka Parse Tree)
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// ExprAST - Base class for all expression nodes.
|
||||
class ExprAST {
|
||||
public:
|
||||
virtual ~ExprAST() {}
|
||||
virtual Value *Codegen() = 0;
|
||||
};
|
||||
|
||||
/// NumberExprAST - Expression class for numeric literals like "1.0".
|
||||
class NumberExprAST : public ExprAST {
|
||||
double Val;
|
||||
public:
|
||||
NumberExprAST(double val) : Val(val) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// VariableExprAST - Expression class for referencing a variable, like "a".
|
||||
class VariableExprAST : public ExprAST {
|
||||
std::string Name;
|
||||
public:
|
||||
VariableExprAST(const std::string &name) : Name(name) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// UnaryExprAST - Expression class for a unary operator.
|
||||
class UnaryExprAST : public ExprAST {
|
||||
char Opcode;
|
||||
ExprAST *Operand;
|
||||
public:
|
||||
UnaryExprAST(char opcode, ExprAST *operand)
|
||||
: Opcode(opcode), Operand(operand) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// BinaryExprAST - Expression class for a binary operator.
|
||||
class BinaryExprAST : public ExprAST {
|
||||
char Op;
|
||||
ExprAST *LHS, *RHS;
|
||||
public:
|
||||
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
|
||||
: Op(op), LHS(lhs), RHS(rhs) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// CallExprAST - Expression class for function calls.
|
||||
class CallExprAST : public ExprAST {
|
||||
std::string Callee;
|
||||
std::vector<ExprAST*> Args;
|
||||
public:
|
||||
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
|
||||
: Callee(callee), Args(args) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// IfExprAST - Expression class for if/then/else.
|
||||
class IfExprAST : public ExprAST {
|
||||
ExprAST *Cond, *Then, *Else;
|
||||
public:
|
||||
IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
|
||||
: Cond(cond), Then(then), Else(_else) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// ForExprAST - Expression class for for/in.
|
||||
class ForExprAST : public ExprAST {
|
||||
std::string VarName;
|
||||
ExprAST *Start, *End, *Step, *Body;
|
||||
public:
|
||||
ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
|
||||
ExprAST *step, ExprAST *body)
|
||||
: VarName(varname), Start(start), End(end), Step(step), Body(body) {}
|
||||
virtual Value *Codegen();
|
||||
};
|
||||
|
||||
/// PrototypeAST - This class represents the "prototype" for a function,
|
||||
/// which captures its name, and its argument names (thus implicitly the number
|
||||
/// of arguments the function takes), as well as if it is an operator.
|
||||
class PrototypeAST {
|
||||
std::string Name;
|
||||
std::vector<std::string> Args;
|
||||
bool isOperator;
|
||||
unsigned Precedence; // Precedence if a binary op.
|
||||
public:
|
||||
PrototypeAST(const std::string &name, const std::vector<std::string> &args,
|
||||
bool isoperator = false, unsigned prec = 0)
|
||||
: Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
|
||||
|
||||
bool isUnaryOp() const { return isOperator && Args.size() == 1; }
|
||||
bool isBinaryOp() const { return isOperator && Args.size() == 2; }
|
||||
|
||||
char getOperatorName() const {
|
||||
assert(isUnaryOp() || isBinaryOp());
|
||||
return Name[Name.size()-1];
|
||||
}
|
||||
|
||||
unsigned getBinaryPrecedence() const { return Precedence; }
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
/// FunctionAST - This class represents a function definition itself.
|
||||
class FunctionAST {
|
||||
PrototypeAST *Proto;
|
||||
ExprAST *Body;
|
||||
public:
|
||||
FunctionAST(PrototypeAST *proto, ExprAST *body)
|
||||
: Proto(proto), Body(body) {}
|
||||
|
||||
Function *Codegen();
|
||||
};
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Parser
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
|
||||
/// token the parser is looking at. getNextToken reads another token from the
|
||||
/// lexer and updates CurTok with its results.
|
||||
static int CurTok;
|
||||
static int getNextToken() {
|
||||
return CurTok = gettok();
|
||||
}
|
||||
|
||||
/// BinopPrecedence - This holds the precedence for each binary operator that is
|
||||
/// defined.
|
||||
static std::map<char, int> BinopPrecedence;
|
||||
|
||||
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
|
||||
static int GetTokPrecedence() {
|
||||
if (!isascii(CurTok))
|
||||
return -1;
|
||||
|
||||
// Make sure it's a declared binop.
|
||||
int TokPrec = BinopPrecedence[CurTok];
|
||||
if (TokPrec <= 0) return -1;
|
||||
return TokPrec;
|
||||
}
|
||||
|
||||
/// Error* - These are little helper functions for error handling.
|
||||
ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
|
||||
PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
|
||||
FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
static ExprAST *ParseExpression();
|
||||
|
||||
/// identifierexpr
|
||||
/// ::= identifier
|
||||
/// ::= identifier '(' expression* ')'
|
||||
static ExprAST *ParseIdentifierExpr() {
|
||||
std::string IdName = IdentifierStr;
|
||||
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '(') // Simple variable ref.
|
||||
return new VariableExprAST(IdName);
|
||||
|
||||
// Call.
|
||||
getNextToken(); // eat (
|
||||
std::vector<ExprAST*> Args;
|
||||
if (CurTok != ')') {
|
||||
while (1) {
|
||||
ExprAST *Arg = ParseExpression();
|
||||
if (!Arg) return 0;
|
||||
Args.push_back(Arg);
|
||||
|
||||
if (CurTok == ')') break;
|
||||
|
||||
if (CurTok != ',')
|
||||
return Error("Expected ')' or ',' in argument list");
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
// Eat the ')'.
|
||||
getNextToken();
|
||||
|
||||
return new CallExprAST(IdName, Args);
|
||||
}
|
||||
|
||||
/// numberexpr ::= number
|
||||
static ExprAST *ParseNumberExpr() {
|
||||
ExprAST *Result = new NumberExprAST(NumVal);
|
||||
getNextToken(); // consume the number
|
||||
return Result;
|
||||
}
|
||||
|
||||
/// parenexpr ::= '(' expression ')'
|
||||
static ExprAST *ParseParenExpr() {
|
||||
getNextToken(); // eat (.
|
||||
ExprAST *V = ParseExpression();
|
||||
if (!V) return 0;
|
||||
|
||||
if (CurTok != ')')
|
||||
return Error("expected ')'");
|
||||
getNextToken(); // eat ).
|
||||
return V;
|
||||
}
|
||||
|
||||
/// ifexpr ::= 'if' expression 'then' expression 'else' expression
|
||||
static ExprAST *ParseIfExpr() {
|
||||
getNextToken(); // eat the if.
|
||||
|
||||
// condition.
|
||||
ExprAST *Cond = ParseExpression();
|
||||
if (!Cond) return 0;
|
||||
|
||||
if (CurTok != tok_then)
|
||||
return Error("expected then");
|
||||
getNextToken(); // eat the then
|
||||
|
||||
ExprAST *Then = ParseExpression();
|
||||
if (Then == 0) return 0;
|
||||
|
||||
if (CurTok != tok_else)
|
||||
return Error("expected else");
|
||||
|
||||
getNextToken();
|
||||
|
||||
ExprAST *Else = ParseExpression();
|
||||
if (!Else) return 0;
|
||||
|
||||
return new IfExprAST(Cond, Then, Else);
|
||||
}
|
||||
|
||||
/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
|
||||
static ExprAST *ParseForExpr() {
|
||||
getNextToken(); // eat the for.
|
||||
|
||||
if (CurTok != tok_identifier)
|
||||
return Error("expected identifier after for");
|
||||
|
||||
std::string IdName = IdentifierStr;
|
||||
getNextToken(); // eat identifier.
|
||||
|
||||
if (CurTok != '=')
|
||||
return Error("expected '=' after for");
|
||||
getNextToken(); // eat '='.
|
||||
|
||||
|
||||
ExprAST *Start = ParseExpression();
|
||||
if (Start == 0) return 0;
|
||||
if (CurTok != ',')
|
||||
return Error("expected ',' after for start value");
|
||||
getNextToken();
|
||||
|
||||
ExprAST *End = ParseExpression();
|
||||
if (End == 0) return 0;
|
||||
|
||||
// The step value is optional.
|
||||
ExprAST *Step = 0;
|
||||
if (CurTok == ',') {
|
||||
getNextToken();
|
||||
Step = ParseExpression();
|
||||
if (Step == 0) return 0;
|
||||
}
|
||||
|
||||
if (CurTok != tok_in)
|
||||
return Error("expected 'in' after for");
|
||||
getNextToken(); // eat 'in'.
|
||||
|
||||
ExprAST *Body = ParseExpression();
|
||||
if (Body == 0) return 0;
|
||||
|
||||
return new ForExprAST(IdName, Start, End, Step, Body);
|
||||
}
|
||||
|
||||
/// primary
|
||||
/// ::= identifierexpr
|
||||
/// ::= numberexpr
|
||||
/// ::= parenexpr
|
||||
/// ::= ifexpr
|
||||
/// ::= forexpr
|
||||
static ExprAST *ParsePrimary() {
|
||||
switch (CurTok) {
|
||||
default: return Error("unknown token when expecting an expression");
|
||||
case tok_identifier: return ParseIdentifierExpr();
|
||||
case tok_number: return ParseNumberExpr();
|
||||
case '(': return ParseParenExpr();
|
||||
case tok_if: return ParseIfExpr();
|
||||
case tok_for: return ParseForExpr();
|
||||
}
|
||||
}
|
||||
|
||||
/// unary
|
||||
/// ::= primary
|
||||
/// ::= '!' unary
|
||||
static ExprAST *ParseUnary() {
|
||||
// If the current token is not an operator, it must be a primary expr.
|
||||
if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
|
||||
return ParsePrimary();
|
||||
|
||||
// If this is a unary operator, read it.
|
||||
int Opc = CurTok;
|
||||
getNextToken();
|
||||
if (ExprAST *Operand = ParseUnary())
|
||||
return new UnaryExprAST(Opc, Operand);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// binoprhs
|
||||
/// ::= ('+' unary)*
|
||||
static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
|
||||
// If this is a binop, find its precedence.
|
||||
while (1) {
|
||||
int TokPrec = GetTokPrecedence();
|
||||
|
||||
// If this is a binop that binds at least as tightly as the current binop,
|
||||
// consume it, otherwise we are done.
|
||||
if (TokPrec < ExprPrec)
|
||||
return LHS;
|
||||
|
||||
// Okay, we know this is a binop.
|
||||
int BinOp = CurTok;
|
||||
getNextToken(); // eat binop
|
||||
|
||||
// Parse the unary expression after the binary operator.
|
||||
ExprAST *RHS = ParseUnary();
|
||||
if (!RHS) return 0;
|
||||
|
||||
// If BinOp binds less tightly with RHS than the operator after RHS, let
|
||||
// the pending operator take RHS as its LHS.
|
||||
int NextPrec = GetTokPrecedence();
|
||||
if (TokPrec < NextPrec) {
|
||||
RHS = ParseBinOpRHS(TokPrec+1, RHS);
|
||||
if (RHS == 0) return 0;
|
||||
}
|
||||
|
||||
// Merge LHS/RHS.
|
||||
LHS = new BinaryExprAST(BinOp, LHS, RHS);
|
||||
}
|
||||
}
|
||||
|
||||
/// expression
|
||||
/// ::= unary binoprhs
|
||||
///
|
||||
static ExprAST *ParseExpression() {
|
||||
ExprAST *LHS = ParseUnary();
|
||||
if (!LHS) return 0;
|
||||
|
||||
return ParseBinOpRHS(0, LHS);
|
||||
}
|
||||
|
||||
/// prototype
|
||||
/// ::= id '(' id* ')'
|
||||
/// ::= binary LETTER number? (id, id)
|
||||
/// ::= unary LETTER (id)
|
||||
static PrototypeAST *ParsePrototype() {
|
||||
std::string FnName;
|
||||
|
||||
unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
|
||||
unsigned BinaryPrecedence = 30;
|
||||
|
||||
switch (CurTok) {
|
||||
default:
|
||||
return ErrorP("Expected function name in prototype");
|
||||
case tok_identifier:
|
||||
FnName = IdentifierStr;
|
||||
Kind = 0;
|
||||
getNextToken();
|
||||
break;
|
||||
case tok_unary:
|
||||
getNextToken();
|
||||
if (!isascii(CurTok))
|
||||
return ErrorP("Expected unary operator");
|
||||
FnName = "unary";
|
||||
FnName += (char)CurTok;
|
||||
Kind = 1;
|
||||
getNextToken();
|
||||
break;
|
||||
case tok_binary:
|
||||
getNextToken();
|
||||
if (!isascii(CurTok))
|
||||
return ErrorP("Expected binary operator");
|
||||
FnName = "binary";
|
||||
FnName += (char)CurTok;
|
||||
Kind = 2;
|
||||
getNextToken();
|
||||
|
||||
// Read the precedence if present.
|
||||
if (CurTok == tok_number) {
|
||||
if (NumVal < 1 || NumVal > 100)
|
||||
return ErrorP("Invalid precedecnce: must be 1..100");
|
||||
BinaryPrecedence = (unsigned)NumVal;
|
||||
getNextToken();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (CurTok != '(')
|
||||
return ErrorP("Expected '(' in prototype");
|
||||
|
||||
std::vector<std::string> ArgNames;
|
||||
while (getNextToken() == tok_identifier)
|
||||
ArgNames.push_back(IdentifierStr);
|
||||
if (CurTok != ')')
|
||||
return ErrorP("Expected ')' in prototype");
|
||||
|
||||
// success.
|
||||
getNextToken(); // eat ')'.
|
||||
|
||||
// Verify right number of names for operator.
|
||||
if (Kind && ArgNames.size() != Kind)
|
||||
return ErrorP("Invalid number of operands for operator");
|
||||
|
||||
return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
|
||||
}
|
||||
|
||||
/// definition ::= 'def' prototype expression
|
||||
static FunctionAST *ParseDefinition() {
|
||||
getNextToken(); // eat def.
|
||||
PrototypeAST *Proto = ParsePrototype();
|
||||
if (Proto == 0) return 0;
|
||||
|
||||
if (ExprAST *E = ParseExpression())
|
||||
return new FunctionAST(Proto, E);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// toplevelexpr ::= expression
|
||||
static FunctionAST *ParseTopLevelExpr() {
|
||||
if (ExprAST *E = ParseExpression()) {
|
||||
// Make an anonymous proto.
|
||||
PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
|
||||
return new FunctionAST(Proto, E);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// external ::= 'extern' prototype
|
||||
static PrototypeAST *ParseExtern() {
|
||||
getNextToken(); // eat extern.
|
||||
return ParsePrototype();
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Code Generation
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static Module *TheModule;
|
||||
static IRBuilder<> Builder(getGlobalContext());
|
||||
static std::map<std::string, Value*> NamedValues;
|
||||
static FunctionPassManager *TheFPM;
|
||||
|
||||
Value *ErrorV(const char *Str) { Error(Str); return 0; }
|
||||
|
||||
Value *NumberExprAST::Codegen() {
|
||||
return ConstantFP::get(getGlobalContext(), APFloat(Val));
|
||||
}
|
||||
|
||||
Value *VariableExprAST::Codegen() {
|
||||
// Look this variable up in the function.
|
||||
Value *V = NamedValues[Name];
|
||||
return V ? V : ErrorV("Unknown variable name");
|
||||
}
|
||||
|
||||
Value *UnaryExprAST::Codegen() {
|
||||
Value *OperandV = Operand->Codegen();
|
||||
if (OperandV == 0) return 0;
|
||||
|
||||
Function *F = TheModule->getFunction(std::string("unary")+Opcode);
|
||||
if (F == 0)
|
||||
return ErrorV("Unknown unary operator");
|
||||
|
||||
return Builder.CreateCall(F, OperandV, "unop");
|
||||
}
|
||||
|
||||
Value *BinaryExprAST::Codegen() {
|
||||
Value *L = LHS->Codegen();
|
||||
Value *R = RHS->Codegen();
|
||||
if (L == 0 || R == 0) return 0;
|
||||
|
||||
switch (Op) {
|
||||
case '+': return Builder.CreateAdd(L, R, "addtmp");
|
||||
case '-': return Builder.CreateSub(L, R, "subtmp");
|
||||
case '*': return Builder.CreateMul(L, R, "multmp");
|
||||
case '<':
|
||||
L = Builder.CreateFCmpULT(L, R, "cmptmp");
|
||||
// Convert bool 0/1 to double 0.0 or 1.0
|
||||
return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
|
||||
"booltmp");
|
||||
default: break;
|
||||
}
|
||||
|
||||
// If it wasn't a builtin binary operator, it must be a user defined one. Emit
|
||||
// a call to it.
|
||||
Function *F = TheModule->getFunction(std::string("binary")+Op);
|
||||
assert(F && "binary operator not found!");
|
||||
|
||||
Value *Ops[] = { L, R };
|
||||
return Builder.CreateCall(F, Ops, Ops+2, "binop");
|
||||
}
|
||||
|
||||
Value *CallExprAST::Codegen() {
|
||||
// Look up the name in the global module table.
|
||||
Function *CalleeF = TheModule->getFunction(Callee);
|
||||
if (CalleeF == 0)
|
||||
return ErrorV("Unknown function referenced");
|
||||
|
||||
// If argument mismatch error.
|
||||
if (CalleeF->arg_size() != Args.size())
|
||||
return ErrorV("Incorrect # arguments passed");
|
||||
|
||||
std::vector<Value*> ArgsV;
|
||||
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
|
||||
ArgsV.push_back(Args[i]->Codegen());
|
||||
if (ArgsV.back() == 0) return 0;
|
||||
}
|
||||
|
||||
return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
|
||||
}
|
||||
|
||||
Value *IfExprAST::Codegen() {
|
||||
Value *CondV = Cond->Codegen();
|
||||
if (CondV == 0) return 0;
|
||||
|
||||
// Convert condition to a bool by comparing equal to 0.0.
|
||||
CondV = Builder.CreateFCmpONE(CondV,
|
||||
ConstantFP::get(getGlobalContext(), APFloat(0.0)),
|
||||
"ifcond");
|
||||
|
||||
Function *TheFunction = Builder.GetInsertBlock()->getParent();
|
||||
|
||||
// Create blocks for the then and else cases. Insert the 'then' block at the
|
||||
// end of the function.
|
||||
BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
|
||||
BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
|
||||
BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
|
||||
|
||||
Builder.CreateCondBr(CondV, ThenBB, ElseBB);
|
||||
|
||||
// Emit then value.
|
||||
Builder.SetInsertPoint(ThenBB);
|
||||
|
||||
Value *ThenV = Then->Codegen();
|
||||
if (ThenV == 0) return 0;
|
||||
|
||||
Builder.CreateBr(MergeBB);
|
||||
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
|
||||
ThenBB = Builder.GetInsertBlock();
|
||||
|
||||
// Emit else block.
|
||||
TheFunction->getBasicBlockList().push_back(ElseBB);
|
||||
Builder.SetInsertPoint(ElseBB);
|
||||
|
||||
Value *ElseV = Else->Codegen();
|
||||
if (ElseV == 0) return 0;
|
||||
|
||||
Builder.CreateBr(MergeBB);
|
||||
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
|
||||
ElseBB = Builder.GetInsertBlock();
|
||||
|
||||
// Emit merge block.
|
||||
TheFunction->getBasicBlockList().push_back(MergeBB);
|
||||
Builder.SetInsertPoint(MergeBB);
|
||||
PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
|
||||
"iftmp");
|
||||
|
||||
PN->addIncoming(ThenV, ThenBB);
|
||||
PN->addIncoming(ElseV, ElseBB);
|
||||
return PN;
|
||||
}
|
||||
|
||||
Value *ForExprAST::Codegen() {
|
||||
// Output this as:
|
||||
// ...
|
||||
// start = startexpr
|
||||
// goto loop
|
||||
// loop:
|
||||
// variable = phi [start, loopheader], [nextvariable, loopend]
|
||||
// ...
|
||||
// bodyexpr
|
||||
// ...
|
||||
// loopend:
|
||||
// step = stepexpr
|
||||
// nextvariable = variable + step
|
||||
// endcond = endexpr
|
||||
// br endcond, loop, endloop
|
||||
// outloop:
|
||||
|
||||
// Emit the start code first, without 'variable' in scope.
|
||||
Value *StartVal = Start->Codegen();
|
||||
if (StartVal == 0) return 0;
|
||||
|
||||
// Make the new basic block for the loop header, inserting after current
|
||||
// block.
|
||||
Function *TheFunction = Builder.GetInsertBlock()->getParent();
|
||||
BasicBlock *PreheaderBB = Builder.GetInsertBlock();
|
||||
BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
|
||||
|
||||
// Insert an explicit fall through from the current block to the LoopBB.
|
||||
Builder.CreateBr(LoopBB);
|
||||
|
||||
// Start insertion in LoopBB.
|
||||
Builder.SetInsertPoint(LoopBB);
|
||||
|
||||
// Start the PHI node with an entry for Start.
|
||||
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), VarName.c_str());
|
||||
Variable->addIncoming(StartVal, PreheaderBB);
|
||||
|
||||
// Within the loop, the variable is defined equal to the PHI node. If it
|
||||
// shadows an existing variable, we have to restore it, so save it now.
|
||||
Value *OldVal = NamedValues[VarName];
|
||||
NamedValues[VarName] = Variable;
|
||||
|
||||
// Emit the body of the loop. This, like any other expr, can change the
|
||||
// current BB. Note that we ignore the value computed by the body, but don't
|
||||
// allow an error.
|
||||
if (Body->Codegen() == 0)
|
||||
return 0;
|
||||
|
||||
// Emit the step value.
|
||||
Value *StepVal;
|
||||
if (Step) {
|
||||
StepVal = Step->Codegen();
|
||||
if (StepVal == 0) return 0;
|
||||
} else {
|
||||
// If not specified, use 1.0.
|
||||
StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
|
||||
}
|
||||
|
||||
Value *NextVar = Builder.CreateAdd(Variable, StepVal, "nextvar");
|
||||
|
||||
// Compute the end condition.
|
||||
Value *EndCond = End->Codegen();
|
||||
if (EndCond == 0) return EndCond;
|
||||
|
||||
// Convert condition to a bool by comparing equal to 0.0.
|
||||
EndCond = Builder.CreateFCmpONE(EndCond,
|
||||
ConstantFP::get(getGlobalContext(), APFloat(0.0)),
|
||||
"loopcond");
|
||||
|
||||
// Create the "after loop" block and insert it.
|
||||
BasicBlock *LoopEndBB = Builder.GetInsertBlock();
|
||||
BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
|
||||
|
||||
// Insert the conditional branch into the end of LoopEndBB.
|
||||
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
|
||||
|
||||
// Any new code will be inserted in AfterBB.
|
||||
Builder.SetInsertPoint(AfterBB);
|
||||
|
||||
// Add a new entry to the PHI node for the backedge.
|
||||
Variable->addIncoming(NextVar, LoopEndBB);
|
||||
|
||||
// Restore the unshadowed variable.
|
||||
if (OldVal)
|
||||
NamedValues[VarName] = OldVal;
|
||||
else
|
||||
NamedValues.erase(VarName);
|
||||
|
||||
|
||||
// for expr always returns 0.0.
|
||||
return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
|
||||
}
|
||||
|
||||
Function *PrototypeAST::Codegen() {
|
||||
// Make the function type: double(double,double) etc.
|
||||
std::vector<const Type*> Doubles(Args.size(),
|
||||
Type::getDoubleTy(getGlobalContext()));
|
||||
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
|
||||
Doubles, false);
|
||||
|
||||
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
|
||||
|
||||
// If F conflicted, there was already something named 'Name'. If it has a
|
||||
// body, don't allow redefinition or reextern.
|
||||
if (F->getName() != Name) {
|
||||
// Delete the one we just made and get the existing one.
|
||||
F->eraseFromParent();
|
||||
F = TheModule->getFunction(Name);
|
||||
|
||||
// If F already has a body, reject this.
|
||||
if (!F->empty()) {
|
||||
ErrorF("redefinition of function");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If F took a different number of args, reject.
|
||||
if (F->arg_size() != Args.size()) {
|
||||
ErrorF("redefinition of function with different # args");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Set names for all arguments.
|
||||
unsigned Idx = 0;
|
||||
for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
|
||||
++AI, ++Idx) {
|
||||
AI->setName(Args[Idx]);
|
||||
|
||||
// Add arguments to variable symbol table.
|
||||
NamedValues[Args[Idx]] = AI;
|
||||
}
|
||||
|
||||
return F;
|
||||
}
|
||||
|
||||
Function *FunctionAST::Codegen() {
|
||||
NamedValues.clear();
|
||||
|
||||
Function *TheFunction = Proto->Codegen();
|
||||
if (TheFunction == 0)
|
||||
return 0;
|
||||
|
||||
// If this is an operator, install it.
|
||||
if (Proto->isBinaryOp())
|
||||
BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
|
||||
|
||||
// Create a new basic block to start insertion into.
|
||||
BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
|
||||
Builder.SetInsertPoint(BB);
|
||||
|
||||
if (Value *RetVal = Body->Codegen()) {
|
||||
// Finish off the function.
|
||||
Builder.CreateRet(RetVal);
|
||||
|
||||
// Validate the generated code, checking for consistency.
|
||||
verifyFunction(*TheFunction);
|
||||
|
||||
// Optimize the function.
|
||||
TheFPM->run(*TheFunction);
|
||||
|
||||
return TheFunction;
|
||||
}
|
||||
|
||||
// Error reading body, remove function.
|
||||
TheFunction->eraseFromParent();
|
||||
|
||||
if (Proto->isBinaryOp())
|
||||
BinopPrecedence.erase(Proto->getOperatorName());
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Top-Level parsing and JIT Driver
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
static ExecutionEngine *TheExecutionEngine;
|
||||
|
||||
static void HandleDefinition() {
|
||||
if (FunctionAST *F = ParseDefinition()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
fprintf(stderr, "Read function definition:");
|
||||
LF->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleExtern() {
|
||||
if (PrototypeAST *P = ParseExtern()) {
|
||||
if (Function *F = P->Codegen()) {
|
||||
fprintf(stderr, "Read extern: ");
|
||||
F->dump();
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
static void HandleTopLevelExpression() {
|
||||
// Evaluate a top-level expression into an anonymous function.
|
||||
if (FunctionAST *F = ParseTopLevelExpr()) {
|
||||
if (Function *LF = F->Codegen()) {
|
||||
// JIT the function, returning a function pointer.
|
||||
void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
|
||||
|
||||
// Cast it to the right type (takes no arguments, returns a double) so we
|
||||
// can call it as a native function.
|
||||
double (*FP)() = (double (*)())(intptr_t)FPtr;
|
||||
fprintf(stderr, "Evaluated to %f\n", FP());
|
||||
}
|
||||
} else {
|
||||
// Skip token for error recovery.
|
||||
getNextToken();
|
||||
}
|
||||
}
|
||||
|
||||
/// top ::= definition | external | expression | ';'
|
||||
static void MainLoop() {
|
||||
while (1) {
|
||||
fprintf(stderr, "ready> ");
|
||||
switch (CurTok) {
|
||||
case tok_eof: return;
|
||||
case ';': getNextToken(); break; // ignore top-level semicolons.
|
||||
case tok_def: HandleDefinition(); break;
|
||||
case tok_extern: HandleExtern(); break;
|
||||
default: HandleTopLevelExpression(); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// "Library" functions that can be "extern'd" from user code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// putchard - putchar that takes a double and returns 0.
|
||||
extern "C"
|
||||
double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// printd - printf that takes a double prints it as "%f\n", returning 0.
|
||||
extern "C"
|
||||
double printd(double X) {
|
||||
printf("%f\n", X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Main driver code.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
int main() {
|
||||
InitializeNativeTarget();
|
||||
LLVMContext &Context = getGlobalContext();
|
||||
|
||||
// Install standard binary operators.
|
||||
// 1 is lowest precedence.
|
||||
BinopPrecedence['<'] = 10;
|
||||
BinopPrecedence['+'] = 20;
|
||||
BinopPrecedence['-'] = 20;
|
||||
BinopPrecedence['*'] = 40; // highest.
|
||||
|
||||
// Prime the first token.
|
||||
fprintf(stderr, "ready> ");
|
||||
getNextToken();
|
||||
|
||||
// Make the module, which holds all the code.
|
||||
TheModule = new Module("my cool jit", Context);
|
||||
|
||||
// Create the JIT. This takes ownership of the module.
|
||||
std::string ErrStr;
|
||||
TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
|
||||
if (!TheExecutionEngine) {
|
||||
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
FunctionPassManager OurFPM(TheModule);
|
||||
|
||||
// Set up the optimizer pipeline. Start with registering info about how the
|
||||
// target lays out data structures.
|
||||
OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
|
||||
// Do simple "peephole" optimizations and bit-twiddling optzns.
|
||||
OurFPM.add(createInstructionCombiningPass());
|
||||
// Reassociate expressions.
|
||||
OurFPM.add(createReassociatePass());
|
||||
// Eliminate Common SubExpressions.
|
||||
OurFPM.add(createGVNPass());
|
||||
// Simplify the control flow graph (deleting unreachable blocks, etc).
|
||||
OurFPM.add(createCFGSimplificationPass());
|
||||
|
||||
OurFPM.doInitialization();
|
||||
|
||||
// Set the global so the code gen can use this.
|
||||
TheFPM = &OurFPM;
|
||||
|
||||
// Run the main "interpreter loop" now.
|
||||
MainLoop();
|
||||
|
||||
TheFPM = 0;
|
||||
|
||||
// Print out all of the generated code.
|
||||
TheModule->dump();
|
||||
|
||||
return 0;
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS core jit interpreter native)
|
||||
|
||||
add_llvm_example(Kaleidoscope-Ch7
|
||||
toy.cpp
|
||||
)
|
@ -1,16 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Chapter7/Makefile -------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL = ../../..
|
||||
TOOLNAME = Kaleidoscope-Ch7
|
||||
EXAMPLE_TOOL = 1
|
||||
REQUIRES_RTTI := 1
|
||||
|
||||
LINK_COMPONENTS := core jit native
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
File diff suppressed because it is too large
Load Diff
@ -1,15 +0,0 @@
|
||||
##===- examples/Kaleidoscope/Makefile ----------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL=../..
|
||||
|
||||
include $(LEVEL)/Makefile.config
|
||||
|
||||
PARALLEL_DIRS:= Chapter2 Chapter3 Chapter4 Chapter5 Chapter6 Chapter7
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,32 +0,0 @@
|
||||
##===- examples/Makefile -----------------------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL=..
|
||||
|
||||
include $(LEVEL)/Makefile.config
|
||||
|
||||
PARALLEL_DIRS:= BrainF Fibonacci HowToUseJIT Kaleidoscope ModuleMaker
|
||||
|
||||
ifeq ($(HAVE_PTHREAD),1)
|
||||
PARALLEL_DIRS += ParallelJIT
|
||||
endif
|
||||
|
||||
ifeq ($(LLVM_ON_UNIX),1)
|
||||
ifeq ($(ARCH),x86)
|
||||
PARALLEL_DIRS += ExceptionDemo
|
||||
endif
|
||||
ifeq ($(ARCH),x86_64)
|
||||
PARALLEL_DIRS += ExceptionDemo
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(filter $(BINDINGS_TO_BUILD),ocaml),ocaml)
|
||||
PARALLEL_DIRS += OCaml-Kaleidoscope
|
||||
endif
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,5 +0,0 @@
|
||||
set(LLVM_LINK_COMPONENTS bitwriter)
|
||||
|
||||
add_llvm_example(ModuleMaker
|
||||
ModuleMaker.cpp
|
||||
)
|
@ -1,14 +0,0 @@
|
||||
##===- examples/ModuleMaker/Makefile -----------------------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
LEVEL=../..
|
||||
TOOLNAME=ModuleMaker
|
||||
EXAMPLE_TOOL = 1
|
||||
LINK_COMPONENTS := bitwriter
|
||||
|
||||
include $(LEVEL)/Makefile.common
|
@ -1,64 +0,0 @@
|
||||
//===- examples/ModuleMaker/ModuleMaker.cpp - Example project ---*- C++ -*-===//
|
||||
//
|
||||
// The LLVM Compiler Infrastructure
|
||||
//
|
||||
// This file is distributed under the University of Illinois Open Source
|
||||
// License. See LICENSE.TXT for details.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This programs is a simple example that creates an LLVM module "from scratch",
|
||||
// emitting it as a bitcode file to standard out. This is just to show how
|
||||
// LLVM projects work and to demonstrate some of the LLVM APIs.
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#include "llvm/LLVMContext.h"
|
||||
#include "llvm/Module.h"
|
||||
#include "llvm/DerivedTypes.h"
|
||||
#include "llvm/Constants.h"
|
||||
#include "llvm/Instructions.h"
|
||||
#include "llvm/Bitcode/ReaderWriter.h"
|
||||
#include "llvm/Support/raw_ostream.h"
|
||||
using namespace llvm;
|
||||
|
||||
int main() {
|
||||
LLVMContext Context;
|
||||
|
||||
// Create the "module" or "program" or "translation unit" to hold the
|
||||
// function
|
||||
Module *M = new Module("test", Context);
|
||||
|
||||
// Create the main function: first create the type 'int ()'
|
||||
FunctionType *FT =
|
||||
FunctionType::get(Type::getInt32Ty(Context), /*not vararg*/false);
|
||||
|
||||
// By passing a module as the last parameter to the Function constructor,
|
||||
// it automatically gets appended to the Module.
|
||||
Function *F = Function::Create(FT, Function::ExternalLinkage, "main", M);
|
||||
|
||||
// Add a basic block to the function... again, it automatically inserts
|
||||
// because of the last argument.
|
||||
BasicBlock *BB = BasicBlock::Create(Context, "EntryBlock", F);
|
||||
|
||||
// Get pointers to the constant integers...
|
||||
Value *Two = ConstantInt::get(Type::getInt32Ty(Context), 2);
|
||||
Value *Three = ConstantInt::get(Type::getInt32Ty(Context), 3);
|
||||
|
||||
// Create the add instruction... does not insert...
|
||||
Instruction *Add = BinaryOperator::Create(Instruction::Add, Two, Three,
|
||||
"addresult");
|
||||
|
||||
// explicitly insert it into the basic block...
|
||||
BB->getInstList().push_back(Add);
|
||||
|
||||
// Create the return instruction and add it to the basic block
|
||||
BB->getInstList().push_back(ReturnInst::Create(Context, Add));
|
||||
|
||||
// Output the bitcode file to stdout
|
||||
WriteBitcodeToFile(M, outs());
|
||||
|
||||
// Delete the module and all of its contents.
|
||||
delete M;
|
||||
return 0;
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// ModuleMaker Sample project
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
This project is an extremely simple example of using some simple pieces of the
|
||||
LLVM API. The actual executable generated by this project simply emits an
|
||||
LLVM bytecode file to standard output. It is designed to show some basic
|
||||
usage of LLVM APIs, and how to link to LLVM libraries.
|
@ -1,22 +0,0 @@
|
||||
##===- examples/OCaml-Kaleidoscope/Chapter2/Makefile -------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
#
|
||||
# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 2.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL := ../../..
|
||||
TOOLNAME := OCaml-Kaleidoscope-Ch2
|
||||
EXAMPLE_TOOL := 1
|
||||
UsedComponents := core
|
||||
UsedOcamLibs := llvm
|
||||
|
||||
OCAMLCFLAGS += -pp camlp4of
|
||||
|
||||
include $(LEVEL)/bindings/ocaml/Makefile.ocaml
|
@ -1 +0,0 @@
|
||||
<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
|
@ -1,25 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Abstract Syntax Tree (aka Parse Tree)
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* expr - Base type for all expression nodes. *)
|
||||
type expr =
|
||||
(* variant for numeric literals like "1.0". *)
|
||||
| Number of float
|
||||
|
||||
(* variant for referencing a variable, like "a". *)
|
||||
| Variable of string
|
||||
|
||||
(* variant for a binary operator. *)
|
||||
| Binary of char * expr * expr
|
||||
|
||||
(* variant for function calls. *)
|
||||
| Call of string * expr array
|
||||
|
||||
(* proto - This type represents the "prototype" for a function, which captures
|
||||
* its name, and its argument names (thus implicitly the number of arguments the
|
||||
* function takes). *)
|
||||
type proto = Prototype of string * string array
|
||||
|
||||
(* func - This type represents a function definition itself. *)
|
||||
type func = Function of proto * expr
|
@ -1,52 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let rec lex = parser
|
||||
(* Skip any whitespace. *)
|
||||
| [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
|
||||
|
||||
(* identifier: [a-zA-Z][a-zA-Z0-9] *)
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
|
||||
(* number: [0-9.]+ *)
|
||||
| [< ' ('0' .. '9' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
|
||||
(* Comment until end of line. *)
|
||||
| [< ' ('#'); stream >] ->
|
||||
lex_comment stream
|
||||
|
||||
(* Otherwise, just return the character as its ascii value. *)
|
||||
| [< 'c; stream >] ->
|
||||
[< 'Token.Kwd c; lex stream >]
|
||||
|
||||
(* end of stream. *)
|
||||
| [< >] -> [< >]
|
||||
|
||||
and lex_number buffer = parser
|
||||
| [< ' ('0' .. '9' | '.' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
| [< stream=lex >] ->
|
||||
[< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
|
||||
|
||||
and lex_ident buffer = parser
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
| [< stream=lex >] ->
|
||||
match Buffer.contents buffer with
|
||||
| "def" -> [< 'Token.Def; stream >]
|
||||
| "extern" -> [< 'Token.Extern; stream >]
|
||||
| id -> [< 'Token.Ident id; stream >]
|
||||
|
||||
and lex_comment = parser
|
||||
| [< ' ('\n'); stream=lex >] -> stream
|
||||
| [< 'c; e=lex_comment >] -> e
|
||||
| [< >] -> [< >]
|
@ -1,122 +0,0 @@
|
||||
(*===---------------------------------------------------------------------===
|
||||
* Parser
|
||||
*===---------------------------------------------------------------------===*)
|
||||
|
||||
(* binop_precedence - This holds the precedence for each binary operator that is
|
||||
* defined *)
|
||||
let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
|
||||
|
||||
(* precedence - Get the precedence of the pending binary operator token. *)
|
||||
let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
|
||||
|
||||
(* primary
|
||||
* ::= identifier
|
||||
* ::= numberexpr
|
||||
* ::= parenexpr *)
|
||||
let rec parse_primary = parser
|
||||
(* numberexpr ::= number *)
|
||||
| [< 'Token.Number n >] -> Ast.Number n
|
||||
|
||||
(* parenexpr ::= '(' expression ')' *)
|
||||
| [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
|
||||
|
||||
(* identifierexpr
|
||||
* ::= identifier
|
||||
* ::= identifier '(' argumentexpr ')' *)
|
||||
| [< 'Token.Ident id; stream >] ->
|
||||
let rec parse_args accumulator = parser
|
||||
| [< e=parse_expr; stream >] ->
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
|
||||
| [< >] -> e :: accumulator
|
||||
end stream
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let rec parse_ident id = parser
|
||||
(* Call. *)
|
||||
| [< 'Token.Kwd '(';
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')'">] ->
|
||||
Ast.Call (id, Array.of_list (List.rev args))
|
||||
|
||||
(* Simple variable ref. *)
|
||||
| [< >] -> Ast.Variable id
|
||||
in
|
||||
parse_ident id stream
|
||||
|
||||
| [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
|
||||
|
||||
(* binoprhs
|
||||
* ::= ('+' primary)* *)
|
||||
and parse_bin_rhs expr_prec lhs stream =
|
||||
match Stream.peek stream with
|
||||
(* If this is a binop, find its precedence. *)
|
||||
| Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
|
||||
let token_prec = precedence c in
|
||||
|
||||
(* If this is a binop that binds at least as tightly as the current binop,
|
||||
* consume it, otherwise we are done. *)
|
||||
if token_prec < expr_prec then lhs else begin
|
||||
(* Eat the binop. *)
|
||||
Stream.junk stream;
|
||||
|
||||
(* Parse the primary expression after the binary operator. *)
|
||||
let rhs = parse_primary stream in
|
||||
|
||||
(* Okay, we know this is a binop. *)
|
||||
let rhs =
|
||||
match Stream.peek stream with
|
||||
| Some (Token.Kwd c2) ->
|
||||
(* If BinOp binds less tightly with rhs than the operator after
|
||||
* rhs, let the pending operator take rhs as its lhs. *)
|
||||
let next_prec = precedence c2 in
|
||||
if token_prec < next_prec
|
||||
then parse_bin_rhs (token_prec + 1) rhs stream
|
||||
else rhs
|
||||
| _ -> rhs
|
||||
in
|
||||
|
||||
(* Merge lhs/rhs. *)
|
||||
let lhs = Ast.Binary (c, lhs, rhs) in
|
||||
parse_bin_rhs expr_prec lhs stream
|
||||
end
|
||||
| _ -> lhs
|
||||
|
||||
(* expression
|
||||
* ::= primary binoprhs *)
|
||||
and parse_expr = parser
|
||||
| [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
|
||||
|
||||
(* prototype
|
||||
* ::= id '(' id* ')' *)
|
||||
let parse_prototype =
|
||||
let rec parse_args accumulator = parser
|
||||
| [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
|
||||
parser
|
||||
| [< 'Token.Ident id;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
(* success. *)
|
||||
Ast.Prototype (id, Array.of_list (List.rev args))
|
||||
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected function name in prototype")
|
||||
|
||||
(* definition ::= 'def' prototype expression *)
|
||||
let parse_definition = parser
|
||||
| [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
|
||||
Ast.Function (p, e)
|
||||
|
||||
(* toplevelexpr ::= expression *)
|
||||
let parse_toplevel = parser
|
||||
| [< e=parse_expr >] ->
|
||||
(* Make an anonymous proto. *)
|
||||
Ast.Function (Ast.Prototype ("", [||]), e)
|
||||
|
||||
(* external ::= 'extern' prototype *)
|
||||
let parse_extern = parser
|
||||
| [< 'Token.Extern; e=parse_prototype >] -> e
|
@ -1,15 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer Tokens
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
|
||||
* these others for known things. *)
|
||||
type token =
|
||||
(* commands *)
|
||||
| Def | Extern
|
||||
|
||||
(* primary *)
|
||||
| Ident of string | Number of float
|
||||
|
||||
(* unknown *)
|
||||
| Kwd of char
|
@ -1,34 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Top-Level parsing and JIT Driver
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* top ::= definition | external | expression | ';' *)
|
||||
let rec main_loop stream =
|
||||
match Stream.peek stream with
|
||||
| None -> ()
|
||||
|
||||
(* ignore top-level semicolons. *)
|
||||
| Some (Token.Kwd ';') ->
|
||||
Stream.junk stream;
|
||||
main_loop stream
|
||||
|
||||
| Some token ->
|
||||
begin
|
||||
try match token with
|
||||
| Token.Def ->
|
||||
ignore(Parser.parse_definition stream);
|
||||
print_endline "parsed a function definition.";
|
||||
| Token.Extern ->
|
||||
ignore(Parser.parse_extern stream);
|
||||
print_endline "parsed an extern.";
|
||||
| _ ->
|
||||
(* Evaluate a top-level expression into an anonymous function. *)
|
||||
ignore(Parser.parse_toplevel stream);
|
||||
print_endline "parsed a top-level expr";
|
||||
with Stream.Error s ->
|
||||
(* Skip token for error recovery. *)
|
||||
Stream.junk stream;
|
||||
print_endline s;
|
||||
end;
|
||||
print_string "ready> "; flush stdout;
|
||||
main_loop stream
|
@ -1,21 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Main driver code.
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let main () =
|
||||
(* Install standard binary operators.
|
||||
* 1 is the lowest precedence. *)
|
||||
Hashtbl.add Parser.binop_precedence '<' 10;
|
||||
Hashtbl.add Parser.binop_precedence '+' 20;
|
||||
Hashtbl.add Parser.binop_precedence '-' 20;
|
||||
Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
|
||||
|
||||
(* Prime the first token. *)
|
||||
print_string "ready> "; flush stdout;
|
||||
let stream = Lexer.lex (Stream.of_channel stdin) in
|
||||
|
||||
(* Run the main "interpreter loop" now. *)
|
||||
Toplevel.main_loop stream;
|
||||
;;
|
||||
|
||||
main ()
|
@ -1,24 +0,0 @@
|
||||
##===- examples/OCaml-Kaleidoscope/Chapter3/Makefile -------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
#
|
||||
# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 3.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL := ../../..
|
||||
TOOLNAME := OCaml-Kaleidoscope-Ch3
|
||||
EXAMPLE_TOOL := 1
|
||||
UsedComponents := core
|
||||
UsedOcamLibs := llvm llvm_analysis
|
||||
|
||||
OCAMLCFLAGS += -pp camlp4of
|
||||
|
||||
ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
|
||||
|
||||
include $(LEVEL)/bindings/ocaml/Makefile.ocaml
|
@ -1,2 +0,0 @@
|
||||
<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
|
||||
<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
|
@ -1,25 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Abstract Syntax Tree (aka Parse Tree)
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* expr - Base type for all expression nodes. *)
|
||||
type expr =
|
||||
(* variant for numeric literals like "1.0". *)
|
||||
| Number of float
|
||||
|
||||
(* variant for referencing a variable, like "a". *)
|
||||
| Variable of string
|
||||
|
||||
(* variant for a binary operator. *)
|
||||
| Binary of char * expr * expr
|
||||
|
||||
(* variant for function calls. *)
|
||||
| Call of string * expr array
|
||||
|
||||
(* proto - This type represents the "prototype" for a function, which captures
|
||||
* its name, and its argument names (thus implicitly the number of arguments the
|
||||
* function takes). *)
|
||||
type proto = Prototype of string * string array
|
||||
|
||||
(* func - This type represents a function definition itself. *)
|
||||
type func = Function of proto * expr
|
@ -1,100 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Code Generation
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
exception Error of string
|
||||
|
||||
let context = global_context ()
|
||||
let the_module = create_module context "my cool jit"
|
||||
let builder = builder context
|
||||
let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
|
||||
let double_type = double_type context
|
||||
|
||||
let rec codegen_expr = function
|
||||
| Ast.Number n -> const_float double_type n
|
||||
| Ast.Variable name ->
|
||||
(try Hashtbl.find named_values name with
|
||||
| Not_found -> raise (Error "unknown variable name"))
|
||||
| Ast.Binary (op, lhs, rhs) ->
|
||||
let lhs_val = codegen_expr lhs in
|
||||
let rhs_val = codegen_expr rhs in
|
||||
begin
|
||||
match op with
|
||||
| '+' -> build_add lhs_val rhs_val "addtmp" builder
|
||||
| '-' -> build_sub lhs_val rhs_val "subtmp" builder
|
||||
| '*' -> build_mul lhs_val rhs_val "multmp" builder
|
||||
| '<' ->
|
||||
(* Convert bool 0/1 to double 0.0 or 1.0 *)
|
||||
let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
|
||||
build_uitofp i double_type "booltmp" builder
|
||||
| _ -> raise (Error "invalid binary operator")
|
||||
end
|
||||
| Ast.Call (callee, args) ->
|
||||
(* Look up the name in the module table. *)
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown function referenced")
|
||||
in
|
||||
let params = params callee in
|
||||
|
||||
(* If argument mismatch error. *)
|
||||
if Array.length params == Array.length args then () else
|
||||
raise (Error "incorrect # arguments passed");
|
||||
let args = Array.map codegen_expr args in
|
||||
build_call callee args "calltmp" builder
|
||||
|
||||
let codegen_proto = function
|
||||
| Ast.Prototype (name, args) ->
|
||||
(* Make the function type: double(double,double) etc. *)
|
||||
let doubles = Array.make (Array.length args) double_type in
|
||||
let ft = function_type double_type doubles in
|
||||
let f =
|
||||
match lookup_function name the_module with
|
||||
| None -> declare_function name ft the_module
|
||||
|
||||
(* If 'f' conflicted, there was already something named 'name'. If it
|
||||
* has a body, don't allow redefinition or reextern. *)
|
||||
| Some f ->
|
||||
(* If 'f' already has a body, reject this. *)
|
||||
if block_begin f <> At_end f then
|
||||
raise (Error "redefinition of function");
|
||||
|
||||
(* If 'f' took a different number of arguments, reject. *)
|
||||
if element_type (type_of f) <> ft then
|
||||
raise (Error "redefinition of function with different # args");
|
||||
f
|
||||
in
|
||||
|
||||
(* Set names for all arguments. *)
|
||||
Array.iteri (fun i a ->
|
||||
let n = args.(i) in
|
||||
set_value_name n a;
|
||||
Hashtbl.add named_values n a;
|
||||
) (params f);
|
||||
f
|
||||
|
||||
let codegen_func = function
|
||||
| Ast.Function (proto, body) ->
|
||||
Hashtbl.clear named_values;
|
||||
let the_function = codegen_proto proto in
|
||||
|
||||
(* Create a new basic block to start insertion into. *)
|
||||
let bb = append_block context "entry" the_function in
|
||||
position_at_end bb builder;
|
||||
|
||||
try
|
||||
let ret_val = codegen_expr body in
|
||||
|
||||
(* Finish off the function. *)
|
||||
let _ = build_ret ret_val builder in
|
||||
|
||||
(* Validate the generated code, checking for consistency. *)
|
||||
Llvm_analysis.assert_valid_function the_function;
|
||||
|
||||
the_function
|
||||
with e ->
|
||||
delete_function the_function;
|
||||
raise e
|
@ -1,52 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let rec lex = parser
|
||||
(* Skip any whitespace. *)
|
||||
| [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
|
||||
|
||||
(* identifier: [a-zA-Z][a-zA-Z0-9] *)
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
|
||||
(* number: [0-9.]+ *)
|
||||
| [< ' ('0' .. '9' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
|
||||
(* Comment until end of line. *)
|
||||
| [< ' ('#'); stream >] ->
|
||||
lex_comment stream
|
||||
|
||||
(* Otherwise, just return the character as its ascii value. *)
|
||||
| [< 'c; stream >] ->
|
||||
[< 'Token.Kwd c; lex stream >]
|
||||
|
||||
(* end of stream. *)
|
||||
| [< >] -> [< >]
|
||||
|
||||
and lex_number buffer = parser
|
||||
| [< ' ('0' .. '9' | '.' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
| [< stream=lex >] ->
|
||||
[< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
|
||||
|
||||
and lex_ident buffer = parser
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
| [< stream=lex >] ->
|
||||
match Buffer.contents buffer with
|
||||
| "def" -> [< 'Token.Def; stream >]
|
||||
| "extern" -> [< 'Token.Extern; stream >]
|
||||
| id -> [< 'Token.Ident id; stream >]
|
||||
|
||||
and lex_comment = parser
|
||||
| [< ' ('\n'); stream=lex >] -> stream
|
||||
| [< 'c; e=lex_comment >] -> e
|
||||
| [< >] -> [< >]
|
@ -1,6 +0,0 @@
|
||||
open Ocamlbuild_plugin;;
|
||||
|
||||
ocaml_lib ~extern:true "llvm";;
|
||||
ocaml_lib ~extern:true "llvm_analysis";;
|
||||
|
||||
flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
|
@ -1,122 +0,0 @@
|
||||
(*===---------------------------------------------------------------------===
|
||||
* Parser
|
||||
*===---------------------------------------------------------------------===*)
|
||||
|
||||
(* binop_precedence - This holds the precedence for each binary operator that is
|
||||
* defined *)
|
||||
let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
|
||||
|
||||
(* precedence - Get the precedence of the pending binary operator token. *)
|
||||
let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
|
||||
|
||||
(* primary
|
||||
* ::= identifier
|
||||
* ::= numberexpr
|
||||
* ::= parenexpr *)
|
||||
let rec parse_primary = parser
|
||||
(* numberexpr ::= number *)
|
||||
| [< 'Token.Number n >] -> Ast.Number n
|
||||
|
||||
(* parenexpr ::= '(' expression ')' *)
|
||||
| [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
|
||||
|
||||
(* identifierexpr
|
||||
* ::= identifier
|
||||
* ::= identifier '(' argumentexpr ')' *)
|
||||
| [< 'Token.Ident id; stream >] ->
|
||||
let rec parse_args accumulator = parser
|
||||
| [< e=parse_expr; stream >] ->
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
|
||||
| [< >] -> e :: accumulator
|
||||
end stream
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let rec parse_ident id = parser
|
||||
(* Call. *)
|
||||
| [< 'Token.Kwd '(';
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')'">] ->
|
||||
Ast.Call (id, Array.of_list (List.rev args))
|
||||
|
||||
(* Simple variable ref. *)
|
||||
| [< >] -> Ast.Variable id
|
||||
in
|
||||
parse_ident id stream
|
||||
|
||||
| [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
|
||||
|
||||
(* binoprhs
|
||||
* ::= ('+' primary)* *)
|
||||
and parse_bin_rhs expr_prec lhs stream =
|
||||
match Stream.peek stream with
|
||||
(* If this is a binop, find its precedence. *)
|
||||
| Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
|
||||
let token_prec = precedence c in
|
||||
|
||||
(* If this is a binop that binds at least as tightly as the current binop,
|
||||
* consume it, otherwise we are done. *)
|
||||
if token_prec < expr_prec then lhs else begin
|
||||
(* Eat the binop. *)
|
||||
Stream.junk stream;
|
||||
|
||||
(* Parse the primary expression after the binary operator. *)
|
||||
let rhs = parse_primary stream in
|
||||
|
||||
(* Okay, we know this is a binop. *)
|
||||
let rhs =
|
||||
match Stream.peek stream with
|
||||
| Some (Token.Kwd c2) ->
|
||||
(* If BinOp binds less tightly with rhs than the operator after
|
||||
* rhs, let the pending operator take rhs as its lhs. *)
|
||||
let next_prec = precedence c2 in
|
||||
if token_prec < next_prec
|
||||
then parse_bin_rhs (token_prec + 1) rhs stream
|
||||
else rhs
|
||||
| _ -> rhs
|
||||
in
|
||||
|
||||
(* Merge lhs/rhs. *)
|
||||
let lhs = Ast.Binary (c, lhs, rhs) in
|
||||
parse_bin_rhs expr_prec lhs stream
|
||||
end
|
||||
| _ -> lhs
|
||||
|
||||
(* expression
|
||||
* ::= primary binoprhs *)
|
||||
and parse_expr = parser
|
||||
| [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
|
||||
|
||||
(* prototype
|
||||
* ::= id '(' id* ')' *)
|
||||
let parse_prototype =
|
||||
let rec parse_args accumulator = parser
|
||||
| [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
|
||||
parser
|
||||
| [< 'Token.Ident id;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
(* success. *)
|
||||
Ast.Prototype (id, Array.of_list (List.rev args))
|
||||
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected function name in prototype")
|
||||
|
||||
(* definition ::= 'def' prototype expression *)
|
||||
let parse_definition = parser
|
||||
| [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
|
||||
Ast.Function (p, e)
|
||||
|
||||
(* toplevelexpr ::= expression *)
|
||||
let parse_toplevel = parser
|
||||
| [< e=parse_expr >] ->
|
||||
(* Make an anonymous proto. *)
|
||||
Ast.Function (Ast.Prototype ("", [||]), e)
|
||||
|
||||
(* external ::= 'extern' prototype *)
|
||||
let parse_extern = parser
|
||||
| [< 'Token.Extern; e=parse_prototype >] -> e
|
@ -1,15 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer Tokens
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
|
||||
* these others for known things. *)
|
||||
type token =
|
||||
(* commands *)
|
||||
| Def | Extern
|
||||
|
||||
(* primary *)
|
||||
| Ident of string | Number of float
|
||||
|
||||
(* unknown *)
|
||||
| Kwd of char
|
@ -1,39 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Top-Level parsing and JIT Driver
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
(* top ::= definition | external | expression | ';' *)
|
||||
let rec main_loop stream =
|
||||
match Stream.peek stream with
|
||||
| None -> ()
|
||||
|
||||
(* ignore top-level semicolons. *)
|
||||
| Some (Token.Kwd ';') ->
|
||||
Stream.junk stream;
|
||||
main_loop stream
|
||||
|
||||
| Some token ->
|
||||
begin
|
||||
try match token with
|
||||
| Token.Def ->
|
||||
let e = Parser.parse_definition stream in
|
||||
print_endline "parsed a function definition.";
|
||||
dump_value (Codegen.codegen_func e);
|
||||
| Token.Extern ->
|
||||
let e = Parser.parse_extern stream in
|
||||
print_endline "parsed an extern.";
|
||||
dump_value (Codegen.codegen_proto e);
|
||||
| _ ->
|
||||
(* Evaluate a top-level expression into an anonymous function. *)
|
||||
let e = Parser.parse_toplevel stream in
|
||||
print_endline "parsed a top-level expr";
|
||||
dump_value (Codegen.codegen_func e);
|
||||
with Stream.Error s | Codegen.Error s ->
|
||||
(* Skip token for error recovery. *)
|
||||
Stream.junk stream;
|
||||
print_endline s;
|
||||
end;
|
||||
print_string "ready> "; flush stdout;
|
||||
main_loop stream
|
@ -1,26 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Main driver code.
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
let main () =
|
||||
(* Install standard binary operators.
|
||||
* 1 is the lowest precedence. *)
|
||||
Hashtbl.add Parser.binop_precedence '<' 10;
|
||||
Hashtbl.add Parser.binop_precedence '+' 20;
|
||||
Hashtbl.add Parser.binop_precedence '-' 20;
|
||||
Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
|
||||
|
||||
(* Prime the first token. *)
|
||||
print_string "ready> "; flush stdout;
|
||||
let stream = Lexer.lex (Stream.of_channel stdin) in
|
||||
|
||||
(* Run the main "interpreter loop" now. *)
|
||||
Toplevel.main_loop stream;
|
||||
|
||||
(* Print out all the generated code. *)
|
||||
dump_module Codegen.the_module
|
||||
;;
|
||||
|
||||
main ()
|
@ -1,25 +0,0 @@
|
||||
##===- examples/OCaml-Kaleidoscope/Chapter4/Makefile -------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
#
|
||||
# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 4.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL := ../../..
|
||||
TOOLNAME := OCaml-Kaleidoscope-Ch4
|
||||
EXAMPLE_TOOL := 1
|
||||
UsedComponents := core
|
||||
UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
|
||||
llvm_scalar_opts
|
||||
|
||||
OCAMLCFLAGS += -pp camlp4of
|
||||
|
||||
ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
|
||||
|
||||
include $(LEVEL)/bindings/ocaml/Makefile.ocaml
|
@ -1,4 +0,0 @@
|
||||
<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
|
||||
<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
|
||||
<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
|
||||
<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
|
@ -1,25 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Abstract Syntax Tree (aka Parse Tree)
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* expr - Base type for all expression nodes. *)
|
||||
type expr =
|
||||
(* variant for numeric literals like "1.0". *)
|
||||
| Number of float
|
||||
|
||||
(* variant for referencing a variable, like "a". *)
|
||||
| Variable of string
|
||||
|
||||
(* variant for a binary operator. *)
|
||||
| Binary of char * expr * expr
|
||||
|
||||
(* variant for function calls. *)
|
||||
| Call of string * expr array
|
||||
|
||||
(* proto - This type represents the "prototype" for a function, which captures
|
||||
* its name, and its argument names (thus implicitly the number of arguments the
|
||||
* function takes). *)
|
||||
type proto = Prototype of string * string array
|
||||
|
||||
(* func - This type represents a function definition itself. *)
|
||||
type func = Function of proto * expr
|
@ -1,7 +0,0 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* putchard - putchar that takes a double and returns 0. */
|
||||
extern double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
@ -1,103 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Code Generation
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
exception Error of string
|
||||
|
||||
let context = global_context ()
|
||||
let the_module = create_module context "my cool jit"
|
||||
let builder = builder context
|
||||
let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
|
||||
let double_type = double_type context
|
||||
|
||||
let rec codegen_expr = function
|
||||
| Ast.Number n -> const_float double_type n
|
||||
| Ast.Variable name ->
|
||||
(try Hashtbl.find named_values name with
|
||||
| Not_found -> raise (Error "unknown variable name"))
|
||||
| Ast.Binary (op, lhs, rhs) ->
|
||||
let lhs_val = codegen_expr lhs in
|
||||
let rhs_val = codegen_expr rhs in
|
||||
begin
|
||||
match op with
|
||||
| '+' -> build_add lhs_val rhs_val "addtmp" builder
|
||||
| '-' -> build_sub lhs_val rhs_val "subtmp" builder
|
||||
| '*' -> build_mul lhs_val rhs_val "multmp" builder
|
||||
| '<' ->
|
||||
(* Convert bool 0/1 to double 0.0 or 1.0 *)
|
||||
let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
|
||||
build_uitofp i double_type "booltmp" builder
|
||||
| _ -> raise (Error "invalid binary operator")
|
||||
end
|
||||
| Ast.Call (callee, args) ->
|
||||
(* Look up the name in the module table. *)
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown function referenced")
|
||||
in
|
||||
let params = params callee in
|
||||
|
||||
(* If argument mismatch error. *)
|
||||
if Array.length params == Array.length args then () else
|
||||
raise (Error "incorrect # arguments passed");
|
||||
let args = Array.map codegen_expr args in
|
||||
build_call callee args "calltmp" builder
|
||||
|
||||
let codegen_proto = function
|
||||
| Ast.Prototype (name, args) ->
|
||||
(* Make the function type: double(double,double) etc. *)
|
||||
let doubles = Array.make (Array.length args) double_type in
|
||||
let ft = function_type double_type doubles in
|
||||
let f =
|
||||
match lookup_function name the_module with
|
||||
| None -> declare_function name ft the_module
|
||||
|
||||
(* If 'f' conflicted, there was already something named 'name'. If it
|
||||
* has a body, don't allow redefinition or reextern. *)
|
||||
| Some f ->
|
||||
(* If 'f' already has a body, reject this. *)
|
||||
if block_begin f <> At_end f then
|
||||
raise (Error "redefinition of function");
|
||||
|
||||
(* If 'f' took a different number of arguments, reject. *)
|
||||
if element_type (type_of f) <> ft then
|
||||
raise (Error "redefinition of function with different # args");
|
||||
f
|
||||
in
|
||||
|
||||
(* Set names for all arguments. *)
|
||||
Array.iteri (fun i a ->
|
||||
let n = args.(i) in
|
||||
set_value_name n a;
|
||||
Hashtbl.add named_values n a;
|
||||
) (params f);
|
||||
f
|
||||
|
||||
let codegen_func the_fpm = function
|
||||
| Ast.Function (proto, body) ->
|
||||
Hashtbl.clear named_values;
|
||||
let the_function = codegen_proto proto in
|
||||
|
||||
(* Create a new basic block to start insertion into. *)
|
||||
let bb = append_block context "entry" the_function in
|
||||
position_at_end bb builder;
|
||||
|
||||
try
|
||||
let ret_val = codegen_expr body in
|
||||
|
||||
(* Finish off the function. *)
|
||||
let _ = build_ret ret_val builder in
|
||||
|
||||
(* Validate the generated code, checking for consistency. *)
|
||||
Llvm_analysis.assert_valid_function the_function;
|
||||
|
||||
(* Optimize the function. *)
|
||||
let _ = PassManager.run_function the_function the_fpm in
|
||||
|
||||
the_function
|
||||
with e ->
|
||||
delete_function the_function;
|
||||
raise e
|
@ -1,52 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let rec lex = parser
|
||||
(* Skip any whitespace. *)
|
||||
| [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
|
||||
|
||||
(* identifier: [a-zA-Z][a-zA-Z0-9] *)
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
|
||||
(* number: [0-9.]+ *)
|
||||
| [< ' ('0' .. '9' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
|
||||
(* Comment until end of line. *)
|
||||
| [< ' ('#'); stream >] ->
|
||||
lex_comment stream
|
||||
|
||||
(* Otherwise, just return the character as its ascii value. *)
|
||||
| [< 'c; stream >] ->
|
||||
[< 'Token.Kwd c; lex stream >]
|
||||
|
||||
(* end of stream. *)
|
||||
| [< >] -> [< >]
|
||||
|
||||
and lex_number buffer = parser
|
||||
| [< ' ('0' .. '9' | '.' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
| [< stream=lex >] ->
|
||||
[< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
|
||||
|
||||
and lex_ident buffer = parser
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
| [< stream=lex >] ->
|
||||
match Buffer.contents buffer with
|
||||
| "def" -> [< 'Token.Def; stream >]
|
||||
| "extern" -> [< 'Token.Extern; stream >]
|
||||
| id -> [< 'Token.Ident id; stream >]
|
||||
|
||||
and lex_comment = parser
|
||||
| [< ' ('\n'); stream=lex >] -> stream
|
||||
| [< 'c; e=lex_comment >] -> e
|
||||
| [< >] -> [< >]
|
@ -1,10 +0,0 @@
|
||||
open Ocamlbuild_plugin;;
|
||||
|
||||
ocaml_lib ~extern:true "llvm";;
|
||||
ocaml_lib ~extern:true "llvm_analysis";;
|
||||
ocaml_lib ~extern:true "llvm_executionengine";;
|
||||
ocaml_lib ~extern:true "llvm_target";;
|
||||
ocaml_lib ~extern:true "llvm_scalar_opts";;
|
||||
|
||||
flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
|
||||
dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
|
@ -1,122 +0,0 @@
|
||||
(*===---------------------------------------------------------------------===
|
||||
* Parser
|
||||
*===---------------------------------------------------------------------===*)
|
||||
|
||||
(* binop_precedence - This holds the precedence for each binary operator that is
|
||||
* defined *)
|
||||
let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
|
||||
|
||||
(* precedence - Get the precedence of the pending binary operator token. *)
|
||||
let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
|
||||
|
||||
(* primary
|
||||
* ::= identifier
|
||||
* ::= numberexpr
|
||||
* ::= parenexpr *)
|
||||
let rec parse_primary = parser
|
||||
(* numberexpr ::= number *)
|
||||
| [< 'Token.Number n >] -> Ast.Number n
|
||||
|
||||
(* parenexpr ::= '(' expression ')' *)
|
||||
| [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
|
||||
|
||||
(* identifierexpr
|
||||
* ::= identifier
|
||||
* ::= identifier '(' argumentexpr ')' *)
|
||||
| [< 'Token.Ident id; stream >] ->
|
||||
let rec parse_args accumulator = parser
|
||||
| [< e=parse_expr; stream >] ->
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
|
||||
| [< >] -> e :: accumulator
|
||||
end stream
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let rec parse_ident id = parser
|
||||
(* Call. *)
|
||||
| [< 'Token.Kwd '(';
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')'">] ->
|
||||
Ast.Call (id, Array.of_list (List.rev args))
|
||||
|
||||
(* Simple variable ref. *)
|
||||
| [< >] -> Ast.Variable id
|
||||
in
|
||||
parse_ident id stream
|
||||
|
||||
| [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
|
||||
|
||||
(* binoprhs
|
||||
* ::= ('+' primary)* *)
|
||||
and parse_bin_rhs expr_prec lhs stream =
|
||||
match Stream.peek stream with
|
||||
(* If this is a binop, find its precedence. *)
|
||||
| Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
|
||||
let token_prec = precedence c in
|
||||
|
||||
(* If this is a binop that binds at least as tightly as the current binop,
|
||||
* consume it, otherwise we are done. *)
|
||||
if token_prec < expr_prec then lhs else begin
|
||||
(* Eat the binop. *)
|
||||
Stream.junk stream;
|
||||
|
||||
(* Parse the primary expression after the binary operator. *)
|
||||
let rhs = parse_primary stream in
|
||||
|
||||
(* Okay, we know this is a binop. *)
|
||||
let rhs =
|
||||
match Stream.peek stream with
|
||||
| Some (Token.Kwd c2) ->
|
||||
(* If BinOp binds less tightly with rhs than the operator after
|
||||
* rhs, let the pending operator take rhs as its lhs. *)
|
||||
let next_prec = precedence c2 in
|
||||
if token_prec < next_prec
|
||||
then parse_bin_rhs (token_prec + 1) rhs stream
|
||||
else rhs
|
||||
| _ -> rhs
|
||||
in
|
||||
|
||||
(* Merge lhs/rhs. *)
|
||||
let lhs = Ast.Binary (c, lhs, rhs) in
|
||||
parse_bin_rhs expr_prec lhs stream
|
||||
end
|
||||
| _ -> lhs
|
||||
|
||||
(* expression
|
||||
* ::= primary binoprhs *)
|
||||
and parse_expr = parser
|
||||
| [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
|
||||
|
||||
(* prototype
|
||||
* ::= id '(' id* ')' *)
|
||||
let parse_prototype =
|
||||
let rec parse_args accumulator = parser
|
||||
| [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
|
||||
parser
|
||||
| [< 'Token.Ident id;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
(* success. *)
|
||||
Ast.Prototype (id, Array.of_list (List.rev args))
|
||||
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected function name in prototype")
|
||||
|
||||
(* definition ::= 'def' prototype expression *)
|
||||
let parse_definition = parser
|
||||
| [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
|
||||
Ast.Function (p, e)
|
||||
|
||||
(* toplevelexpr ::= expression *)
|
||||
let parse_toplevel = parser
|
||||
| [< e=parse_expr >] ->
|
||||
(* Make an anonymous proto. *)
|
||||
Ast.Function (Ast.Prototype ("", [||]), e)
|
||||
|
||||
(* external ::= 'extern' prototype *)
|
||||
let parse_extern = parser
|
||||
| [< 'Token.Extern; e=parse_prototype >] -> e
|
@ -1,15 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer Tokens
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
|
||||
* these others for known things. *)
|
||||
type token =
|
||||
(* commands *)
|
||||
| Def | Extern
|
||||
|
||||
(* primary *)
|
||||
| Ident of string | Number of float
|
||||
|
||||
(* unknown *)
|
||||
| Kwd of char
|
@ -1,49 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Top-Level parsing and JIT Driver
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
open Llvm_executionengine
|
||||
|
||||
(* top ::= definition | external | expression | ';' *)
|
||||
let rec main_loop the_fpm the_execution_engine stream =
|
||||
match Stream.peek stream with
|
||||
| None -> ()
|
||||
|
||||
(* ignore top-level semicolons. *)
|
||||
| Some (Token.Kwd ';') ->
|
||||
Stream.junk stream;
|
||||
main_loop the_fpm the_execution_engine stream
|
||||
|
||||
| Some token ->
|
||||
begin
|
||||
try match token with
|
||||
| Token.Def ->
|
||||
let e = Parser.parse_definition stream in
|
||||
print_endline "parsed a function definition.";
|
||||
dump_value (Codegen.codegen_func the_fpm e);
|
||||
| Token.Extern ->
|
||||
let e = Parser.parse_extern stream in
|
||||
print_endline "parsed an extern.";
|
||||
dump_value (Codegen.codegen_proto e);
|
||||
| _ ->
|
||||
(* Evaluate a top-level expression into an anonymous function. *)
|
||||
let e = Parser.parse_toplevel stream in
|
||||
print_endline "parsed a top-level expr";
|
||||
let the_function = Codegen.codegen_func the_fpm e in
|
||||
dump_value the_function;
|
||||
|
||||
(* JIT the function, returning a function pointer. *)
|
||||
let result = ExecutionEngine.run_function the_function [||]
|
||||
the_execution_engine in
|
||||
|
||||
print_string "Evaluated to ";
|
||||
print_float (GenericValue.as_float Codegen.double_type result);
|
||||
print_newline ();
|
||||
with Stream.Error s | Codegen.Error s ->
|
||||
(* Skip token for error recovery. *)
|
||||
Stream.junk stream;
|
||||
print_endline s;
|
||||
end;
|
||||
print_string "ready> "; flush stdout;
|
||||
main_loop the_fpm the_execution_engine stream
|
@ -1,53 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Main driver code.
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
open Llvm_executionengine
|
||||
open Llvm_target
|
||||
open Llvm_scalar_opts
|
||||
|
||||
let main () =
|
||||
ignore (initialize_native_target ());
|
||||
|
||||
(* Install standard binary operators.
|
||||
* 1 is the lowest precedence. *)
|
||||
Hashtbl.add Parser.binop_precedence '<' 10;
|
||||
Hashtbl.add Parser.binop_precedence '+' 20;
|
||||
Hashtbl.add Parser.binop_precedence '-' 20;
|
||||
Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
|
||||
|
||||
(* Prime the first token. *)
|
||||
print_string "ready> "; flush stdout;
|
||||
let stream = Lexer.lex (Stream.of_channel stdin) in
|
||||
|
||||
(* Create the JIT. *)
|
||||
let the_execution_engine = ExecutionEngine.create Codegen.the_module in
|
||||
let the_fpm = PassManager.create_function Codegen.the_module in
|
||||
|
||||
(* Set up the optimizer pipeline. Start with registering info about how the
|
||||
* target lays out data structures. *)
|
||||
TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
|
||||
|
||||
(* Do simple "peephole" optimizations and bit-twiddling optzn. *)
|
||||
add_instruction_combination the_fpm;
|
||||
|
||||
(* reassociate expressions. *)
|
||||
add_reassociation the_fpm;
|
||||
|
||||
(* Eliminate Common SubExpressions. *)
|
||||
add_gvn the_fpm;
|
||||
|
||||
(* Simplify the control flow graph (deleting unreachable blocks, etc). *)
|
||||
add_cfg_simplification the_fpm;
|
||||
|
||||
ignore (PassManager.initialize the_fpm);
|
||||
|
||||
(* Run the main "interpreter loop" now. *)
|
||||
Toplevel.main_loop the_fpm the_execution_engine stream;
|
||||
|
||||
(* Print out all the generated code. *)
|
||||
dump_module Codegen.the_module
|
||||
;;
|
||||
|
||||
main ()
|
@ -1,25 +0,0 @@
|
||||
##===- examples/OCaml-Kaleidoscope/Chapter5/Makefile -------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
#
|
||||
# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 5.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL := ../../..
|
||||
TOOLNAME := OCaml-Kaleidoscope-Ch5
|
||||
EXAMPLE_TOOL := 1
|
||||
UsedComponents := core
|
||||
UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
|
||||
llvm_scalar_opts
|
||||
|
||||
OCAMLCFLAGS += -pp camlp4of
|
||||
|
||||
ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
|
||||
|
||||
include $(LEVEL)/bindings/ocaml/Makefile.ocaml
|
@ -1,4 +0,0 @@
|
||||
<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
|
||||
<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
|
||||
<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
|
||||
<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
|
@ -1,31 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Abstract Syntax Tree (aka Parse Tree)
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* expr - Base type for all expression nodes. *)
|
||||
type expr =
|
||||
(* variant for numeric literals like "1.0". *)
|
||||
| Number of float
|
||||
|
||||
(* variant for referencing a variable, like "a". *)
|
||||
| Variable of string
|
||||
|
||||
(* variant for a binary operator. *)
|
||||
| Binary of char * expr * expr
|
||||
|
||||
(* variant for function calls. *)
|
||||
| Call of string * expr array
|
||||
|
||||
(* variant for if/then/else. *)
|
||||
| If of expr * expr * expr
|
||||
|
||||
(* variant for for/in. *)
|
||||
| For of string * expr * expr * expr option * expr
|
||||
|
||||
(* proto - This type represents the "prototype" for a function, which captures
|
||||
* its name, and its argument names (thus implicitly the number of arguments the
|
||||
* function takes). *)
|
||||
type proto = Prototype of string * string array
|
||||
|
||||
(* func - This type represents a function definition itself. *)
|
||||
type func = Function of proto * expr
|
@ -1,7 +0,0 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* putchard - putchar that takes a double and returns 0. */
|
||||
extern double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
@ -1,225 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Code Generation
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
exception Error of string
|
||||
|
||||
let context = global_context ()
|
||||
let the_module = create_module context "my cool jit"
|
||||
let builder = builder context
|
||||
let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
|
||||
let double_type = double_type context
|
||||
|
||||
let rec codegen_expr = function
|
||||
| Ast.Number n -> const_float double_type n
|
||||
| Ast.Variable name ->
|
||||
(try Hashtbl.find named_values name with
|
||||
| Not_found -> raise (Error "unknown variable name"))
|
||||
| Ast.Binary (op, lhs, rhs) ->
|
||||
let lhs_val = codegen_expr lhs in
|
||||
let rhs_val = codegen_expr rhs in
|
||||
begin
|
||||
match op with
|
||||
| '+' -> build_add lhs_val rhs_val "addtmp" builder
|
||||
| '-' -> build_sub lhs_val rhs_val "subtmp" builder
|
||||
| '*' -> build_mul lhs_val rhs_val "multmp" builder
|
||||
| '<' ->
|
||||
(* Convert bool 0/1 to double 0.0 or 1.0 *)
|
||||
let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
|
||||
build_uitofp i double_type "booltmp" builder
|
||||
| _ -> raise (Error "invalid binary operator")
|
||||
end
|
||||
| Ast.Call (callee, args) ->
|
||||
(* Look up the name in the module table. *)
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown function referenced")
|
||||
in
|
||||
let params = params callee in
|
||||
|
||||
(* If argument mismatch error. *)
|
||||
if Array.length params == Array.length args then () else
|
||||
raise (Error "incorrect # arguments passed");
|
||||
let args = Array.map codegen_expr args in
|
||||
build_call callee args "calltmp" builder
|
||||
| Ast.If (cond, then_, else_) ->
|
||||
let cond = codegen_expr cond in
|
||||
|
||||
(* Convert condition to a bool by comparing equal to 0.0 *)
|
||||
let zero = const_float double_type 0.0 in
|
||||
let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
|
||||
|
||||
(* Grab the first block so that we might later add the conditional branch
|
||||
* to it at the end of the function. *)
|
||||
let start_bb = insertion_block builder in
|
||||
let the_function = block_parent start_bb in
|
||||
|
||||
let then_bb = append_block context "then" the_function in
|
||||
|
||||
(* Emit 'then' value. *)
|
||||
position_at_end then_bb builder;
|
||||
let then_val = codegen_expr then_ in
|
||||
|
||||
(* Codegen of 'then' can change the current block, update then_bb for the
|
||||
* phi. We create a new name because one is used for the phi node, and the
|
||||
* other is used for the conditional branch. *)
|
||||
let new_then_bb = insertion_block builder in
|
||||
|
||||
(* Emit 'else' value. *)
|
||||
let else_bb = append_block context "else" the_function in
|
||||
position_at_end else_bb builder;
|
||||
let else_val = codegen_expr else_ in
|
||||
|
||||
(* Codegen of 'else' can change the current block, update else_bb for the
|
||||
* phi. *)
|
||||
let new_else_bb = insertion_block builder in
|
||||
|
||||
(* Emit merge block. *)
|
||||
let merge_bb = append_block context "ifcont" the_function in
|
||||
position_at_end merge_bb builder;
|
||||
let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
|
||||
let phi = build_phi incoming "iftmp" builder in
|
||||
|
||||
(* Return to the start block to add the conditional branch. *)
|
||||
position_at_end start_bb builder;
|
||||
ignore (build_cond_br cond_val then_bb else_bb builder);
|
||||
|
||||
(* Set a unconditional branch at the end of the 'then' block and the
|
||||
* 'else' block to the 'merge' block. *)
|
||||
position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
|
||||
position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
|
||||
|
||||
(* Finally, set the builder to the end of the merge block. *)
|
||||
position_at_end merge_bb builder;
|
||||
|
||||
phi
|
||||
| Ast.For (var_name, start, end_, step, body) ->
|
||||
(* Emit the start code first, without 'variable' in scope. *)
|
||||
let start_val = codegen_expr start in
|
||||
|
||||
(* Make the new basic block for the loop header, inserting after current
|
||||
* block. *)
|
||||
let preheader_bb = insertion_block builder in
|
||||
let the_function = block_parent preheader_bb in
|
||||
let loop_bb = append_block context "loop" the_function in
|
||||
|
||||
(* Insert an explicit fall through from the current block to the
|
||||
* loop_bb. *)
|
||||
ignore (build_br loop_bb builder);
|
||||
|
||||
(* Start insertion in loop_bb. *)
|
||||
position_at_end loop_bb builder;
|
||||
|
||||
(* Start the PHI node with an entry for start. *)
|
||||
let variable = build_phi [(start_val, preheader_bb)] var_name builder in
|
||||
|
||||
(* Within the loop, the variable is defined equal to the PHI node. If it
|
||||
* shadows an existing variable, we have to restore it, so save it
|
||||
* now. *)
|
||||
let old_val =
|
||||
try Some (Hashtbl.find named_values var_name) with Not_found -> None
|
||||
in
|
||||
Hashtbl.add named_values var_name variable;
|
||||
|
||||
(* Emit the body of the loop. This, like any other expr, can change the
|
||||
* current BB. Note that we ignore the value computed by the body, but
|
||||
* don't allow an error *)
|
||||
ignore (codegen_expr body);
|
||||
|
||||
(* Emit the step value. *)
|
||||
let step_val =
|
||||
match step with
|
||||
| Some step -> codegen_expr step
|
||||
(* If not specified, use 1.0. *)
|
||||
| None -> const_float double_type 1.0
|
||||
in
|
||||
|
||||
let next_var = build_add variable step_val "nextvar" builder in
|
||||
|
||||
(* Compute the end condition. *)
|
||||
let end_cond = codegen_expr end_ in
|
||||
|
||||
(* Convert condition to a bool by comparing equal to 0.0. *)
|
||||
let zero = const_float double_type 0.0 in
|
||||
let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
|
||||
|
||||
(* Create the "after loop" block and insert it. *)
|
||||
let loop_end_bb = insertion_block builder in
|
||||
let after_bb = append_block context "afterloop" the_function in
|
||||
|
||||
(* Insert the conditional branch into the end of loop_end_bb. *)
|
||||
ignore (build_cond_br end_cond loop_bb after_bb builder);
|
||||
|
||||
(* Any new code will be inserted in after_bb. *)
|
||||
position_at_end after_bb builder;
|
||||
|
||||
(* Add a new entry to the PHI node for the backedge. *)
|
||||
add_incoming (next_var, loop_end_bb) variable;
|
||||
|
||||
(* Restore the unshadowed variable. *)
|
||||
begin match old_val with
|
||||
| Some old_val -> Hashtbl.add named_values var_name old_val
|
||||
| None -> ()
|
||||
end;
|
||||
|
||||
(* for expr always returns 0.0. *)
|
||||
const_null double_type
|
||||
|
||||
let codegen_proto = function
|
||||
| Ast.Prototype (name, args) ->
|
||||
(* Make the function type: double(double,double) etc. *)
|
||||
let doubles = Array.make (Array.length args) double_type in
|
||||
let ft = function_type double_type doubles in
|
||||
let f =
|
||||
match lookup_function name the_module with
|
||||
| None -> declare_function name ft the_module
|
||||
|
||||
(* If 'f' conflicted, there was already something named 'name'. If it
|
||||
* has a body, don't allow redefinition or reextern. *)
|
||||
| Some f ->
|
||||
(* If 'f' already has a body, reject this. *)
|
||||
if block_begin f <> At_end f then
|
||||
raise (Error "redefinition of function");
|
||||
|
||||
(* If 'f' took a different number of arguments, reject. *)
|
||||
if element_type (type_of f) <> ft then
|
||||
raise (Error "redefinition of function with different # args");
|
||||
f
|
||||
in
|
||||
|
||||
(* Set names for all arguments. *)
|
||||
Array.iteri (fun i a ->
|
||||
let n = args.(i) in
|
||||
set_value_name n a;
|
||||
Hashtbl.add named_values n a;
|
||||
) (params f);
|
||||
f
|
||||
|
||||
let codegen_func the_fpm = function
|
||||
| Ast.Function (proto, body) ->
|
||||
Hashtbl.clear named_values;
|
||||
let the_function = codegen_proto proto in
|
||||
|
||||
(* Create a new basic block to start insertion into. *)
|
||||
let bb = append_block context "entry" the_function in
|
||||
position_at_end bb builder;
|
||||
|
||||
try
|
||||
let ret_val = codegen_expr body in
|
||||
|
||||
(* Finish off the function. *)
|
||||
let _ = build_ret ret_val builder in
|
||||
|
||||
(* Validate the generated code, checking for consistency. *)
|
||||
Llvm_analysis.assert_valid_function the_function;
|
||||
|
||||
(* Optimize the function. *)
|
||||
let _ = PassManager.run_function the_function the_fpm in
|
||||
|
||||
the_function
|
||||
with e ->
|
||||
delete_function the_function;
|
||||
raise e
|
@ -1,57 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let rec lex = parser
|
||||
(* Skip any whitespace. *)
|
||||
| [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
|
||||
|
||||
(* identifier: [a-zA-Z][a-zA-Z0-9] *)
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
|
||||
(* number: [0-9.]+ *)
|
||||
| [< ' ('0' .. '9' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
|
||||
(* Comment until end of line. *)
|
||||
| [< ' ('#'); stream >] ->
|
||||
lex_comment stream
|
||||
|
||||
(* Otherwise, just return the character as its ascii value. *)
|
||||
| [< 'c; stream >] ->
|
||||
[< 'Token.Kwd c; lex stream >]
|
||||
|
||||
(* end of stream. *)
|
||||
| [< >] -> [< >]
|
||||
|
||||
and lex_number buffer = parser
|
||||
| [< ' ('0' .. '9' | '.' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
| [< stream=lex >] ->
|
||||
[< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
|
||||
|
||||
and lex_ident buffer = parser
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
| [< stream=lex >] ->
|
||||
match Buffer.contents buffer with
|
||||
| "def" -> [< 'Token.Def; stream >]
|
||||
| "extern" -> [< 'Token.Extern; stream >]
|
||||
| "if" -> [< 'Token.If; stream >]
|
||||
| "then" -> [< 'Token.Then; stream >]
|
||||
| "else" -> [< 'Token.Else; stream >]
|
||||
| "for" -> [< 'Token.For; stream >]
|
||||
| "in" -> [< 'Token.In; stream >]
|
||||
| id -> [< 'Token.Ident id; stream >]
|
||||
|
||||
and lex_comment = parser
|
||||
| [< ' ('\n'); stream=lex >] -> stream
|
||||
| [< 'c; e=lex_comment >] -> e
|
||||
| [< >] -> [< >]
|
@ -1,10 +0,0 @@
|
||||
open Ocamlbuild_plugin;;
|
||||
|
||||
ocaml_lib ~extern:true "llvm";;
|
||||
ocaml_lib ~extern:true "llvm_analysis";;
|
||||
ocaml_lib ~extern:true "llvm_executionengine";;
|
||||
ocaml_lib ~extern:true "llvm_target";;
|
||||
ocaml_lib ~extern:true "llvm_scalar_opts";;
|
||||
|
||||
flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"]);;
|
||||
dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
|
@ -1,158 +0,0 @@
|
||||
(*===---------------------------------------------------------------------===
|
||||
* Parser
|
||||
*===---------------------------------------------------------------------===*)
|
||||
|
||||
(* binop_precedence - This holds the precedence for each binary operator that is
|
||||
* defined *)
|
||||
let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
|
||||
|
||||
(* precedence - Get the precedence of the pending binary operator token. *)
|
||||
let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
|
||||
|
||||
(* primary
|
||||
* ::= identifier
|
||||
* ::= numberexpr
|
||||
* ::= parenexpr
|
||||
* ::= ifexpr
|
||||
* ::= forexpr *)
|
||||
let rec parse_primary = parser
|
||||
(* numberexpr ::= number *)
|
||||
| [< 'Token.Number n >] -> Ast.Number n
|
||||
|
||||
(* parenexpr ::= '(' expression ')' *)
|
||||
| [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
|
||||
|
||||
(* identifierexpr
|
||||
* ::= identifier
|
||||
* ::= identifier '(' argumentexpr ')' *)
|
||||
| [< 'Token.Ident id; stream >] ->
|
||||
let rec parse_args accumulator = parser
|
||||
| [< e=parse_expr; stream >] ->
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
|
||||
| [< >] -> e :: accumulator
|
||||
end stream
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let rec parse_ident id = parser
|
||||
(* Call. *)
|
||||
| [< 'Token.Kwd '(';
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')'">] ->
|
||||
Ast.Call (id, Array.of_list (List.rev args))
|
||||
|
||||
(* Simple variable ref. *)
|
||||
| [< >] -> Ast.Variable id
|
||||
in
|
||||
parse_ident id stream
|
||||
|
||||
(* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
|
||||
| [< 'Token.If; c=parse_expr;
|
||||
'Token.Then ?? "expected 'then'"; t=parse_expr;
|
||||
'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
|
||||
Ast.If (c, t, e)
|
||||
|
||||
(* forexpr
|
||||
::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
|
||||
| [< 'Token.For;
|
||||
'Token.Ident id ?? "expected identifier after for";
|
||||
'Token.Kwd '=' ?? "expected '=' after for";
|
||||
stream >] ->
|
||||
begin parser
|
||||
| [<
|
||||
start=parse_expr;
|
||||
'Token.Kwd ',' ?? "expected ',' after for";
|
||||
end_=parse_expr;
|
||||
stream >] ->
|
||||
let step =
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; step=parse_expr >] -> Some step
|
||||
| [< >] -> None
|
||||
end stream
|
||||
in
|
||||
begin parser
|
||||
| [< 'Token.In; body=parse_expr >] ->
|
||||
Ast.For (id, start, end_, step, body)
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected 'in' after for")
|
||||
end stream
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected '=' after for")
|
||||
end stream
|
||||
|
||||
| [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
|
||||
|
||||
(* binoprhs
|
||||
* ::= ('+' primary)* *)
|
||||
and parse_bin_rhs expr_prec lhs stream =
|
||||
match Stream.peek stream with
|
||||
(* If this is a binop, find its precedence. *)
|
||||
| Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
|
||||
let token_prec = precedence c in
|
||||
|
||||
(* If this is a binop that binds at least as tightly as the current binop,
|
||||
* consume it, otherwise we are done. *)
|
||||
if token_prec < expr_prec then lhs else begin
|
||||
(* Eat the binop. *)
|
||||
Stream.junk stream;
|
||||
|
||||
(* Parse the primary expression after the binary operator. *)
|
||||
let rhs = parse_primary stream in
|
||||
|
||||
(* Okay, we know this is a binop. *)
|
||||
let rhs =
|
||||
match Stream.peek stream with
|
||||
| Some (Token.Kwd c2) ->
|
||||
(* If BinOp binds less tightly with rhs than the operator after
|
||||
* rhs, let the pending operator take rhs as its lhs. *)
|
||||
let next_prec = precedence c2 in
|
||||
if token_prec < next_prec
|
||||
then parse_bin_rhs (token_prec + 1) rhs stream
|
||||
else rhs
|
||||
| _ -> rhs
|
||||
in
|
||||
|
||||
(* Merge lhs/rhs. *)
|
||||
let lhs = Ast.Binary (c, lhs, rhs) in
|
||||
parse_bin_rhs expr_prec lhs stream
|
||||
end
|
||||
| _ -> lhs
|
||||
|
||||
(* expression
|
||||
* ::= primary binoprhs *)
|
||||
and parse_expr = parser
|
||||
| [< lhs=parse_primary; stream >] -> parse_bin_rhs 0 lhs stream
|
||||
|
||||
(* prototype
|
||||
* ::= id '(' id* ')' *)
|
||||
let parse_prototype =
|
||||
let rec parse_args accumulator = parser
|
||||
| [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
|
||||
parser
|
||||
| [< 'Token.Ident id;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
(* success. *)
|
||||
Ast.Prototype (id, Array.of_list (List.rev args))
|
||||
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected function name in prototype")
|
||||
|
||||
(* definition ::= 'def' prototype expression *)
|
||||
let parse_definition = parser
|
||||
| [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
|
||||
Ast.Function (p, e)
|
||||
|
||||
(* toplevelexpr ::= expression *)
|
||||
let parse_toplevel = parser
|
||||
| [< e=parse_expr >] ->
|
||||
(* Make an anonymous proto. *)
|
||||
Ast.Function (Ast.Prototype ("", [||]), e)
|
||||
|
||||
(* external ::= 'extern' prototype *)
|
||||
let parse_extern = parser
|
||||
| [< 'Token.Extern; e=parse_prototype >] -> e
|
@ -1,19 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer Tokens
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
|
||||
* these others for known things. *)
|
||||
type token =
|
||||
(* commands *)
|
||||
| Def | Extern
|
||||
|
||||
(* primary *)
|
||||
| Ident of string | Number of float
|
||||
|
||||
(* unknown *)
|
||||
| Kwd of char
|
||||
|
||||
(* control *)
|
||||
| If | Then | Else
|
||||
| For | In
|
@ -1,49 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Top-Level parsing and JIT Driver
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
open Llvm_executionengine
|
||||
|
||||
(* top ::= definition | external | expression | ';' *)
|
||||
let rec main_loop the_fpm the_execution_engine stream =
|
||||
match Stream.peek stream with
|
||||
| None -> ()
|
||||
|
||||
(* ignore top-level semicolons. *)
|
||||
| Some (Token.Kwd ';') ->
|
||||
Stream.junk stream;
|
||||
main_loop the_fpm the_execution_engine stream
|
||||
|
||||
| Some token ->
|
||||
begin
|
||||
try match token with
|
||||
| Token.Def ->
|
||||
let e = Parser.parse_definition stream in
|
||||
print_endline "parsed a function definition.";
|
||||
dump_value (Codegen.codegen_func the_fpm e);
|
||||
| Token.Extern ->
|
||||
let e = Parser.parse_extern stream in
|
||||
print_endline "parsed an extern.";
|
||||
dump_value (Codegen.codegen_proto e);
|
||||
| _ ->
|
||||
(* Evaluate a top-level expression into an anonymous function. *)
|
||||
let e = Parser.parse_toplevel stream in
|
||||
print_endline "parsed a top-level expr";
|
||||
let the_function = Codegen.codegen_func the_fpm e in
|
||||
dump_value the_function;
|
||||
|
||||
(* JIT the function, returning a function pointer. *)
|
||||
let result = ExecutionEngine.run_function the_function [||]
|
||||
the_execution_engine in
|
||||
|
||||
print_string "Evaluated to ";
|
||||
print_float (GenericValue.as_float Codegen.double_type result);
|
||||
print_newline ();
|
||||
with Stream.Error s | Codegen.Error s ->
|
||||
(* Skip token for error recovery. *)
|
||||
Stream.junk stream;
|
||||
print_endline s;
|
||||
end;
|
||||
print_string "ready> "; flush stdout;
|
||||
main_loop the_fpm the_execution_engine stream
|
@ -1,53 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Main driver code.
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
open Llvm_executionengine
|
||||
open Llvm_target
|
||||
open Llvm_scalar_opts
|
||||
|
||||
let main () =
|
||||
ignore (initialize_native_target ());
|
||||
|
||||
(* Install standard binary operators.
|
||||
* 1 is the lowest precedence. *)
|
||||
Hashtbl.add Parser.binop_precedence '<' 10;
|
||||
Hashtbl.add Parser.binop_precedence '+' 20;
|
||||
Hashtbl.add Parser.binop_precedence '-' 20;
|
||||
Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
|
||||
|
||||
(* Prime the first token. *)
|
||||
print_string "ready> "; flush stdout;
|
||||
let stream = Lexer.lex (Stream.of_channel stdin) in
|
||||
|
||||
(* Create the JIT. *)
|
||||
let the_execution_engine = ExecutionEngine.create Codegen.the_module in
|
||||
let the_fpm = PassManager.create_function Codegen.the_module in
|
||||
|
||||
(* Set up the optimizer pipeline. Start with registering info about how the
|
||||
* target lays out data structures. *)
|
||||
TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
|
||||
|
||||
(* Do simple "peephole" optimizations and bit-twiddling optzn. *)
|
||||
add_instruction_combination the_fpm;
|
||||
|
||||
(* reassociate expressions. *)
|
||||
add_reassociation the_fpm;
|
||||
|
||||
(* Eliminate Common SubExpressions. *)
|
||||
add_gvn the_fpm;
|
||||
|
||||
(* Simplify the control flow graph (deleting unreachable blocks, etc). *)
|
||||
add_cfg_simplification the_fpm;
|
||||
|
||||
ignore (PassManager.initialize the_fpm);
|
||||
|
||||
(* Run the main "interpreter loop" now. *)
|
||||
Toplevel.main_loop the_fpm the_execution_engine stream;
|
||||
|
||||
(* Print out all the generated code. *)
|
||||
dump_module Codegen.the_module
|
||||
;;
|
||||
|
||||
main ()
|
@ -1,25 +0,0 @@
|
||||
##===- examples/OCaml-Kaleidoscope/Chapter6/Makefile -------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
#
|
||||
# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 6.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL := ../../..
|
||||
TOOLNAME := OCaml-Kaleidoscope-Ch6
|
||||
EXAMPLE_TOOL := 1
|
||||
UsedComponents := core
|
||||
UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
|
||||
llvm_scalar_opts
|
||||
|
||||
OCAMLCFLAGS += -pp camlp4of
|
||||
|
||||
ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
|
||||
|
||||
include $(LEVEL)/bindings/ocaml/Makefile.ocaml
|
@ -1,4 +0,0 @@
|
||||
<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
|
||||
<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
|
||||
<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
|
||||
<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
|
@ -1,36 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Abstract Syntax Tree (aka Parse Tree)
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* expr - Base type for all expression nodes. *)
|
||||
type expr =
|
||||
(* variant for numeric literals like "1.0". *)
|
||||
| Number of float
|
||||
|
||||
(* variant for referencing a variable, like "a". *)
|
||||
| Variable of string
|
||||
|
||||
(* variant for a unary operator. *)
|
||||
| Unary of char * expr
|
||||
|
||||
(* variant for a binary operator. *)
|
||||
| Binary of char * expr * expr
|
||||
|
||||
(* variant for function calls. *)
|
||||
| Call of string * expr array
|
||||
|
||||
(* variant for if/then/else. *)
|
||||
| If of expr * expr * expr
|
||||
|
||||
(* variant for for/in. *)
|
||||
| For of string * expr * expr * expr option * expr
|
||||
|
||||
(* proto - This type represents the "prototype" for a function, which captures
|
||||
* its name, and its argument names (thus implicitly the number of arguments the
|
||||
* function takes). *)
|
||||
type proto =
|
||||
| Prototype of string * string array
|
||||
| BinOpPrototype of string * string array * int
|
||||
|
||||
(* func - This type represents a function definition itself. *)
|
||||
type func = Function of proto * expr
|
@ -1,13 +0,0 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* putchard - putchar that takes a double and returns 0. */
|
||||
extern double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* printd - printf that takes a double prints it as "%f\n", returning 0. */
|
||||
extern double printd(double X) {
|
||||
printf("%f\n", X);
|
||||
return 0;
|
||||
}
|
@ -1,251 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Code Generation
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
exception Error of string
|
||||
|
||||
let context = global_context ()
|
||||
let the_module = create_module context "my cool jit"
|
||||
let builder = builder context
|
||||
let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
|
||||
let double_type = double_type context
|
||||
|
||||
let rec codegen_expr = function
|
||||
| Ast.Number n -> const_float double_type n
|
||||
| Ast.Variable name ->
|
||||
(try Hashtbl.find named_values name with
|
||||
| Not_found -> raise (Error "unknown variable name"))
|
||||
| Ast.Unary (op, operand) ->
|
||||
let operand = codegen_expr operand in
|
||||
let callee = "unary" ^ (String.make 1 op) in
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown unary operator")
|
||||
in
|
||||
build_call callee [|operand|] "unop" builder
|
||||
| Ast.Binary (op, lhs, rhs) ->
|
||||
let lhs_val = codegen_expr lhs in
|
||||
let rhs_val = codegen_expr rhs in
|
||||
begin
|
||||
match op with
|
||||
| '+' -> build_add lhs_val rhs_val "addtmp" builder
|
||||
| '-' -> build_sub lhs_val rhs_val "subtmp" builder
|
||||
| '*' -> build_mul lhs_val rhs_val "multmp" builder
|
||||
| '<' ->
|
||||
(* Convert bool 0/1 to double 0.0 or 1.0 *)
|
||||
let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
|
||||
build_uitofp i double_type "booltmp" builder
|
||||
| _ ->
|
||||
(* If it wasn't a builtin binary operator, it must be a user defined
|
||||
* one. Emit a call to it. *)
|
||||
let callee = "binary" ^ (String.make 1 op) in
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "binary operator not found!")
|
||||
in
|
||||
build_call callee [|lhs_val; rhs_val|] "binop" builder
|
||||
end
|
||||
| Ast.Call (callee, args) ->
|
||||
(* Look up the name in the module table. *)
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown function referenced")
|
||||
in
|
||||
let params = params callee in
|
||||
|
||||
(* If argument mismatch error. *)
|
||||
if Array.length params == Array.length args then () else
|
||||
raise (Error "incorrect # arguments passed");
|
||||
let args = Array.map codegen_expr args in
|
||||
build_call callee args "calltmp" builder
|
||||
| Ast.If (cond, then_, else_) ->
|
||||
let cond = codegen_expr cond in
|
||||
|
||||
(* Convert condition to a bool by comparing equal to 0.0 *)
|
||||
let zero = const_float double_type 0.0 in
|
||||
let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
|
||||
|
||||
(* Grab the first block so that we might later add the conditional branch
|
||||
* to it at the end of the function. *)
|
||||
let start_bb = insertion_block builder in
|
||||
let the_function = block_parent start_bb in
|
||||
|
||||
let then_bb = append_block context "then" the_function in
|
||||
|
||||
(* Emit 'then' value. *)
|
||||
position_at_end then_bb builder;
|
||||
let then_val = codegen_expr then_ in
|
||||
|
||||
(* Codegen of 'then' can change the current block, update then_bb for the
|
||||
* phi. We create a new name because one is used for the phi node, and the
|
||||
* other is used for the conditional branch. *)
|
||||
let new_then_bb = insertion_block builder in
|
||||
|
||||
(* Emit 'else' value. *)
|
||||
let else_bb = append_block context "else" the_function in
|
||||
position_at_end else_bb builder;
|
||||
let else_val = codegen_expr else_ in
|
||||
|
||||
(* Codegen of 'else' can change the current block, update else_bb for the
|
||||
* phi. *)
|
||||
let new_else_bb = insertion_block builder in
|
||||
|
||||
(* Emit merge block. *)
|
||||
let merge_bb = append_block context "ifcont" the_function in
|
||||
position_at_end merge_bb builder;
|
||||
let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
|
||||
let phi = build_phi incoming "iftmp" builder in
|
||||
|
||||
(* Return to the start block to add the conditional branch. *)
|
||||
position_at_end start_bb builder;
|
||||
ignore (build_cond_br cond_val then_bb else_bb builder);
|
||||
|
||||
(* Set a unconditional branch at the end of the 'then' block and the
|
||||
* 'else' block to the 'merge' block. *)
|
||||
position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
|
||||
position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
|
||||
|
||||
(* Finally, set the builder to the end of the merge block. *)
|
||||
position_at_end merge_bb builder;
|
||||
|
||||
phi
|
||||
| Ast.For (var_name, start, end_, step, body) ->
|
||||
(* Emit the start code first, without 'variable' in scope. *)
|
||||
let start_val = codegen_expr start in
|
||||
|
||||
(* Make the new basic block for the loop header, inserting after current
|
||||
* block. *)
|
||||
let preheader_bb = insertion_block builder in
|
||||
let the_function = block_parent preheader_bb in
|
||||
let loop_bb = append_block context "loop" the_function in
|
||||
|
||||
(* Insert an explicit fall through from the current block to the
|
||||
* loop_bb. *)
|
||||
ignore (build_br loop_bb builder);
|
||||
|
||||
(* Start insertion in loop_bb. *)
|
||||
position_at_end loop_bb builder;
|
||||
|
||||
(* Start the PHI node with an entry for start. *)
|
||||
let variable = build_phi [(start_val, preheader_bb)] var_name builder in
|
||||
|
||||
(* Within the loop, the variable is defined equal to the PHI node. If it
|
||||
* shadows an existing variable, we have to restore it, so save it
|
||||
* now. *)
|
||||
let old_val =
|
||||
try Some (Hashtbl.find named_values var_name) with Not_found -> None
|
||||
in
|
||||
Hashtbl.add named_values var_name variable;
|
||||
|
||||
(* Emit the body of the loop. This, like any other expr, can change the
|
||||
* current BB. Note that we ignore the value computed by the body, but
|
||||
* don't allow an error *)
|
||||
ignore (codegen_expr body);
|
||||
|
||||
(* Emit the step value. *)
|
||||
let step_val =
|
||||
match step with
|
||||
| Some step -> codegen_expr step
|
||||
(* If not specified, use 1.0. *)
|
||||
| None -> const_float double_type 1.0
|
||||
in
|
||||
|
||||
let next_var = build_add variable step_val "nextvar" builder in
|
||||
|
||||
(* Compute the end condition. *)
|
||||
let end_cond = codegen_expr end_ in
|
||||
|
||||
(* Convert condition to a bool by comparing equal to 0.0. *)
|
||||
let zero = const_float double_type 0.0 in
|
||||
let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
|
||||
|
||||
(* Create the "after loop" block and insert it. *)
|
||||
let loop_end_bb = insertion_block builder in
|
||||
let after_bb = append_block context "afterloop" the_function in
|
||||
|
||||
(* Insert the conditional branch into the end of loop_end_bb. *)
|
||||
ignore (build_cond_br end_cond loop_bb after_bb builder);
|
||||
|
||||
(* Any new code will be inserted in after_bb. *)
|
||||
position_at_end after_bb builder;
|
||||
|
||||
(* Add a new entry to the PHI node for the backedge. *)
|
||||
add_incoming (next_var, loop_end_bb) variable;
|
||||
|
||||
(* Restore the unshadowed variable. *)
|
||||
begin match old_val with
|
||||
| Some old_val -> Hashtbl.add named_values var_name old_val
|
||||
| None -> ()
|
||||
end;
|
||||
|
||||
(* for expr always returns 0.0. *)
|
||||
const_null double_type
|
||||
|
||||
let codegen_proto = function
|
||||
| Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) ->
|
||||
(* Make the function type: double(double,double) etc. *)
|
||||
let doubles = Array.make (Array.length args) double_type in
|
||||
let ft = function_type double_type doubles in
|
||||
let f =
|
||||
match lookup_function name the_module with
|
||||
| None -> declare_function name ft the_module
|
||||
|
||||
(* If 'f' conflicted, there was already something named 'name'. If it
|
||||
* has a body, don't allow redefinition or reextern. *)
|
||||
| Some f ->
|
||||
(* If 'f' already has a body, reject this. *)
|
||||
if block_begin f <> At_end f then
|
||||
raise (Error "redefinition of function");
|
||||
|
||||
(* If 'f' took a different number of arguments, reject. *)
|
||||
if element_type (type_of f) <> ft then
|
||||
raise (Error "redefinition of function with different # args");
|
||||
f
|
||||
in
|
||||
|
||||
(* Set names for all arguments. *)
|
||||
Array.iteri (fun i a ->
|
||||
let n = args.(i) in
|
||||
set_value_name n a;
|
||||
Hashtbl.add named_values n a;
|
||||
) (params f);
|
||||
f
|
||||
|
||||
let codegen_func the_fpm = function
|
||||
| Ast.Function (proto, body) ->
|
||||
Hashtbl.clear named_values;
|
||||
let the_function = codegen_proto proto in
|
||||
|
||||
(* If this is an operator, install it. *)
|
||||
begin match proto with
|
||||
| Ast.BinOpPrototype (name, args, prec) ->
|
||||
let op = name.[String.length name - 1] in
|
||||
Hashtbl.add Parser.binop_precedence op prec;
|
||||
| _ -> ()
|
||||
end;
|
||||
|
||||
(* Create a new basic block to start insertion into. *)
|
||||
let bb = append_block context "entry" the_function in
|
||||
position_at_end bb builder;
|
||||
|
||||
try
|
||||
let ret_val = codegen_expr body in
|
||||
|
||||
(* Finish off the function. *)
|
||||
let _ = build_ret ret_val builder in
|
||||
|
||||
(* Validate the generated code, checking for consistency. *)
|
||||
Llvm_analysis.assert_valid_function the_function;
|
||||
|
||||
(* Optimize the function. *)
|
||||
let _ = PassManager.run_function the_function the_fpm in
|
||||
|
||||
the_function
|
||||
with e ->
|
||||
delete_function the_function;
|
||||
raise e
|
@ -1,59 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let rec lex = parser
|
||||
(* Skip any whitespace. *)
|
||||
| [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
|
||||
|
||||
(* identifier: [a-zA-Z][a-zA-Z0-9] *)
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
|
||||
(* number: [0-9.]+ *)
|
||||
| [< ' ('0' .. '9' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
|
||||
(* Comment until end of line. *)
|
||||
| [< ' ('#'); stream >] ->
|
||||
lex_comment stream
|
||||
|
||||
(* Otherwise, just return the character as its ascii value. *)
|
||||
| [< 'c; stream >] ->
|
||||
[< 'Token.Kwd c; lex stream >]
|
||||
|
||||
(* end of stream. *)
|
||||
| [< >] -> [< >]
|
||||
|
||||
and lex_number buffer = parser
|
||||
| [< ' ('0' .. '9' | '.' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
| [< stream=lex >] ->
|
||||
[< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
|
||||
|
||||
and lex_ident buffer = parser
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
| [< stream=lex >] ->
|
||||
match Buffer.contents buffer with
|
||||
| "def" -> [< 'Token.Def; stream >]
|
||||
| "extern" -> [< 'Token.Extern; stream >]
|
||||
| "if" -> [< 'Token.If; stream >]
|
||||
| "then" -> [< 'Token.Then; stream >]
|
||||
| "else" -> [< 'Token.Else; stream >]
|
||||
| "for" -> [< 'Token.For; stream >]
|
||||
| "in" -> [< 'Token.In; stream >]
|
||||
| "binary" -> [< 'Token.Binary; stream >]
|
||||
| "unary" -> [< 'Token.Unary; stream >]
|
||||
| id -> [< 'Token.Ident id; stream >]
|
||||
|
||||
and lex_comment = parser
|
||||
| [< ' ('\n'); stream=lex >] -> stream
|
||||
| [< 'c; e=lex_comment >] -> e
|
||||
| [< >] -> [< >]
|
@ -1,10 +0,0 @@
|
||||
open Ocamlbuild_plugin;;
|
||||
|
||||
ocaml_lib ~extern:true "llvm";;
|
||||
ocaml_lib ~extern:true "llvm_analysis";;
|
||||
ocaml_lib ~extern:true "llvm_executionengine";;
|
||||
ocaml_lib ~extern:true "llvm_target";;
|
||||
ocaml_lib ~extern:true "llvm_scalar_opts";;
|
||||
|
||||
flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
|
||||
dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
|
@ -1,195 +0,0 @@
|
||||
(*===---------------------------------------------------------------------===
|
||||
* Parser
|
||||
*===---------------------------------------------------------------------===*)
|
||||
|
||||
(* binop_precedence - This holds the precedence for each binary operator that is
|
||||
* defined *)
|
||||
let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
|
||||
|
||||
(* precedence - Get the precedence of the pending binary operator token. *)
|
||||
let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
|
||||
|
||||
(* primary
|
||||
* ::= identifier
|
||||
* ::= numberexpr
|
||||
* ::= parenexpr
|
||||
* ::= ifexpr
|
||||
* ::= forexpr *)
|
||||
let rec parse_primary = parser
|
||||
(* numberexpr ::= number *)
|
||||
| [< 'Token.Number n >] -> Ast.Number n
|
||||
|
||||
(* parenexpr ::= '(' expression ')' *)
|
||||
| [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
|
||||
|
||||
(* identifierexpr
|
||||
* ::= identifier
|
||||
* ::= identifier '(' argumentexpr ')' *)
|
||||
| [< 'Token.Ident id; stream >] ->
|
||||
let rec parse_args accumulator = parser
|
||||
| [< e=parse_expr; stream >] ->
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
|
||||
| [< >] -> e :: accumulator
|
||||
end stream
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let rec parse_ident id = parser
|
||||
(* Call. *)
|
||||
| [< 'Token.Kwd '(';
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')'">] ->
|
||||
Ast.Call (id, Array.of_list (List.rev args))
|
||||
|
||||
(* Simple variable ref. *)
|
||||
| [< >] -> Ast.Variable id
|
||||
in
|
||||
parse_ident id stream
|
||||
|
||||
(* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
|
||||
| [< 'Token.If; c=parse_expr;
|
||||
'Token.Then ?? "expected 'then'"; t=parse_expr;
|
||||
'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
|
||||
Ast.If (c, t, e)
|
||||
|
||||
(* forexpr
|
||||
::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
|
||||
| [< 'Token.For;
|
||||
'Token.Ident id ?? "expected identifier after for";
|
||||
'Token.Kwd '=' ?? "expected '=' after for";
|
||||
stream >] ->
|
||||
begin parser
|
||||
| [<
|
||||
start=parse_expr;
|
||||
'Token.Kwd ',' ?? "expected ',' after for";
|
||||
end_=parse_expr;
|
||||
stream >] ->
|
||||
let step =
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; step=parse_expr >] -> Some step
|
||||
| [< >] -> None
|
||||
end stream
|
||||
in
|
||||
begin parser
|
||||
| [< 'Token.In; body=parse_expr >] ->
|
||||
Ast.For (id, start, end_, step, body)
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected 'in' after for")
|
||||
end stream
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected '=' after for")
|
||||
end stream
|
||||
|
||||
| [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
|
||||
|
||||
(* unary
|
||||
* ::= primary
|
||||
* ::= '!' unary *)
|
||||
and parse_unary = parser
|
||||
(* If this is a unary operator, read it. *)
|
||||
| [< 'Token.Kwd op when op != '(' && op != ')'; operand=parse_expr >] ->
|
||||
Ast.Unary (op, operand)
|
||||
|
||||
(* If the current token is not an operator, it must be a primary expr. *)
|
||||
| [< stream >] -> parse_primary stream
|
||||
|
||||
(* binoprhs
|
||||
* ::= ('+' primary)* *)
|
||||
and parse_bin_rhs expr_prec lhs stream =
|
||||
match Stream.peek stream with
|
||||
(* If this is a binop, find its precedence. *)
|
||||
| Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
|
||||
let token_prec = precedence c in
|
||||
|
||||
(* If this is a binop that binds at least as tightly as the current binop,
|
||||
* consume it, otherwise we are done. *)
|
||||
if token_prec < expr_prec then lhs else begin
|
||||
(* Eat the binop. *)
|
||||
Stream.junk stream;
|
||||
|
||||
(* Parse the unary expression after the binary operator. *)
|
||||
let rhs = parse_unary stream in
|
||||
|
||||
(* Okay, we know this is a binop. *)
|
||||
let rhs =
|
||||
match Stream.peek stream with
|
||||
| Some (Token.Kwd c2) ->
|
||||
(* If BinOp binds less tightly with rhs than the operator after
|
||||
* rhs, let the pending operator take rhs as its lhs. *)
|
||||
let next_prec = precedence c2 in
|
||||
if token_prec < next_prec
|
||||
then parse_bin_rhs (token_prec + 1) rhs stream
|
||||
else rhs
|
||||
| _ -> rhs
|
||||
in
|
||||
|
||||
(* Merge lhs/rhs. *)
|
||||
let lhs = Ast.Binary (c, lhs, rhs) in
|
||||
parse_bin_rhs expr_prec lhs stream
|
||||
end
|
||||
| _ -> lhs
|
||||
|
||||
(* expression
|
||||
* ::= primary binoprhs *)
|
||||
and parse_expr = parser
|
||||
| [< lhs=parse_unary; stream >] -> parse_bin_rhs 0 lhs stream
|
||||
|
||||
(* prototype
|
||||
* ::= id '(' id* ')'
|
||||
* ::= binary LETTER number? (id, id)
|
||||
* ::= unary LETTER number? (id) *)
|
||||
let parse_prototype =
|
||||
let rec parse_args accumulator = parser
|
||||
| [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let parse_operator = parser
|
||||
| [< 'Token.Unary >] -> "unary", 1
|
||||
| [< 'Token.Binary >] -> "binary", 2
|
||||
in
|
||||
let parse_binary_precedence = parser
|
||||
| [< 'Token.Number n >] -> int_of_float n
|
||||
| [< >] -> 30
|
||||
in
|
||||
parser
|
||||
| [< 'Token.Ident id;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
(* success. *)
|
||||
Ast.Prototype (id, Array.of_list (List.rev args))
|
||||
| [< (prefix, kind)=parse_operator;
|
||||
'Token.Kwd op ?? "expected an operator";
|
||||
(* Read the precedence if present. *)
|
||||
binary_precedence=parse_binary_precedence;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
let name = prefix ^ (String.make 1 op) in
|
||||
let args = Array.of_list (List.rev args) in
|
||||
|
||||
(* Verify right number of arguments for operator. *)
|
||||
if Array.length args != kind
|
||||
then raise (Stream.Error "invalid number of operands for operator")
|
||||
else
|
||||
if kind == 1 then
|
||||
Ast.Prototype (name, args)
|
||||
else
|
||||
Ast.BinOpPrototype (name, args, binary_precedence)
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected function name in prototype")
|
||||
|
||||
(* definition ::= 'def' prototype expression *)
|
||||
let parse_definition = parser
|
||||
| [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
|
||||
Ast.Function (p, e)
|
||||
|
||||
(* toplevelexpr ::= expression *)
|
||||
let parse_toplevel = parser
|
||||
| [< e=parse_expr >] ->
|
||||
(* Make an anonymous proto. *)
|
||||
Ast.Function (Ast.Prototype ("", [||]), e)
|
||||
|
||||
(* external ::= 'extern' prototype *)
|
||||
let parse_extern = parser
|
||||
| [< 'Token.Extern; e=parse_prototype >] -> e
|
@ -1,22 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer Tokens
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
|
||||
* these others for known things. *)
|
||||
type token =
|
||||
(* commands *)
|
||||
| Def | Extern
|
||||
|
||||
(* primary *)
|
||||
| Ident of string | Number of float
|
||||
|
||||
(* unknown *)
|
||||
| Kwd of char
|
||||
|
||||
(* control *)
|
||||
| If | Then | Else
|
||||
| For | In
|
||||
|
||||
(* operators *)
|
||||
| Binary | Unary
|
@ -1,49 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Top-Level parsing and JIT Driver
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
open Llvm_executionengine
|
||||
|
||||
(* top ::= definition | external | expression | ';' *)
|
||||
let rec main_loop the_fpm the_execution_engine stream =
|
||||
match Stream.peek stream with
|
||||
| None -> ()
|
||||
|
||||
(* ignore top-level semicolons. *)
|
||||
| Some (Token.Kwd ';') ->
|
||||
Stream.junk stream;
|
||||
main_loop the_fpm the_execution_engine stream
|
||||
|
||||
| Some token ->
|
||||
begin
|
||||
try match token with
|
||||
| Token.Def ->
|
||||
let e = Parser.parse_definition stream in
|
||||
print_endline "parsed a function definition.";
|
||||
dump_value (Codegen.codegen_func the_fpm e);
|
||||
| Token.Extern ->
|
||||
let e = Parser.parse_extern stream in
|
||||
print_endline "parsed an extern.";
|
||||
dump_value (Codegen.codegen_proto e);
|
||||
| _ ->
|
||||
(* Evaluate a top-level expression into an anonymous function. *)
|
||||
let e = Parser.parse_toplevel stream in
|
||||
print_endline "parsed a top-level expr";
|
||||
let the_function = Codegen.codegen_func the_fpm e in
|
||||
dump_value the_function;
|
||||
|
||||
(* JIT the function, returning a function pointer. *)
|
||||
let result = ExecutionEngine.run_function the_function [||]
|
||||
the_execution_engine in
|
||||
|
||||
print_string "Evaluated to ";
|
||||
print_float (GenericValue.as_float Codegen.double_type result);
|
||||
print_newline ();
|
||||
with Stream.Error s | Codegen.Error s ->
|
||||
(* Skip token for error recovery. *)
|
||||
Stream.junk stream;
|
||||
print_endline s;
|
||||
end;
|
||||
print_string "ready> "; flush stdout;
|
||||
main_loop the_fpm the_execution_engine stream
|
@ -1,53 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Main driver code.
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
open Llvm_executionengine
|
||||
open Llvm_target
|
||||
open Llvm_scalar_opts
|
||||
|
||||
let main () =
|
||||
ignore (initialize_native_target ());
|
||||
|
||||
(* Install standard binary operators.
|
||||
* 1 is the lowest precedence. *)
|
||||
Hashtbl.add Parser.binop_precedence '<' 10;
|
||||
Hashtbl.add Parser.binop_precedence '+' 20;
|
||||
Hashtbl.add Parser.binop_precedence '-' 20;
|
||||
Hashtbl.add Parser.binop_precedence '*' 40; (* highest. *)
|
||||
|
||||
(* Prime the first token. *)
|
||||
print_string "ready> "; flush stdout;
|
||||
let stream = Lexer.lex (Stream.of_channel stdin) in
|
||||
|
||||
(* Create the JIT. *)
|
||||
let the_execution_engine = ExecutionEngine.create Codegen.the_module in
|
||||
let the_fpm = PassManager.create_function Codegen.the_module in
|
||||
|
||||
(* Set up the optimizer pipeline. Start with registering info about how the
|
||||
* target lays out data structures. *)
|
||||
TargetData.add (ExecutionEngine.target_data the_execution_engine) the_fpm;
|
||||
|
||||
(* Do simple "peephole" optimizations and bit-twiddling optzn. *)
|
||||
add_instruction_combination the_fpm;
|
||||
|
||||
(* reassociate expressions. *)
|
||||
add_reassociation the_fpm;
|
||||
|
||||
(* Eliminate Common SubExpressions. *)
|
||||
add_gvn the_fpm;
|
||||
|
||||
(* Simplify the control flow graph (deleting unreachable blocks, etc). *)
|
||||
add_cfg_simplification the_fpm;
|
||||
|
||||
ignore (PassManager.initialize the_fpm);
|
||||
|
||||
(* Run the main "interpreter loop" now. *)
|
||||
Toplevel.main_loop the_fpm the_execution_engine stream;
|
||||
|
||||
(* Print out all the generated code. *)
|
||||
dump_module Codegen.the_module
|
||||
;;
|
||||
|
||||
main ()
|
@ -1,25 +0,0 @@
|
||||
##===- examples/OCaml-Kaleidoscope/Chapter7/Makefile -------*- Makefile -*-===##
|
||||
#
|
||||
# The LLVM Compiler Infrastructure
|
||||
#
|
||||
# This file is distributed under the University of Illinois Open Source
|
||||
# License. See LICENSE.TXT for details.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
#
|
||||
# This is the makefile for the Objective Caml kaleidoscope tutorial, chapter 7.
|
||||
#
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
LEVEL := ../../..
|
||||
TOOLNAME := OCaml-Kaleidoscope-Ch7
|
||||
EXAMPLE_TOOL := 1
|
||||
UsedComponents := core
|
||||
UsedOcamLibs := llvm llvm_analysis llvm_executionengine llvm_target \
|
||||
llvm_scalar_opts
|
||||
|
||||
OCAMLCFLAGS += -pp camlp4of
|
||||
|
||||
ExcludeSources = $(PROJ_SRC_DIR)/myocamlbuild.ml
|
||||
|
||||
include $(LEVEL)/bindings/ocaml/Makefile.ocaml
|
@ -1,4 +0,0 @@
|
||||
<{lexer,parser}.ml>: use_camlp4, pp(camlp4of)
|
||||
<*.{byte,native}>: g++, use_llvm, use_llvm_analysis
|
||||
<*.{byte,native}>: use_llvm_executionengine, use_llvm_target
|
||||
<*.{byte,native}>: use_llvm_scalar_opts, use_bindings
|
@ -1,39 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Abstract Syntax Tree (aka Parse Tree)
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* expr - Base type for all expression nodes. *)
|
||||
type expr =
|
||||
(* variant for numeric literals like "1.0". *)
|
||||
| Number of float
|
||||
|
||||
(* variant for referencing a variable, like "a". *)
|
||||
| Variable of string
|
||||
|
||||
(* variant for a unary operator. *)
|
||||
| Unary of char * expr
|
||||
|
||||
(* variant for a binary operator. *)
|
||||
| Binary of char * expr * expr
|
||||
|
||||
(* variant for function calls. *)
|
||||
| Call of string * expr array
|
||||
|
||||
(* variant for if/then/else. *)
|
||||
| If of expr * expr * expr
|
||||
|
||||
(* variant for for/in. *)
|
||||
| For of string * expr * expr * expr option * expr
|
||||
|
||||
(* variant for var/in. *)
|
||||
| Var of (string * expr option) array * expr
|
||||
|
||||
(* proto - This type represents the "prototype" for a function, which captures
|
||||
* its name, and its argument names (thus implicitly the number of arguments the
|
||||
* function takes). *)
|
||||
type proto =
|
||||
| Prototype of string * string array
|
||||
| BinOpPrototype of string * string array * int
|
||||
|
||||
(* func - This type represents a function definition itself. *)
|
||||
type func = Function of proto * expr
|
@ -1,13 +0,0 @@
|
||||
#include <stdio.h>
|
||||
|
||||
/* putchard - putchar that takes a double and returns 0. */
|
||||
extern double putchard(double X) {
|
||||
putchar((char)X);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* printd - printf that takes a double prints it as "%f\n", returning 0. */
|
||||
extern double printd(double X) {
|
||||
printf("%f\n", X);
|
||||
return 0;
|
||||
}
|
@ -1,370 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Code Generation
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
open Llvm
|
||||
|
||||
exception Error of string
|
||||
|
||||
let context = global_context ()
|
||||
let the_module = create_module context "my cool jit"
|
||||
let builder = builder context
|
||||
let named_values:(string, llvalue) Hashtbl.t = Hashtbl.create 10
|
||||
let double_type = double_type context
|
||||
|
||||
(* Create an alloca instruction in the entry block of the function. This
|
||||
* is used for mutable variables etc. *)
|
||||
let create_entry_block_alloca the_function var_name =
|
||||
let builder = builder_at context (instr_begin (entry_block the_function)) in
|
||||
build_alloca double_type var_name builder
|
||||
|
||||
let rec codegen_expr = function
|
||||
| Ast.Number n -> const_float double_type n
|
||||
| Ast.Variable name ->
|
||||
let v = try Hashtbl.find named_values name with
|
||||
| Not_found -> raise (Error "unknown variable name")
|
||||
in
|
||||
(* Load the value. *)
|
||||
build_load v name builder
|
||||
| Ast.Unary (op, operand) ->
|
||||
let operand = codegen_expr operand in
|
||||
let callee = "unary" ^ (String.make 1 op) in
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown unary operator")
|
||||
in
|
||||
build_call callee [|operand|] "unop" builder
|
||||
| Ast.Binary (op, lhs, rhs) ->
|
||||
begin match op with
|
||||
| '=' ->
|
||||
(* Special case '=' because we don't want to emit the LHS as an
|
||||
* expression. *)
|
||||
let name =
|
||||
match lhs with
|
||||
| Ast.Variable name -> name
|
||||
| _ -> raise (Error "destination of '=' must be a variable")
|
||||
in
|
||||
|
||||
(* Codegen the rhs. *)
|
||||
let val_ = codegen_expr rhs in
|
||||
|
||||
(* Lookup the name. *)
|
||||
let variable = try Hashtbl.find named_values name with
|
||||
| Not_found -> raise (Error "unknown variable name")
|
||||
in
|
||||
ignore(build_store val_ variable builder);
|
||||
val_
|
||||
| _ ->
|
||||
let lhs_val = codegen_expr lhs in
|
||||
let rhs_val = codegen_expr rhs in
|
||||
begin
|
||||
match op with
|
||||
| '+' -> build_add lhs_val rhs_val "addtmp" builder
|
||||
| '-' -> build_sub lhs_val rhs_val "subtmp" builder
|
||||
| '*' -> build_mul lhs_val rhs_val "multmp" builder
|
||||
| '<' ->
|
||||
(* Convert bool 0/1 to double 0.0 or 1.0 *)
|
||||
let i = build_fcmp Fcmp.Ult lhs_val rhs_val "cmptmp" builder in
|
||||
build_uitofp i double_type "booltmp" builder
|
||||
| _ ->
|
||||
(* If it wasn't a builtin binary operator, it must be a user defined
|
||||
* one. Emit a call to it. *)
|
||||
let callee = "binary" ^ (String.make 1 op) in
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "binary operator not found!")
|
||||
in
|
||||
build_call callee [|lhs_val; rhs_val|] "binop" builder
|
||||
end
|
||||
end
|
||||
| Ast.Call (callee, args) ->
|
||||
(* Look up the name in the module table. *)
|
||||
let callee =
|
||||
match lookup_function callee the_module with
|
||||
| Some callee -> callee
|
||||
| None -> raise (Error "unknown function referenced")
|
||||
in
|
||||
let params = params callee in
|
||||
|
||||
(* If argument mismatch error. *)
|
||||
if Array.length params == Array.length args then () else
|
||||
raise (Error "incorrect # arguments passed");
|
||||
let args = Array.map codegen_expr args in
|
||||
build_call callee args "calltmp" builder
|
||||
| Ast.If (cond, then_, else_) ->
|
||||
let cond = codegen_expr cond in
|
||||
|
||||
(* Convert condition to a bool by comparing equal to 0.0 *)
|
||||
let zero = const_float double_type 0.0 in
|
||||
let cond_val = build_fcmp Fcmp.One cond zero "ifcond" builder in
|
||||
|
||||
(* Grab the first block so that we might later add the conditional branch
|
||||
* to it at the end of the function. *)
|
||||
let start_bb = insertion_block builder in
|
||||
let the_function = block_parent start_bb in
|
||||
|
||||
let then_bb = append_block context "then" the_function in
|
||||
|
||||
(* Emit 'then' value. *)
|
||||
position_at_end then_bb builder;
|
||||
let then_val = codegen_expr then_ in
|
||||
|
||||
(* Codegen of 'then' can change the current block, update then_bb for the
|
||||
* phi. We create a new name because one is used for the phi node, and the
|
||||
* other is used for the conditional branch. *)
|
||||
let new_then_bb = insertion_block builder in
|
||||
|
||||
(* Emit 'else' value. *)
|
||||
let else_bb = append_block context "else" the_function in
|
||||
position_at_end else_bb builder;
|
||||
let else_val = codegen_expr else_ in
|
||||
|
||||
(* Codegen of 'else' can change the current block, update else_bb for the
|
||||
* phi. *)
|
||||
let new_else_bb = insertion_block builder in
|
||||
|
||||
(* Emit merge block. *)
|
||||
let merge_bb = append_block context "ifcont" the_function in
|
||||
position_at_end merge_bb builder;
|
||||
let incoming = [(then_val, new_then_bb); (else_val, new_else_bb)] in
|
||||
let phi = build_phi incoming "iftmp" builder in
|
||||
|
||||
(* Return to the start block to add the conditional branch. *)
|
||||
position_at_end start_bb builder;
|
||||
ignore (build_cond_br cond_val then_bb else_bb builder);
|
||||
|
||||
(* Set a unconditional branch at the end of the 'then' block and the
|
||||
* 'else' block to the 'merge' block. *)
|
||||
position_at_end new_then_bb builder; ignore (build_br merge_bb builder);
|
||||
position_at_end new_else_bb builder; ignore (build_br merge_bb builder);
|
||||
|
||||
(* Finally, set the builder to the end of the merge block. *)
|
||||
position_at_end merge_bb builder;
|
||||
|
||||
phi
|
||||
| Ast.For (var_name, start, end_, step, body) ->
|
||||
(* Output this as:
|
||||
* var = alloca double
|
||||
* ...
|
||||
* start = startexpr
|
||||
* store start -> var
|
||||
* goto loop
|
||||
* loop:
|
||||
* ...
|
||||
* bodyexpr
|
||||
* ...
|
||||
* loopend:
|
||||
* step = stepexpr
|
||||
* endcond = endexpr
|
||||
*
|
||||
* curvar = load var
|
||||
* nextvar = curvar + step
|
||||
* store nextvar -> var
|
||||
* br endcond, loop, endloop
|
||||
* outloop: *)
|
||||
|
||||
let the_function = block_parent (insertion_block builder) in
|
||||
|
||||
(* Create an alloca for the variable in the entry block. *)
|
||||
let alloca = create_entry_block_alloca the_function var_name in
|
||||
|
||||
(* Emit the start code first, without 'variable' in scope. *)
|
||||
let start_val = codegen_expr start in
|
||||
|
||||
(* Store the value into the alloca. *)
|
||||
ignore(build_store start_val alloca builder);
|
||||
|
||||
(* Make the new basic block for the loop header, inserting after current
|
||||
* block. *)
|
||||
let loop_bb = append_block context "loop" the_function in
|
||||
|
||||
(* Insert an explicit fall through from the current block to the
|
||||
* loop_bb. *)
|
||||
ignore (build_br loop_bb builder);
|
||||
|
||||
(* Start insertion in loop_bb. *)
|
||||
position_at_end loop_bb builder;
|
||||
|
||||
(* Within the loop, the variable is defined equal to the PHI node. If it
|
||||
* shadows an existing variable, we have to restore it, so save it
|
||||
* now. *)
|
||||
let old_val =
|
||||
try Some (Hashtbl.find named_values var_name) with Not_found -> None
|
||||
in
|
||||
Hashtbl.add named_values var_name alloca;
|
||||
|
||||
(* Emit the body of the loop. This, like any other expr, can change the
|
||||
* current BB. Note that we ignore the value computed by the body, but
|
||||
* don't allow an error *)
|
||||
ignore (codegen_expr body);
|
||||
|
||||
(* Emit the step value. *)
|
||||
let step_val =
|
||||
match step with
|
||||
| Some step -> codegen_expr step
|
||||
(* If not specified, use 1.0. *)
|
||||
| None -> const_float double_type 1.0
|
||||
in
|
||||
|
||||
(* Compute the end condition. *)
|
||||
let end_cond = codegen_expr end_ in
|
||||
|
||||
(* Reload, increment, and restore the alloca. This handles the case where
|
||||
* the body of the loop mutates the variable. *)
|
||||
let cur_var = build_load alloca var_name builder in
|
||||
let next_var = build_add cur_var step_val "nextvar" builder in
|
||||
ignore(build_store next_var alloca builder);
|
||||
|
||||
(* Convert condition to a bool by comparing equal to 0.0. *)
|
||||
let zero = const_float double_type 0.0 in
|
||||
let end_cond = build_fcmp Fcmp.One end_cond zero "loopcond" builder in
|
||||
|
||||
(* Create the "after loop" block and insert it. *)
|
||||
let after_bb = append_block context "afterloop" the_function in
|
||||
|
||||
(* Insert the conditional branch into the end of loop_end_bb. *)
|
||||
ignore (build_cond_br end_cond loop_bb after_bb builder);
|
||||
|
||||
(* Any new code will be inserted in after_bb. *)
|
||||
position_at_end after_bb builder;
|
||||
|
||||
(* Restore the unshadowed variable. *)
|
||||
begin match old_val with
|
||||
| Some old_val -> Hashtbl.add named_values var_name old_val
|
||||
| None -> ()
|
||||
end;
|
||||
|
||||
(* for expr always returns 0.0. *)
|
||||
const_null double_type
|
||||
| Ast.Var (var_names, body) ->
|
||||
let old_bindings = ref [] in
|
||||
|
||||
let the_function = block_parent (insertion_block builder) in
|
||||
|
||||
(* Register all variables and emit their initializer. *)
|
||||
Array.iter (fun (var_name, init) ->
|
||||
(* Emit the initializer before adding the variable to scope, this
|
||||
* prevents the initializer from referencing the variable itself, and
|
||||
* permits stuff like this:
|
||||
* var a = 1 in
|
||||
* var a = a in ... # refers to outer 'a'. *)
|
||||
let init_val =
|
||||
match init with
|
||||
| Some init -> codegen_expr init
|
||||
(* If not specified, use 0.0. *)
|
||||
| None -> const_float double_type 0.0
|
||||
in
|
||||
|
||||
let alloca = create_entry_block_alloca the_function var_name in
|
||||
ignore(build_store init_val alloca builder);
|
||||
|
||||
(* Remember the old variable binding so that we can restore the binding
|
||||
* when we unrecurse. *)
|
||||
begin
|
||||
try
|
||||
let old_value = Hashtbl.find named_values var_name in
|
||||
old_bindings := (var_name, old_value) :: !old_bindings;
|
||||
with Not_found -> ()
|
||||
end;
|
||||
|
||||
(* Remember this binding. *)
|
||||
Hashtbl.add named_values var_name alloca;
|
||||
) var_names;
|
||||
|
||||
(* Codegen the body, now that all vars are in scope. *)
|
||||
let body_val = codegen_expr body in
|
||||
|
||||
(* Pop all our variables from scope. *)
|
||||
List.iter (fun (var_name, old_value) ->
|
||||
Hashtbl.add named_values var_name old_value
|
||||
) !old_bindings;
|
||||
|
||||
(* Return the body computation. *)
|
||||
body_val
|
||||
|
||||
let codegen_proto = function
|
||||
| Ast.Prototype (name, args) | Ast.BinOpPrototype (name, args, _) ->
|
||||
(* Make the function type: double(double,double) etc. *)
|
||||
let doubles = Array.make (Array.length args) double_type in
|
||||
let ft = function_type double_type doubles in
|
||||
let f =
|
||||
match lookup_function name the_module with
|
||||
| None -> declare_function name ft the_module
|
||||
|
||||
(* If 'f' conflicted, there was already something named 'name'. If it
|
||||
* has a body, don't allow redefinition or reextern. *)
|
||||
| Some f ->
|
||||
(* If 'f' already has a body, reject this. *)
|
||||
if block_begin f <> At_end f then
|
||||
raise (Error "redefinition of function");
|
||||
|
||||
(* If 'f' took a different number of arguments, reject. *)
|
||||
if element_type (type_of f) <> ft then
|
||||
raise (Error "redefinition of function with different # args");
|
||||
f
|
||||
in
|
||||
|
||||
(* Set names for all arguments. *)
|
||||
Array.iteri (fun i a ->
|
||||
let n = args.(i) in
|
||||
set_value_name n a;
|
||||
Hashtbl.add named_values n a;
|
||||
) (params f);
|
||||
f
|
||||
|
||||
(* Create an alloca for each argument and register the argument in the symbol
|
||||
* table so that references to it will succeed. *)
|
||||
let create_argument_allocas the_function proto =
|
||||
let args = match proto with
|
||||
| Ast.Prototype (_, args) | Ast.BinOpPrototype (_, args, _) -> args
|
||||
in
|
||||
Array.iteri (fun i ai ->
|
||||
let var_name = args.(i) in
|
||||
(* Create an alloca for this variable. *)
|
||||
let alloca = create_entry_block_alloca the_function var_name in
|
||||
|
||||
(* Store the initial value into the alloca. *)
|
||||
ignore(build_store ai alloca builder);
|
||||
|
||||
(* Add arguments to variable symbol table. *)
|
||||
Hashtbl.add named_values var_name alloca;
|
||||
) (params the_function)
|
||||
|
||||
let codegen_func the_fpm = function
|
||||
| Ast.Function (proto, body) ->
|
||||
Hashtbl.clear named_values;
|
||||
let the_function = codegen_proto proto in
|
||||
|
||||
(* If this is an operator, install it. *)
|
||||
begin match proto with
|
||||
| Ast.BinOpPrototype (name, args, prec) ->
|
||||
let op = name.[String.length name - 1] in
|
||||
Hashtbl.add Parser.binop_precedence op prec;
|
||||
| _ -> ()
|
||||
end;
|
||||
|
||||
(* Create a new basic block to start insertion into. *)
|
||||
let bb = append_block context "entry" the_function in
|
||||
position_at_end bb builder;
|
||||
|
||||
try
|
||||
(* Add all arguments to the symbol table and create their allocas. *)
|
||||
create_argument_allocas the_function proto;
|
||||
|
||||
let ret_val = codegen_expr body in
|
||||
|
||||
(* Finish off the function. *)
|
||||
let _ = build_ret ret_val builder in
|
||||
|
||||
(* Validate the generated code, checking for consistency. *)
|
||||
Llvm_analysis.assert_valid_function the_function;
|
||||
|
||||
(* Optimize the function. *)
|
||||
let _ = PassManager.run_function the_function the_fpm in
|
||||
|
||||
the_function
|
||||
with e ->
|
||||
delete_function the_function;
|
||||
raise e
|
@ -1,60 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
let rec lex = parser
|
||||
(* Skip any whitespace. *)
|
||||
| [< ' (' ' | '\n' | '\r' | '\t'); stream >] -> lex stream
|
||||
|
||||
(* identifier: [a-zA-Z][a-zA-Z0-9] *)
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
|
||||
(* number: [0-9.]+ *)
|
||||
| [< ' ('0' .. '9' as c); stream >] ->
|
||||
let buffer = Buffer.create 1 in
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
|
||||
(* Comment until end of line. *)
|
||||
| [< ' ('#'); stream >] ->
|
||||
lex_comment stream
|
||||
|
||||
(* Otherwise, just return the character as its ascii value. *)
|
||||
| [< 'c; stream >] ->
|
||||
[< 'Token.Kwd c; lex stream >]
|
||||
|
||||
(* end of stream. *)
|
||||
| [< >] -> [< >]
|
||||
|
||||
and lex_number buffer = parser
|
||||
| [< ' ('0' .. '9' | '.' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_number buffer stream
|
||||
| [< stream=lex >] ->
|
||||
[< 'Token.Number (float_of_string (Buffer.contents buffer)); stream >]
|
||||
|
||||
and lex_ident buffer = parser
|
||||
| [< ' ('A' .. 'Z' | 'a' .. 'z' | '0' .. '9' as c); stream >] ->
|
||||
Buffer.add_char buffer c;
|
||||
lex_ident buffer stream
|
||||
| [< stream=lex >] ->
|
||||
match Buffer.contents buffer with
|
||||
| "def" -> [< 'Token.Def; stream >]
|
||||
| "extern" -> [< 'Token.Extern; stream >]
|
||||
| "if" -> [< 'Token.If; stream >]
|
||||
| "then" -> [< 'Token.Then; stream >]
|
||||
| "else" -> [< 'Token.Else; stream >]
|
||||
| "for" -> [< 'Token.For; stream >]
|
||||
| "in" -> [< 'Token.In; stream >]
|
||||
| "binary" -> [< 'Token.Binary; stream >]
|
||||
| "unary" -> [< 'Token.Unary; stream >]
|
||||
| "var" -> [< 'Token.Var; stream >]
|
||||
| id -> [< 'Token.Ident id; stream >]
|
||||
|
||||
and lex_comment = parser
|
||||
| [< ' ('\n'); stream=lex >] -> stream
|
||||
| [< 'c; e=lex_comment >] -> e
|
||||
| [< >] -> [< >]
|
@ -1,10 +0,0 @@
|
||||
open Ocamlbuild_plugin;;
|
||||
|
||||
ocaml_lib ~extern:true "llvm";;
|
||||
ocaml_lib ~extern:true "llvm_analysis";;
|
||||
ocaml_lib ~extern:true "llvm_executionengine";;
|
||||
ocaml_lib ~extern:true "llvm_target";;
|
||||
ocaml_lib ~extern:true "llvm_scalar_opts";;
|
||||
|
||||
flag ["link"; "ocaml"; "g++"] (S[A"-cc"; A"g++"; A"-cclib"; A"-rdynamic"]);;
|
||||
dep ["link"; "ocaml"; "use_bindings"] ["bindings.o"];;
|
@ -1,221 +0,0 @@
|
||||
(*===---------------------------------------------------------------------===
|
||||
* Parser
|
||||
*===---------------------------------------------------------------------===*)
|
||||
|
||||
(* binop_precedence - This holds the precedence for each binary operator that is
|
||||
* defined *)
|
||||
let binop_precedence:(char, int) Hashtbl.t = Hashtbl.create 10
|
||||
|
||||
(* precedence - Get the precedence of the pending binary operator token. *)
|
||||
let precedence c = try Hashtbl.find binop_precedence c with Not_found -> -1
|
||||
|
||||
(* primary
|
||||
* ::= identifier
|
||||
* ::= numberexpr
|
||||
* ::= parenexpr
|
||||
* ::= ifexpr
|
||||
* ::= forexpr
|
||||
* ::= varexpr *)
|
||||
let rec parse_primary = parser
|
||||
(* numberexpr ::= number *)
|
||||
| [< 'Token.Number n >] -> Ast.Number n
|
||||
|
||||
(* parenexpr ::= '(' expression ')' *)
|
||||
| [< 'Token.Kwd '('; e=parse_expr; 'Token.Kwd ')' ?? "expected ')'" >] -> e
|
||||
|
||||
(* identifierexpr
|
||||
* ::= identifier
|
||||
* ::= identifier '(' argumentexpr ')' *)
|
||||
| [< 'Token.Ident id; stream >] ->
|
||||
let rec parse_args accumulator = parser
|
||||
| [< e=parse_expr; stream >] ->
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; e=parse_args (e :: accumulator) >] -> e
|
||||
| [< >] -> e :: accumulator
|
||||
end stream
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let rec parse_ident id = parser
|
||||
(* Call. *)
|
||||
| [< 'Token.Kwd '(';
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')'">] ->
|
||||
Ast.Call (id, Array.of_list (List.rev args))
|
||||
|
||||
(* Simple variable ref. *)
|
||||
| [< >] -> Ast.Variable id
|
||||
in
|
||||
parse_ident id stream
|
||||
|
||||
(* ifexpr ::= 'if' expr 'then' expr 'else' expr *)
|
||||
| [< 'Token.If; c=parse_expr;
|
||||
'Token.Then ?? "expected 'then'"; t=parse_expr;
|
||||
'Token.Else ?? "expected 'else'"; e=parse_expr >] ->
|
||||
Ast.If (c, t, e)
|
||||
|
||||
(* forexpr
|
||||
::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression *)
|
||||
| [< 'Token.For;
|
||||
'Token.Ident id ?? "expected identifier after for";
|
||||
'Token.Kwd '=' ?? "expected '=' after for";
|
||||
stream >] ->
|
||||
begin parser
|
||||
| [<
|
||||
start=parse_expr;
|
||||
'Token.Kwd ',' ?? "expected ',' after for";
|
||||
end_=parse_expr;
|
||||
stream >] ->
|
||||
let step =
|
||||
begin parser
|
||||
| [< 'Token.Kwd ','; step=parse_expr >] -> Some step
|
||||
| [< >] -> None
|
||||
end stream
|
||||
in
|
||||
begin parser
|
||||
| [< 'Token.In; body=parse_expr >] ->
|
||||
Ast.For (id, start, end_, step, body)
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected 'in' after for")
|
||||
end stream
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected '=' after for")
|
||||
end stream
|
||||
|
||||
(* varexpr
|
||||
* ::= 'var' identifier ('=' expression?
|
||||
* (',' identifier ('=' expression)?)* 'in' expression *)
|
||||
| [< 'Token.Var;
|
||||
(* At least one variable name is required. *)
|
||||
'Token.Ident id ?? "expected identifier after var";
|
||||
init=parse_var_init;
|
||||
var_names=parse_var_names [(id, init)];
|
||||
(* At this point, we have to have 'in'. *)
|
||||
'Token.In ?? "expected 'in' keyword after 'var'";
|
||||
body=parse_expr >] ->
|
||||
Ast.Var (Array.of_list (List.rev var_names), body)
|
||||
|
||||
| [< >] -> raise (Stream.Error "unknown token when expecting an expression.")
|
||||
|
||||
(* unary
|
||||
* ::= primary
|
||||
* ::= '!' unary *)
|
||||
and parse_unary = parser
|
||||
(* If this is a unary operator, read it. *)
|
||||
| [< 'Token.Kwd op when op != '(' && op != ')'; operand=parse_expr >] ->
|
||||
Ast.Unary (op, operand)
|
||||
|
||||
(* If the current token is not an operator, it must be a primary expr. *)
|
||||
| [< stream >] -> parse_primary stream
|
||||
|
||||
(* binoprhs
|
||||
* ::= ('+' primary)* *)
|
||||
and parse_bin_rhs expr_prec lhs stream =
|
||||
match Stream.peek stream with
|
||||
(* If this is a binop, find its precedence. *)
|
||||
| Some (Token.Kwd c) when Hashtbl.mem binop_precedence c ->
|
||||
let token_prec = precedence c in
|
||||
|
||||
(* If this is a binop that binds at least as tightly as the current binop,
|
||||
* consume it, otherwise we are done. *)
|
||||
if token_prec < expr_prec then lhs else begin
|
||||
(* Eat the binop. *)
|
||||
Stream.junk stream;
|
||||
|
||||
(* Parse the primary expression after the binary operator. *)
|
||||
let rhs = parse_unary stream in
|
||||
|
||||
(* Okay, we know this is a binop. *)
|
||||
let rhs =
|
||||
match Stream.peek stream with
|
||||
| Some (Token.Kwd c2) ->
|
||||
(* If BinOp binds less tightly with rhs than the operator after
|
||||
* rhs, let the pending operator take rhs as its lhs. *)
|
||||
let next_prec = precedence c2 in
|
||||
if token_prec < next_prec
|
||||
then parse_bin_rhs (token_prec + 1) rhs stream
|
||||
else rhs
|
||||
| _ -> rhs
|
||||
in
|
||||
|
||||
(* Merge lhs/rhs. *)
|
||||
let lhs = Ast.Binary (c, lhs, rhs) in
|
||||
parse_bin_rhs expr_prec lhs stream
|
||||
end
|
||||
| _ -> lhs
|
||||
|
||||
and parse_var_init = parser
|
||||
(* read in the optional initializer. *)
|
||||
| [< 'Token.Kwd '='; e=parse_expr >] -> Some e
|
||||
| [< >] -> None
|
||||
|
||||
and parse_var_names accumulator = parser
|
||||
| [< 'Token.Kwd ',';
|
||||
'Token.Ident id ?? "expected identifier list after var";
|
||||
init=parse_var_init;
|
||||
e=parse_var_names ((id, init) :: accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
|
||||
(* expression
|
||||
* ::= primary binoprhs *)
|
||||
and parse_expr = parser
|
||||
| [< lhs=parse_unary; stream >] -> parse_bin_rhs 0 lhs stream
|
||||
|
||||
(* prototype
|
||||
* ::= id '(' id* ')'
|
||||
* ::= binary LETTER number? (id, id)
|
||||
* ::= unary LETTER number? (id) *)
|
||||
let parse_prototype =
|
||||
let rec parse_args accumulator = parser
|
||||
| [< 'Token.Ident id; e=parse_args (id::accumulator) >] -> e
|
||||
| [< >] -> accumulator
|
||||
in
|
||||
let parse_operator = parser
|
||||
| [< 'Token.Unary >] -> "unary", 1
|
||||
| [< 'Token.Binary >] -> "binary", 2
|
||||
in
|
||||
let parse_binary_precedence = parser
|
||||
| [< 'Token.Number n >] -> int_of_float n
|
||||
| [< >] -> 30
|
||||
in
|
||||
parser
|
||||
| [< 'Token.Ident id;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
(* success. *)
|
||||
Ast.Prototype (id, Array.of_list (List.rev args))
|
||||
| [< (prefix, kind)=parse_operator;
|
||||
'Token.Kwd op ?? "expected an operator";
|
||||
(* Read the precedence if present. *)
|
||||
binary_precedence=parse_binary_precedence;
|
||||
'Token.Kwd '(' ?? "expected '(' in prototype";
|
||||
args=parse_args [];
|
||||
'Token.Kwd ')' ?? "expected ')' in prototype" >] ->
|
||||
let name = prefix ^ (String.make 1 op) in
|
||||
let args = Array.of_list (List.rev args) in
|
||||
|
||||
(* Verify right number of arguments for operator. *)
|
||||
if Array.length args != kind
|
||||
then raise (Stream.Error "invalid number of operands for operator")
|
||||
else
|
||||
if kind == 1 then
|
||||
Ast.Prototype (name, args)
|
||||
else
|
||||
Ast.BinOpPrototype (name, args, binary_precedence)
|
||||
| [< >] ->
|
||||
raise (Stream.Error "expected function name in prototype")
|
||||
|
||||
(* definition ::= 'def' prototype expression *)
|
||||
let parse_definition = parser
|
||||
| [< 'Token.Def; p=parse_prototype; e=parse_expr >] ->
|
||||
Ast.Function (p, e)
|
||||
|
||||
(* toplevelexpr ::= expression *)
|
||||
let parse_toplevel = parser
|
||||
| [< e=parse_expr >] ->
|
||||
(* Make an anonymous proto. *)
|
||||
Ast.Function (Ast.Prototype ("", [||]), e)
|
||||
|
||||
(* external ::= 'extern' prototype *)
|
||||
let parse_extern = parser
|
||||
| [< 'Token.Extern; e=parse_prototype >] -> e
|
@ -1,25 +0,0 @@
|
||||
(*===----------------------------------------------------------------------===
|
||||
* Lexer Tokens
|
||||
*===----------------------------------------------------------------------===*)
|
||||
|
||||
(* The lexer returns these 'Kwd' if it is an unknown character, otherwise one of
|
||||
* these others for known things. *)
|
||||
type token =
|
||||
(* commands *)
|
||||
| Def | Extern
|
||||
|
||||
(* primary *)
|
||||
| Ident of string | Number of float
|
||||
|
||||
(* unknown *)
|
||||
| Kwd of char
|
||||
|
||||
(* control *)
|
||||
| If | Then | Else
|
||||
| For | In
|
||||
|
||||
(* operators *)
|
||||
| Binary | Unary
|
||||
|
||||
(* var definition *)
|
||||
| Var
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user