Fix KS tutorial build failure.

make all doesn't build the examples and it was uniquified since
last build.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@223675 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Eric Christopher 2014-12-08 18:12:28 +00:00
parent dcc44c64c1
commit 6efccd025c
5 changed files with 1059 additions and 775 deletions

View File

@ -28,10 +28,12 @@ enum Token {
tok_eof = -1,
// commands
tok_def = -2, tok_extern = -3,
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4, tok_number = -5
tok_identifier = -4,
tok_number = -5
};
static std::string IdentifierStr; // Filled in if tok_identifier
@ -50,8 +52,10 @@ static int gettok() {
while (isalnum((LastChar = getchar())))
IdentifierStr += LastChar;
if (IdentifierStr == "def") return tok_def;
if (IdentifierStr == "extern") return tok_extern;
if (IdentifierStr == "def")
return tok_def;
if (IdentifierStr == "extern")
return tok_extern;
return tok_identifier;
}
@ -68,7 +72,8 @@ static int gettok() {
if (LastChar == '#') {
// Comment until end of line.
do LastChar = getchar();
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
@ -99,6 +104,7 @@ public:
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double val) : Val(val) {}
virtual Value *Codegen();
@ -107,6 +113,7 @@ public:
/// 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();
@ -116,6 +123,7 @@ public:
class BinaryExprAST : public ExprAST {
char Op;
ExprAST *LHS, *RHS;
public:
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
: Op(op), LHS(lhs), RHS(rhs) {}
@ -125,9 +133,10 @@ public:
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
public:
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
: Callee(callee), Args(args) {}
virtual Value *Codegen();
};
@ -138,6 +147,7 @@ public:
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) {}
@ -149,9 +159,9 @@ public:
class FunctionAST {
PrototypeAST *Proto;
ExprAST *Body;
public:
FunctionAST(PrototypeAST *proto, ExprAST *body)
: Proto(proto), Body(body) {}
FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
Function *Codegen();
};
@ -165,9 +175,7 @@ public:
/// 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();
}
static int getNextToken() { return CurTok = gettok(); }
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
@ -180,14 +188,24 @@ static int GetTokPrecedence() {
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
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; }
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();
@ -204,14 +222,16 @@ static ExprAST *ParseIdentifierExpr() {
// Call.
getNextToken(); // eat (
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
if (CurTok != ')') {
while (1) {
ExprAST *Arg = ParseExpression();
if (!Arg) return 0;
if (!Arg)
return 0;
Args.push_back(Arg);
if (CurTok == ')') break;
if (CurTok == ')')
break;
if (CurTok != ',')
return Error("Expected ')' or ',' in argument list");
@ -236,7 +256,8 @@ static ExprAST *ParseNumberExpr() {
static ExprAST *ParseParenExpr() {
getNextToken(); // eat (.
ExprAST *V = ParseExpression();
if (!V) return 0;
if (!V)
return 0;
if (CurTok != ')')
return Error("expected ')'");
@ -250,10 +271,14 @@ static ExprAST *ParseParenExpr() {
/// ::= 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();
default:
return Error("unknown token when expecting an expression");
case tok_identifier:
return ParseIdentifierExpr();
case tok_number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
}
}
@ -275,14 +300,16 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
// Parse the primary expression after the binary operator.
ExprAST *RHS = ParsePrimary();
if (!RHS) return 0;
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;
RHS = ParseBinOpRHS(TokPrec + 1, RHS);
if (RHS == 0)
return 0;
}
// Merge LHS/RHS.
@ -295,7 +322,8 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
///
static ExprAST *ParseExpression() {
ExprAST *LHS = ParsePrimary();
if (!LHS) return 0;
if (!LHS)
return 0;
return ParseBinOpRHS(0, LHS);
}
@ -328,7 +356,8 @@ static PrototypeAST *ParsePrototype() {
static FunctionAST *ParseDefinition() {
getNextToken(); // eat def.
PrototypeAST *Proto = ParsePrototype();
if (Proto == 0) return 0;
if (Proto == 0)
return 0;
if (ExprAST *E = ParseExpression())
return new FunctionAST(Proto, E);
@ -357,10 +386,13 @@ static PrototypeAST *ParseExtern() {
static Module *TheModule;
static IRBuilder<> Builder(getGlobalContext());
static std::map<std::string, Value*> NamedValues;
static std::map<std::string, Value *> NamedValues;
static FunctionPassManager *TheFPM;
Value *ErrorV(const char *Str) { Error(Str); return 0; }
Value *ErrorV(const char *Str) {
Error(Str);
return 0;
}
Value *NumberExprAST::Codegen() {
return ConstantFP::get(getGlobalContext(), APFloat(Val));
@ -375,18 +407,23 @@ Value *VariableExprAST::Codegen() {
Value *BinaryExprAST::Codegen() {
Value *L = LHS->Codegen();
Value *R = RHS->Codegen();
if (L == 0 || R == 0) return 0;
if (L == 0 || R == 0)
return 0;
switch (Op) {
case '+': return Builder.CreateFAdd(L, R, "addtmp");
case '-': return Builder.CreateFSub(L, R, "subtmp");
case '*': return Builder.CreateFMul(L, R, "multmp");
case '+':
return Builder.CreateFAdd(L, R, "addtmp");
case '-':
return Builder.CreateFSub(L, R, "subtmp");
case '*':
return Builder.CreateFMul(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");
default:
return ErrorV("invalid binary operator");
}
}
@ -400,10 +437,11 @@ Value *CallExprAST::Codegen() {
if (CalleeF->arg_size() != Args.size())
return ErrorV("Incorrect # arguments passed");
std::vector<Value*> ArgsV;
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;
if (ArgsV.back() == 0)
return 0;
}
return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
@ -411,12 +449,13 @@ Value *CallExprAST::Codegen() {
Function *PrototypeAST::Codegen() {
// Make the function type: double(double,double) etc.
std::vector<Type*> Doubles(Args.size(),
std::vector<Type *> Doubles(Args.size(),
Type::getDoubleTy(getGlobalContext()));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
Doubles, false);
FunctionType *FT =
FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
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.
@ -534,11 +573,20 @@ 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;
case tok_eof:
return;
case ';':
getNextToken();
break; // ignore top-level semicolons.
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
@ -548,8 +596,7 @@ static void MainLoop() {
//===----------------------------------------------------------------------===//
/// putchard - putchar that takes a double and returns 0.
extern "C"
double putchard(double X) {
extern "C" double putchard(double X) {
putchar((char)X);
return 0;
}
@ -581,9 +628,10 @@ int main() {
// Create the JIT. This takes ownership of the module.
std::string ErrStr;
TheExecutionEngine = EngineBuilder(std::move(Owner))
TheExecutionEngine =
EngineBuilder(std::move(Owner))
.setErrorStr(&ErrStr)
.setMCJITMemoryManager(new SectionMemoryManager())
.setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
.create();
if (!TheExecutionEngine) {
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());

View File

@ -28,14 +28,19 @@ enum Token {
tok_eof = -1,
// commands
tok_def = -2, tok_extern = -3,
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4, tok_number = -5,
tok_identifier = -4,
tok_number = -5,
// control
tok_if = -6, tok_then = -7, tok_else = -8,
tok_for = -9, tok_in = -10
tok_if = -6,
tok_then = -7,
tok_else = -8,
tok_for = -9,
tok_in = -10
};
static std::string IdentifierStr; // Filled in if tok_identifier
@ -54,13 +59,20 @@ static int gettok() {
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 == "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;
}
@ -77,7 +89,8 @@ static int gettok() {
if (LastChar == '#') {
// Comment until end of line.
do LastChar = getchar();
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
@ -108,6 +121,7 @@ public:
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double val) : Val(val) {}
virtual Value *Codegen();
@ -116,6 +130,7 @@ public:
/// 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();
@ -125,6 +140,7 @@ public:
class BinaryExprAST : public ExprAST {
char Op;
ExprAST *LHS, *RHS;
public:
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
: Op(op), LHS(lhs), RHS(rhs) {}
@ -134,9 +150,10 @@ public:
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
public:
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
: Callee(callee), Args(args) {}
virtual Value *Codegen();
};
@ -144,6 +161,7 @@ public:
/// 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) {}
@ -154,6 +172,7 @@ public:
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)
@ -167,6 +186,7 @@ public:
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) {}
@ -178,9 +198,9 @@ public:
class FunctionAST {
PrototypeAST *Proto;
ExprAST *Body;
public:
FunctionAST(PrototypeAST *proto, ExprAST *body)
: Proto(proto), Body(body) {}
FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
Function *Codegen();
};
@ -194,9 +214,7 @@ public:
/// 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();
}
static int getNextToken() { return CurTok = gettok(); }
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
@ -209,14 +227,24 @@ static int GetTokPrecedence() {
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
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; }
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();
@ -233,14 +261,16 @@ static ExprAST *ParseIdentifierExpr() {
// Call.
getNextToken(); // eat (
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
if (CurTok != ')') {
while (1) {
ExprAST *Arg = ParseExpression();
if (!Arg) return 0;
if (!Arg)
return 0;
Args.push_back(Arg);
if (CurTok == ')') break;
if (CurTok == ')')
break;
if (CurTok != ',')
return Error("Expected ')' or ',' in argument list");
@ -265,7 +295,8 @@ static ExprAST *ParseNumberExpr() {
static ExprAST *ParseParenExpr() {
getNextToken(); // eat (.
ExprAST *V = ParseExpression();
if (!V) return 0;
if (!V)
return 0;
if (CurTok != ')')
return Error("expected ')'");
@ -279,14 +310,16 @@ static ExprAST *ParseIfExpr() {
// condition.
ExprAST *Cond = ParseExpression();
if (!Cond) return 0;
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 (Then == 0)
return 0;
if (CurTok != tok_else)
return Error("expected else");
@ -294,7 +327,8 @@ static ExprAST *ParseIfExpr() {
getNextToken();
ExprAST *Else = ParseExpression();
if (!Else) return 0;
if (!Else)
return 0;
return new IfExprAST(Cond, Then, Else);
}
@ -313,22 +347,24 @@ static ExprAST *ParseForExpr() {
return Error("expected '=' after for");
getNextToken(); // eat '='.
ExprAST *Start = ParseExpression();
if (Start == 0) return 0;
if (Start == 0)
return 0;
if (CurTok != ',')
return Error("expected ',' after for start value");
getNextToken();
ExprAST *End = ParseExpression();
if (End == 0) return 0;
if (End == 0)
return 0;
// The step value is optional.
ExprAST *Step = 0;
if (CurTok == ',') {
getNextToken();
Step = ParseExpression();
if (Step == 0) return 0;
if (Step == 0)
return 0;
}
if (CurTok != tok_in)
@ -336,7 +372,8 @@ static ExprAST *ParseForExpr() {
getNextToken(); // eat 'in'.
ExprAST *Body = ParseExpression();
if (Body == 0) return 0;
if (Body == 0)
return 0;
return new ForExprAST(IdName, Start, End, Step, Body);
}
@ -349,12 +386,18 @@ static ExprAST *ParseForExpr() {
/// ::= 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();
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();
}
}
@ -376,14 +419,16 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
// Parse the primary expression after the binary operator.
ExprAST *RHS = ParsePrimary();
if (!RHS) return 0;
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;
RHS = ParseBinOpRHS(TokPrec + 1, RHS);
if (RHS == 0)
return 0;
}
// Merge LHS/RHS.
@ -396,7 +441,8 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
///
static ExprAST *ParseExpression() {
ExprAST *LHS = ParsePrimary();
if (!LHS) return 0;
if (!LHS)
return 0;
return ParseBinOpRHS(0, LHS);
}
@ -429,7 +475,8 @@ static PrototypeAST *ParsePrototype() {
static FunctionAST *ParseDefinition() {
getNextToken(); // eat def.
PrototypeAST *Proto = ParsePrototype();
if (Proto == 0) return 0;
if (Proto == 0)
return 0;
if (ExprAST *E = ParseExpression())
return new FunctionAST(Proto, E);
@ -458,10 +505,13 @@ static PrototypeAST *ParseExtern() {
static Module *TheModule;
static IRBuilder<> Builder(getGlobalContext());
static std::map<std::string, Value*> NamedValues;
static std::map<std::string, Value *> NamedValues;
static FunctionPassManager *TheFPM;
Value *ErrorV(const char *Str) { Error(Str); return 0; }
Value *ErrorV(const char *Str) {
Error(Str);
return 0;
}
Value *NumberExprAST::Codegen() {
return ConstantFP::get(getGlobalContext(), APFloat(Val));
@ -476,18 +526,23 @@ Value *VariableExprAST::Codegen() {
Value *BinaryExprAST::Codegen() {
Value *L = LHS->Codegen();
Value *R = RHS->Codegen();
if (L == 0 || R == 0) return 0;
if (L == 0 || R == 0)
return 0;
switch (Op) {
case '+': return Builder.CreateFAdd(L, R, "addtmp");
case '-': return Builder.CreateFSub(L, R, "subtmp");
case '*': return Builder.CreateFMul(L, R, "multmp");
case '+':
return Builder.CreateFAdd(L, R, "addtmp");
case '-':
return Builder.CreateFSub(L, R, "subtmp");
case '*':
return Builder.CreateFMul(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");
default:
return ErrorV("invalid binary operator");
}
}
@ -501,10 +556,11 @@ Value *CallExprAST::Codegen() {
if (CalleeF->arg_size() != Args.size())
return ErrorV("Incorrect # arguments passed");
std::vector<Value*> ArgsV;
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;
if (ArgsV.back() == 0)
return 0;
}
return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
@ -512,18 +568,19 @@ Value *CallExprAST::Codegen() {
Value *IfExprAST::Codegen() {
Value *CondV = Cond->Codegen();
if (CondV == 0) return 0;
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");
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 *ThenBB =
BasicBlock::Create(getGlobalContext(), "then", TheFunction);
BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
@ -533,7 +590,8 @@ Value *IfExprAST::Codegen() {
Builder.SetInsertPoint(ThenBB);
Value *ThenV = Then->Codegen();
if (ThenV == 0) return 0;
if (ThenV == 0)
return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
@ -544,7 +602,8 @@ Value *IfExprAST::Codegen() {
Builder.SetInsertPoint(ElseBB);
Value *ElseV = Else->Codegen();
if (ElseV == 0) return 0;
if (ElseV == 0)
return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
@ -553,8 +612,8 @@ Value *IfExprAST::Codegen() {
// Emit merge block.
TheFunction->getBasicBlockList().push_back(MergeBB);
Builder.SetInsertPoint(MergeBB);
PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
"iftmp");
PHINode *PN =
Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
PN->addIncoming(ThenV, ThenBB);
PN->addIncoming(ElseV, ElseBB);
@ -580,13 +639,15 @@ Value *ForExprAST::Codegen() {
// Emit the start code first, without 'variable' in scope.
Value *StartVal = Start->Codegen();
if (StartVal == 0) return 0;
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);
BasicBlock *LoopBB =
BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
Builder.CreateBr(LoopBB);
@ -595,7 +656,8 @@ Value *ForExprAST::Codegen() {
Builder.SetInsertPoint(LoopBB);
// Start the PHI node with an entry for Start.
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
2, VarName.c_str());
Variable->addIncoming(StartVal, PreheaderBB);
// Within the loop, the variable is defined equal to the PHI node. If it
@ -613,7 +675,8 @@ Value *ForExprAST::Codegen() {
Value *StepVal;
if (Step) {
StepVal = Step->Codegen();
if (StepVal == 0) return 0;
if (StepVal == 0)
return 0;
} else {
// If not specified, use 1.0.
StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
@ -623,16 +686,17 @@ Value *ForExprAST::Codegen() {
// Compute the end condition.
Value *EndCond = End->Codegen();
if (EndCond == 0) return EndCond;
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");
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);
BasicBlock *AfterBB =
BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@ -649,19 +713,19 @@ Value *ForExprAST::Codegen() {
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<Type*> Doubles(Args.size(),
std::vector<Type *> Doubles(Args.size(),
Type::getDoubleTy(getGlobalContext()));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
Doubles, false);
FunctionType *FT =
FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
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.
@ -779,11 +843,20 @@ 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;
case tok_eof:
return;
case ';':
getNextToken();
break; // ignore top-level semicolons.
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
@ -793,8 +866,7 @@ static void MainLoop() {
//===----------------------------------------------------------------------===//
/// putchard - putchar that takes a double and returns 0.
extern "C"
double putchard(double X) {
extern "C" double putchard(double X) {
putchar((char)X);
return 0;
}
@ -826,9 +898,10 @@ int main() {
// Create the JIT. This takes ownership of the module.
std::string ErrStr;
TheExecutionEngine = EngineBuilder(std::move(Owner))
TheExecutionEngine =
EngineBuilder(std::move(Owner))
.setErrorStr(&ErrStr)
.setMCJITMemoryManager(new SectionMemoryManager())
.setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
.create();
if (!TheExecutionEngine) {
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());

View File

@ -28,17 +28,23 @@ enum Token {
tok_eof = -1,
// commands
tok_def = -2, tok_extern = -3,
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4, tok_number = -5,
tok_identifier = -4,
tok_number = -5,
// control
tok_if = -6, tok_then = -7, tok_else = -8,
tok_for = -9, tok_in = -10,
tok_if = -6,
tok_then = -7,
tok_else = -8,
tok_for = -9,
tok_in = -10,
// operators
tok_binary = -11, tok_unary = -12
tok_binary = -11,
tok_unary = -12
};
static std::string IdentifierStr; // Filled in if tok_identifier
@ -57,15 +63,24 @@ static int gettok() {
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;
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;
}
@ -82,7 +97,8 @@ static int gettok() {
if (LastChar == '#') {
// Comment until end of line.
do LastChar = getchar();
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
@ -113,6 +129,7 @@ public:
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double val) : Val(val) {}
virtual Value *Codegen();
@ -121,6 +138,7 @@ public:
/// 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();
@ -130,6 +148,7 @@ public:
class UnaryExprAST : public ExprAST {
char Opcode;
ExprAST *Operand;
public:
UnaryExprAST(char opcode, ExprAST *operand)
: Opcode(opcode), Operand(operand) {}
@ -140,6 +159,7 @@ public:
class BinaryExprAST : public ExprAST {
char Op;
ExprAST *LHS, *RHS;
public:
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
: Op(op), LHS(lhs), RHS(rhs) {}
@ -149,9 +169,10 @@ public:
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
public:
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
: Callee(callee), Args(args) {}
virtual Value *Codegen();
};
@ -159,6 +180,7 @@ public:
/// 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) {}
@ -169,6 +191,7 @@ public:
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)
@ -194,7 +217,7 @@ public:
char getOperatorName() const {
assert(isUnaryOp() || isBinaryOp());
return Name[Name.size()-1];
return Name[Name.size() - 1];
}
unsigned getBinaryPrecedence() const { return Precedence; }
@ -206,9 +229,9 @@ public:
class FunctionAST {
PrototypeAST *Proto;
ExprAST *Body;
public:
FunctionAST(PrototypeAST *proto, ExprAST *body)
: Proto(proto), Body(body) {}
FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
Function *Codegen();
};
@ -222,9 +245,7 @@ public:
/// 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();
}
static int getNextToken() { return CurTok = gettok(); }
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
@ -237,14 +258,24 @@ static int GetTokPrecedence() {
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
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; }
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();
@ -261,14 +292,16 @@ static ExprAST *ParseIdentifierExpr() {
// Call.
getNextToken(); // eat (
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
if (CurTok != ')') {
while (1) {
ExprAST *Arg = ParseExpression();
if (!Arg) return 0;
if (!Arg)
return 0;
Args.push_back(Arg);
if (CurTok == ')') break;
if (CurTok == ')')
break;
if (CurTok != ',')
return Error("Expected ')' or ',' in argument list");
@ -293,7 +326,8 @@ static ExprAST *ParseNumberExpr() {
static ExprAST *ParseParenExpr() {
getNextToken(); // eat (.
ExprAST *V = ParseExpression();
if (!V) return 0;
if (!V)
return 0;
if (CurTok != ')')
return Error("expected ')'");
@ -307,14 +341,16 @@ static ExprAST *ParseIfExpr() {
// condition.
ExprAST *Cond = ParseExpression();
if (!Cond) return 0;
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 (Then == 0)
return 0;
if (CurTok != tok_else)
return Error("expected else");
@ -322,7 +358,8 @@ static ExprAST *ParseIfExpr() {
getNextToken();
ExprAST *Else = ParseExpression();
if (!Else) return 0;
if (!Else)
return 0;
return new IfExprAST(Cond, Then, Else);
}
@ -341,22 +378,24 @@ static ExprAST *ParseForExpr() {
return Error("expected '=' after for");
getNextToken(); // eat '='.
ExprAST *Start = ParseExpression();
if (Start == 0) return 0;
if (Start == 0)
return 0;
if (CurTok != ',')
return Error("expected ',' after for start value");
getNextToken();
ExprAST *End = ParseExpression();
if (End == 0) return 0;
if (End == 0)
return 0;
// The step value is optional.
ExprAST *Step = 0;
if (CurTok == ',') {
getNextToken();
Step = ParseExpression();
if (Step == 0) return 0;
if (Step == 0)
return 0;
}
if (CurTok != tok_in)
@ -364,7 +403,8 @@ static ExprAST *ParseForExpr() {
getNextToken(); // eat 'in'.
ExprAST *Body = ParseExpression();
if (Body == 0) return 0;
if (Body == 0)
return 0;
return new ForExprAST(IdName, Start, End, Step, Body);
}
@ -377,12 +417,18 @@ static ExprAST *ParseForExpr() {
/// ::= 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();
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();
}
}
@ -420,14 +466,16 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
// Parse the unary expression after the binary operator.
ExprAST *RHS = ParseUnary();
if (!RHS) return 0;
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;
RHS = ParseBinOpRHS(TokPrec + 1, RHS);
if (RHS == 0)
return 0;
}
// Merge LHS/RHS.
@ -440,7 +488,8 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
///
static ExprAST *ParseExpression() {
ExprAST *LHS = ParseUnary();
if (!LHS) return 0;
if (!LHS)
return 0;
return ParseBinOpRHS(0, LHS);
}
@ -514,7 +563,8 @@ static PrototypeAST *ParsePrototype() {
static FunctionAST *ParseDefinition() {
getNextToken(); // eat def.
PrototypeAST *Proto = ParsePrototype();
if (Proto == 0) return 0;
if (Proto == 0)
return 0;
if (ExprAST *E = ParseExpression())
return new FunctionAST(Proto, E);
@ -543,10 +593,13 @@ static PrototypeAST *ParseExtern() {
static Module *TheModule;
static IRBuilder<> Builder(getGlobalContext());
static std::map<std::string, Value*> NamedValues;
static std::map<std::string, Value *> NamedValues;
static FunctionPassManager *TheFPM;
Value *ErrorV(const char *Str) { Error(Str); return 0; }
Value *ErrorV(const char *Str) {
Error(Str);
return 0;
}
Value *NumberExprAST::Codegen() {
return ConstantFP::get(getGlobalContext(), APFloat(Val));
@ -560,9 +613,10 @@ Value *VariableExprAST::Codegen() {
Value *UnaryExprAST::Codegen() {
Value *OperandV = Operand->Codegen();
if (OperandV == 0) return 0;
if (OperandV == 0)
return 0;
Function *F = TheModule->getFunction(std::string("unary")+Opcode);
Function *F = TheModule->getFunction(std::string("unary") + Opcode);
if (F == 0)
return ErrorV("Unknown unary operator");
@ -572,23 +626,28 @@ Value *UnaryExprAST::Codegen() {
Value *BinaryExprAST::Codegen() {
Value *L = LHS->Codegen();
Value *R = RHS->Codegen();
if (L == 0 || R == 0) return 0;
if (L == 0 || R == 0)
return 0;
switch (Op) {
case '+': return Builder.CreateFAdd(L, R, "addtmp");
case '-': return Builder.CreateFSub(L, R, "subtmp");
case '*': return Builder.CreateFMul(L, R, "multmp");
case '+':
return Builder.CreateFAdd(L, R, "addtmp");
case '-':
return Builder.CreateFSub(L, R, "subtmp");
case '*':
return Builder.CreateFMul(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;
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);
Function *F = TheModule->getFunction(std::string("binary") + Op);
assert(F && "binary operator not found!");
Value *Ops[] = { L, R };
@ -605,10 +664,11 @@ Value *CallExprAST::Codegen() {
if (CalleeF->arg_size() != Args.size())
return ErrorV("Incorrect # arguments passed");
std::vector<Value*> ArgsV;
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;
if (ArgsV.back() == 0)
return 0;
}
return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
@ -616,18 +676,19 @@ Value *CallExprAST::Codegen() {
Value *IfExprAST::Codegen() {
Value *CondV = Cond->Codegen();
if (CondV == 0) return 0;
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");
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 *ThenBB =
BasicBlock::Create(getGlobalContext(), "then", TheFunction);
BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
@ -637,7 +698,8 @@ Value *IfExprAST::Codegen() {
Builder.SetInsertPoint(ThenBB);
Value *ThenV = Then->Codegen();
if (ThenV == 0) return 0;
if (ThenV == 0)
return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
@ -648,7 +710,8 @@ Value *IfExprAST::Codegen() {
Builder.SetInsertPoint(ElseBB);
Value *ElseV = Else->Codegen();
if (ElseV == 0) return 0;
if (ElseV == 0)
return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
@ -657,8 +720,8 @@ Value *IfExprAST::Codegen() {
// Emit merge block.
TheFunction->getBasicBlockList().push_back(MergeBB);
Builder.SetInsertPoint(MergeBB);
PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
"iftmp");
PHINode *PN =
Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
PN->addIncoming(ThenV, ThenBB);
PN->addIncoming(ElseV, ElseBB);
@ -684,13 +747,15 @@ Value *ForExprAST::Codegen() {
// Emit the start code first, without 'variable' in scope.
Value *StartVal = Start->Codegen();
if (StartVal == 0) return 0;
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);
BasicBlock *LoopBB =
BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
Builder.CreateBr(LoopBB);
@ -699,7 +764,8 @@ Value *ForExprAST::Codegen() {
Builder.SetInsertPoint(LoopBB);
// Start the PHI node with an entry for Start.
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
2, VarName.c_str());
Variable->addIncoming(StartVal, PreheaderBB);
// Within the loop, the variable is defined equal to the PHI node. If it
@ -717,7 +783,8 @@ Value *ForExprAST::Codegen() {
Value *StepVal;
if (Step) {
StepVal = Step->Codegen();
if (StepVal == 0) return 0;
if (StepVal == 0)
return 0;
} else {
// If not specified, use 1.0.
StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
@ -727,16 +794,17 @@ Value *ForExprAST::Codegen() {
// Compute the end condition.
Value *EndCond = End->Codegen();
if (EndCond == 0) return EndCond;
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");
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);
BasicBlock *AfterBB =
BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@ -753,19 +821,19 @@ Value *ForExprAST::Codegen() {
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<Type*> Doubles(Args.size(),
std::vector<Type *> Doubles(Args.size(),
Type::getDoubleTy(getGlobalContext()));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
Doubles, false);
FunctionType *FT =
FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
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.
@ -890,11 +958,20 @@ 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;
case tok_eof:
return;
case ';':
getNextToken();
break; // ignore top-level semicolons.
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
@ -904,15 +981,13 @@ static void MainLoop() {
//===----------------------------------------------------------------------===//
/// putchard - putchar that takes a double and returns 0.
extern "C"
double putchard(double X) {
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) {
extern "C" double printd(double X) {
printf("%f\n", X);
return 0;
}
@ -944,9 +1019,10 @@ int main() {
// Create the JIT. This takes ownership of the module.
std::string ErrStr;
TheExecutionEngine = EngineBuilder(std::move(Owner))
TheExecutionEngine =
EngineBuilder(std::move(Owner))
.setErrorStr(&ErrStr)
.setMCJITMemoryManager(new SectionMemoryManager())
.setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
.create();
if (!TheExecutionEngine) {
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());

View File

@ -28,17 +28,23 @@ enum Token {
tok_eof = -1,
// commands
tok_def = -2, tok_extern = -3,
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4, tok_number = -5,
tok_identifier = -4,
tok_number = -5,
// control
tok_if = -6, tok_then = -7, tok_else = -8,
tok_for = -9, tok_in = -10,
tok_if = -6,
tok_then = -7,
tok_else = -8,
tok_for = -9,
tok_in = -10,
// operators
tok_binary = -11, tok_unary = -12,
tok_binary = -11,
tok_unary = -12,
// var definition
tok_var = -13
@ -60,16 +66,26 @@ static int gettok() {
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;
if (IdentifierStr == "var") return tok_var;
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;
if (IdentifierStr == "var")
return tok_var;
return tok_identifier;
}
@ -86,7 +102,8 @@ static int gettok() {
if (LastChar == '#') {
// Comment until end of line.
do LastChar = getchar();
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
@ -117,6 +134,7 @@ public:
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double val) : Val(val) {}
virtual Value *Codegen();
@ -125,6 +143,7 @@ public:
/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
std::string Name;
public:
VariableExprAST(const std::string &name) : Name(name) {}
const std::string &getName() const { return Name; }
@ -135,6 +154,7 @@ public:
class UnaryExprAST : public ExprAST {
char Opcode;
ExprAST *Operand;
public:
UnaryExprAST(char opcode, ExprAST *operand)
: Opcode(opcode), Operand(operand) {}
@ -145,6 +165,7 @@ public:
class BinaryExprAST : public ExprAST {
char Op;
ExprAST *LHS, *RHS;
public:
BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
: Op(op), LHS(lhs), RHS(rhs) {}
@ -154,9 +175,10 @@ public:
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
public:
CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
: Callee(callee), Args(args) {}
virtual Value *Codegen();
};
@ -164,6 +186,7 @@ public:
/// 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) {}
@ -174,6 +197,7 @@ public:
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)
@ -183,10 +207,11 @@ public:
/// VarExprAST - Expression class for var/in
class VarExprAST : public ExprAST {
std::vector<std::pair<std::string, ExprAST*> > VarNames;
std::vector<std::pair<std::string, ExprAST *> > VarNames;
ExprAST *Body;
public:
VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
ExprAST *body)
: VarNames(varnames), Body(body) {}
@ -210,7 +235,7 @@ public:
char getOperatorName() const {
assert(isUnaryOp() || isBinaryOp());
return Name[Name.size()-1];
return Name[Name.size() - 1];
}
unsigned getBinaryPrecedence() const { return Precedence; }
@ -224,9 +249,9 @@ public:
class FunctionAST {
PrototypeAST *Proto;
ExprAST *Body;
public:
FunctionAST(PrototypeAST *proto, ExprAST *body)
: Proto(proto), Body(body) {}
FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
Function *Codegen();
};
@ -240,9 +265,7 @@ public:
/// 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();
}
static int getNextToken() { return CurTok = gettok(); }
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
@ -255,14 +278,24 @@ static int GetTokPrecedence() {
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
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; }
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();
@ -279,14 +312,16 @@ static ExprAST *ParseIdentifierExpr() {
// Call.
getNextToken(); // eat (
std::vector<ExprAST*> Args;
std::vector<ExprAST *> Args;
if (CurTok != ')') {
while (1) {
ExprAST *Arg = ParseExpression();
if (!Arg) return 0;
if (!Arg)
return 0;
Args.push_back(Arg);
if (CurTok == ')') break;
if (CurTok == ')')
break;
if (CurTok != ',')
return Error("Expected ')' or ',' in argument list");
@ -311,7 +346,8 @@ static ExprAST *ParseNumberExpr() {
static ExprAST *ParseParenExpr() {
getNextToken(); // eat (.
ExprAST *V = ParseExpression();
if (!V) return 0;
if (!V)
return 0;
if (CurTok != ')')
return Error("expected ')'");
@ -325,14 +361,16 @@ static ExprAST *ParseIfExpr() {
// condition.
ExprAST *Cond = ParseExpression();
if (!Cond) return 0;
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 (Then == 0)
return 0;
if (CurTok != tok_else)
return Error("expected else");
@ -340,7 +378,8 @@ static ExprAST *ParseIfExpr() {
getNextToken();
ExprAST *Else = ParseExpression();
if (!Else) return 0;
if (!Else)
return 0;
return new IfExprAST(Cond, Then, Else);
}
@ -359,22 +398,24 @@ static ExprAST *ParseForExpr() {
return Error("expected '=' after for");
getNextToken(); // eat '='.
ExprAST *Start = ParseExpression();
if (Start == 0) return 0;
if (Start == 0)
return 0;
if (CurTok != ',')
return Error("expected ',' after for start value");
getNextToken();
ExprAST *End = ParseExpression();
if (End == 0) return 0;
if (End == 0)
return 0;
// The step value is optional.
ExprAST *Step = 0;
if (CurTok == ',') {
getNextToken();
Step = ParseExpression();
if (Step == 0) return 0;
if (Step == 0)
return 0;
}
if (CurTok != tok_in)
@ -382,7 +423,8 @@ static ExprAST *ParseForExpr() {
getNextToken(); // eat 'in'.
ExprAST *Body = ParseExpression();
if (Body == 0) return 0;
if (Body == 0)
return 0;
return new ForExprAST(IdName, Start, End, Step, Body);
}
@ -392,7 +434,7 @@ static ExprAST *ParseForExpr() {
static ExprAST *ParseVarExpr() {
getNextToken(); // eat the var.
std::vector<std::pair<std::string, ExprAST*> > VarNames;
std::vector<std::pair<std::string, ExprAST *> > VarNames;
// At least one variable name is required.
if (CurTok != tok_identifier)
@ -408,13 +450,15 @@ static ExprAST *ParseVarExpr() {
getNextToken(); // eat the '='.
Init = ParseExpression();
if (Init == 0) return 0;
if (Init == 0)
return 0;
}
VarNames.push_back(std::make_pair(Name, Init));
// End of var list, exit loop.
if (CurTok != ',') break;
if (CurTok != ',')
break;
getNextToken(); // eat the ','.
if (CurTok != tok_identifier)
@ -427,7 +471,8 @@ static ExprAST *ParseVarExpr() {
getNextToken(); // eat 'in'.
ExprAST *Body = ParseExpression();
if (Body == 0) return 0;
if (Body == 0)
return 0;
return new VarExprAST(VarNames, Body);
}
@ -441,13 +486,20 @@ static ExprAST *ParseVarExpr() {
/// ::= varexpr
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();
case tok_var: return ParseVarExpr();
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();
case tok_var:
return ParseVarExpr();
}
}
@ -485,14 +537,16 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
// Parse the unary expression after the binary operator.
ExprAST *RHS = ParseUnary();
if (!RHS) return 0;
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;
RHS = ParseBinOpRHS(TokPrec + 1, RHS);
if (RHS == 0)
return 0;
}
// Merge LHS/RHS.
@ -505,7 +559,8 @@ static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
///
static ExprAST *ParseExpression() {
ExprAST *LHS = ParseUnary();
if (!LHS) return 0;
if (!LHS)
return 0;
return ParseBinOpRHS(0, LHS);
}
@ -579,7 +634,8 @@ static PrototypeAST *ParsePrototype() {
static FunctionAST *ParseDefinition() {
getNextToken(); // eat def.
PrototypeAST *Proto = ParsePrototype();
if (Proto == 0) return 0;
if (Proto == 0)
return 0;
if (ExprAST *E = ParseExpression())
return new FunctionAST(Proto, E);
@ -608,10 +664,13 @@ static PrototypeAST *ParseExtern() {
static Module *TheModule;
static IRBuilder<> Builder(getGlobalContext());
static std::map<std::string, AllocaInst*> NamedValues;
static std::map<std::string, AllocaInst *> NamedValues;
static FunctionPassManager *TheFPM;
Value *ErrorV(const char *Str) { Error(Str); return 0; }
Value *ErrorV(const char *Str) {
Error(Str);
return 0;
}
/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
/// the function. This is used for mutable variables etc.
@ -630,7 +689,8 @@ Value *NumberExprAST::Codegen() {
Value *VariableExprAST::Codegen() {
// Look this variable up in the function.
Value *V = NamedValues[Name];
if (V == 0) return ErrorV("Unknown variable name");
if (V == 0)
return ErrorV("Unknown variable name");
// Load the value.
return Builder.CreateLoad(V, Name.c_str());
@ -638,9 +698,10 @@ Value *VariableExprAST::Codegen() {
Value *UnaryExprAST::Codegen() {
Value *OperandV = Operand->Codegen();
if (OperandV == 0) return 0;
if (OperandV == 0)
return 0;
Function *F = TheModule->getFunction(std::string("unary")+Opcode);
Function *F = TheModule->getFunction(std::string("unary") + Opcode);
if (F == 0)
return ErrorV("Unknown unary operator");
@ -651,16 +712,18 @@ Value *BinaryExprAST::Codegen() {
// Special case '=' because we don't want to emit the LHS as an expression.
if (Op == '=') {
// Assignment requires the LHS to be an identifier.
VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
VariableExprAST *LHSE = dynamic_cast<VariableExprAST *>(LHS);
if (!LHSE)
return ErrorV("destination of '=' must be a variable");
// Codegen the RHS.
Value *Val = RHS->Codegen();
if (Val == 0) return 0;
if (Val == 0)
return 0;
// Look up the name.
Value *Variable = NamedValues[LHSE->getName()];
if (Variable == 0) return ErrorV("Unknown variable name");
if (Variable == 0)
return ErrorV("Unknown variable name");
Builder.CreateStore(Val, Variable);
return Val;
@ -668,23 +731,28 @@ Value *BinaryExprAST::Codegen() {
Value *L = LHS->Codegen();
Value *R = RHS->Codegen();
if (L == 0 || R == 0) return 0;
if (L == 0 || R == 0)
return 0;
switch (Op) {
case '+': return Builder.CreateFAdd(L, R, "addtmp");
case '-': return Builder.CreateFSub(L, R, "subtmp");
case '*': return Builder.CreateFMul(L, R, "multmp");
case '+':
return Builder.CreateFAdd(L, R, "addtmp");
case '-':
return Builder.CreateFSub(L, R, "subtmp");
case '*':
return Builder.CreateFMul(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;
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);
Function *F = TheModule->getFunction(std::string("binary") + Op);
assert(F && "binary operator not found!");
Value *Ops[] = { L, R };
@ -701,10 +769,11 @@ Value *CallExprAST::Codegen() {
if (CalleeF->arg_size() != Args.size())
return ErrorV("Incorrect # arguments passed");
std::vector<Value*> ArgsV;
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;
if (ArgsV.back() == 0)
return 0;
}
return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
@ -712,18 +781,19 @@ Value *CallExprAST::Codegen() {
Value *IfExprAST::Codegen() {
Value *CondV = Cond->Codegen();
if (CondV == 0) return 0;
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");
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 *ThenBB =
BasicBlock::Create(getGlobalContext(), "then", TheFunction);
BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
@ -733,7 +803,8 @@ Value *IfExprAST::Codegen() {
Builder.SetInsertPoint(ThenBB);
Value *ThenV = Then->Codegen();
if (ThenV == 0) return 0;
if (ThenV == 0)
return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
@ -744,7 +815,8 @@ Value *IfExprAST::Codegen() {
Builder.SetInsertPoint(ElseBB);
Value *ElseV = Else->Codegen();
if (ElseV == 0) return 0;
if (ElseV == 0)
return 0;
Builder.CreateBr(MergeBB);
// Codegen of 'Else' can change the current block, update ElseBB for the PHI.
@ -753,8 +825,8 @@ Value *IfExprAST::Codegen() {
// Emit merge block.
TheFunction->getBasicBlockList().push_back(MergeBB);
Builder.SetInsertPoint(MergeBB);
PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
"iftmp");
PHINode *PN =
Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
PN->addIncoming(ThenV, ThenBB);
PN->addIncoming(ElseV, ElseBB);
@ -789,14 +861,16 @@ Value *ForExprAST::Codegen() {
// Emit the start code first, without 'variable' in scope.
Value *StartVal = Start->Codegen();
if (StartVal == 0) return 0;
if (StartVal == 0)
return 0;
// Store the value into the alloca.
Builder.CreateStore(StartVal, Alloca);
// Make the new basic block for the loop header, inserting after current
// block.
BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
BasicBlock *LoopBB =
BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
// Insert an explicit fall through from the current block to the LoopBB.
Builder.CreateBr(LoopBB);
@ -819,7 +893,8 @@ Value *ForExprAST::Codegen() {
Value *StepVal;
if (Step) {
StepVal = Step->Codegen();
if (StepVal == 0) return 0;
if (StepVal == 0)
return 0;
} else {
// If not specified, use 1.0.
StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
@ -827,7 +902,8 @@ Value *ForExprAST::Codegen() {
// Compute the end condition.
Value *EndCond = End->Codegen();
if (EndCond == 0) return EndCond;
if (EndCond == 0)
return EndCond;
// Reload, increment, and restore the alloca. This handles the case where
// the body of the loop mutates the variable.
@ -836,12 +912,12 @@ Value *ForExprAST::Codegen() {
Builder.CreateStore(NextVar, Alloca);
// Convert condition to a bool by comparing equal to 0.0.
EndCond = Builder.CreateFCmpONE(EndCond,
ConstantFP::get(getGlobalContext(), APFloat(0.0)),
"loopcond");
EndCond = Builder.CreateFCmpONE(
EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
// Create the "after loop" block and insert it.
BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
BasicBlock *AfterBB =
BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
// Insert the conditional branch into the end of LoopEndBB.
Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
@ -855,7 +931,6 @@ Value *ForExprAST::Codegen() {
else
NamedValues.erase(VarName);
// for expr always returns 0.0.
return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
}
@ -878,7 +953,8 @@ Value *VarExprAST::Codegen() {
Value *InitVal;
if (Init) {
InitVal = Init->Codegen();
if (InitVal == 0) return 0;
if (InitVal == 0)
return 0;
} else { // If not specified, use 0.0.
InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
}
@ -896,7 +972,8 @@ Value *VarExprAST::Codegen() {
// Codegen the body, now that all vars are in scope.
Value *BodyVal = Body->Codegen();
if (BodyVal == 0) return 0;
if (BodyVal == 0)
return 0;
// Pop all our variables from scope.
for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
@ -908,12 +985,13 @@ Value *VarExprAST::Codegen() {
Function *PrototypeAST::Codegen() {
// Make the function type: double(double,double) etc.
std::vector<Type*> Doubles(Args.size(),
std::vector<Type *> Doubles(Args.size(),
Type::getDoubleTy(getGlobalContext()));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
Doubles, false);
FunctionType *FT =
FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
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.
@ -1053,11 +1131,20 @@ 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;
case tok_eof:
return;
case ';':
getNextToken();
break; // ignore top-level semicolons.
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
@ -1067,15 +1154,13 @@ static void MainLoop() {
//===----------------------------------------------------------------------===//
/// putchard - putchar that takes a double and returns 0.
extern "C"
double putchard(double X) {
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) {
extern "C" double printd(double X) {
printf("%f\n", X);
return 0;
}
@ -1108,9 +1193,10 @@ int main() {
// Create the JIT. This takes ownership of the module.
std::string ErrStr;
TheExecutionEngine = EngineBuilder(std::move(Owner))
TheExecutionEngine =
EngineBuilder(std::move(Owner))
.setErrorStr(&ErrStr)
.setMCJITMemoryManager(new SectionMemoryManager())
.setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
.create();
if (!TheExecutionEngine) {
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());

View File

@ -1444,9 +1444,10 @@ int main() {
// Create the JIT. This takes ownership of the module.
std::string ErrStr;
TheExecutionEngine = EngineBuilder(std::move(Owner))
TheExecutionEngine =
EngineBuilder(std::move(Owner))
.setErrorStr(&ErrStr)
.setMCJITMemoryManager(new SectionMemoryManager())
.setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
.create();
if (!TheExecutionEngine) {
fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());