blob: 4070d3f38e709d4f8f4fced9035cd229f16dc7a3 [file] [log] [blame]
Nick Lewycky9f856342009-04-12 20:47:23 +00001#include "llvm/DerivedTypes.h"
2#include "llvm/ExecutionEngine/ExecutionEngine.h"
Xerxes Ranby6ce6daa2009-07-19 08:10:01 +00003#include "llvm/ExecutionEngine/JIT.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +00004#include "llvm/LLVMContext.h"
Nick Lewycky9f856342009-04-12 20:47:23 +00005#include "llvm/Module.h"
Nick Lewycky9f856342009-04-12 20:47:23 +00006#include "llvm/PassManager.h"
7#include "llvm/Analysis/Verifier.h"
Dan Gohmanab7fa082010-11-16 17:28:22 +00008#include "llvm/Analysis/Passes.h"
Nick Lewycky9f856342009-04-12 20:47:23 +00009#include "llvm/Target/TargetData.h"
Chris Lattnerda062882009-06-17 16:48:44 +000010#include "llvm/Target/TargetSelect.h"
Nick Lewycky9f856342009-04-12 20:47:23 +000011#include "llvm/Transforms/Scalar.h"
12#include "llvm/Support/IRBuilder.h"
13#include <cstdio>
14#include <string>
15#include <map>
16#include <vector>
17using namespace llvm;
18
19//===----------------------------------------------------------------------===//
20// Lexer
21//===----------------------------------------------------------------------===//
22
23// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
24// of these for known things.
25enum Token {
26 tok_eof = -1,
27
28 // commands
29 tok_def = -2, tok_extern = -3,
30
31 // primary
32 tok_identifier = -4, tok_number = -5,
33
34 // control
35 tok_if = -6, tok_then = -7, tok_else = -8,
36 tok_for = -9, tok_in = -10,
37
38 // operators
39 tok_binary = -11, tok_unary = -12,
40
41 // var definition
42 tok_var = -13
43};
44
45static std::string IdentifierStr; // Filled in if tok_identifier
46static double NumVal; // Filled in if tok_number
47
48/// gettok - Return the next token from standard input.
49static int gettok() {
50 static int LastChar = ' ';
51
52 // Skip any whitespace.
53 while (isspace(LastChar))
54 LastChar = getchar();
55
56 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
57 IdentifierStr = LastChar;
58 while (isalnum((LastChar = getchar())))
59 IdentifierStr += LastChar;
60
61 if (IdentifierStr == "def") return tok_def;
62 if (IdentifierStr == "extern") return tok_extern;
63 if (IdentifierStr == "if") return tok_if;
64 if (IdentifierStr == "then") return tok_then;
65 if (IdentifierStr == "else") return tok_else;
66 if (IdentifierStr == "for") return tok_for;
67 if (IdentifierStr == "in") return tok_in;
68 if (IdentifierStr == "binary") return tok_binary;
69 if (IdentifierStr == "unary") return tok_unary;
70 if (IdentifierStr == "var") return tok_var;
71 return tok_identifier;
72 }
73
74 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
75 std::string NumStr;
76 do {
77 NumStr += LastChar;
78 LastChar = getchar();
79 } while (isdigit(LastChar) || LastChar == '.');
80
81 NumVal = strtod(NumStr.c_str(), 0);
82 return tok_number;
83 }
84
85 if (LastChar == '#') {
86 // Comment until end of line.
87 do LastChar = getchar();
88 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
89
90 if (LastChar != EOF)
91 return gettok();
92 }
93
94 // Check for end of file. Don't eat the EOF.
95 if (LastChar == EOF)
96 return tok_eof;
97
98 // Otherwise, just return the character as its ascii value.
99 int ThisChar = LastChar;
100 LastChar = getchar();
101 return ThisChar;
102}
103
104//===----------------------------------------------------------------------===//
105// Abstract Syntax Tree (aka Parse Tree)
106//===----------------------------------------------------------------------===//
107
108/// ExprAST - Base class for all expression nodes.
109class ExprAST {
110public:
111 virtual ~ExprAST() {}
112 virtual Value *Codegen() = 0;
113};
114
115/// NumberExprAST - Expression class for numeric literals like "1.0".
116class NumberExprAST : public ExprAST {
117 double Val;
118public:
119 NumberExprAST(double val) : Val(val) {}
120 virtual Value *Codegen();
121};
122
123/// VariableExprAST - Expression class for referencing a variable, like "a".
124class VariableExprAST : public ExprAST {
125 std::string Name;
126public:
127 VariableExprAST(const std::string &name) : Name(name) {}
128 const std::string &getName() const { return Name; }
129 virtual Value *Codegen();
130};
131
132/// UnaryExprAST - Expression class for a unary operator.
133class UnaryExprAST : public ExprAST {
134 char Opcode;
135 ExprAST *Operand;
136public:
137 UnaryExprAST(char opcode, ExprAST *operand)
138 : Opcode(opcode), Operand(operand) {}
139 virtual Value *Codegen();
140};
141
142/// BinaryExprAST - Expression class for a binary operator.
143class BinaryExprAST : public ExprAST {
144 char Op;
145 ExprAST *LHS, *RHS;
146public:
147 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
148 : Op(op), LHS(lhs), RHS(rhs) {}
149 virtual Value *Codegen();
150};
151
152/// CallExprAST - Expression class for function calls.
153class CallExprAST : public ExprAST {
154 std::string Callee;
155 std::vector<ExprAST*> Args;
156public:
157 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
158 : Callee(callee), Args(args) {}
159 virtual Value *Codegen();
160};
161
162/// IfExprAST - Expression class for if/then/else.
163class IfExprAST : public ExprAST {
164 ExprAST *Cond, *Then, *Else;
165public:
166 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
167 : Cond(cond), Then(then), Else(_else) {}
168 virtual Value *Codegen();
169};
170
171/// ForExprAST - Expression class for for/in.
172class ForExprAST : public ExprAST {
173 std::string VarName;
174 ExprAST *Start, *End, *Step, *Body;
175public:
176 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
177 ExprAST *step, ExprAST *body)
178 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
179 virtual Value *Codegen();
180};
181
182/// VarExprAST - Expression class for var/in
183class VarExprAST : public ExprAST {
184 std::vector<std::pair<std::string, ExprAST*> > VarNames;
185 ExprAST *Body;
186public:
187 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
188 ExprAST *body)
189 : VarNames(varnames), Body(body) {}
190
191 virtual Value *Codegen();
192};
193
194/// PrototypeAST - This class represents the "prototype" for a function,
195/// which captures its argument names as well as if it is an operator.
196class PrototypeAST {
197 std::string Name;
198 std::vector<std::string> Args;
199 bool isOperator;
200 unsigned Precedence; // Precedence if a binary op.
201public:
202 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
203 bool isoperator = false, unsigned prec = 0)
204 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
205
206 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
207 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
208
209 char getOperatorName() const {
210 assert(isUnaryOp() || isBinaryOp());
211 return Name[Name.size()-1];
212 }
213
214 unsigned getBinaryPrecedence() const { return Precedence; }
215
216 Function *Codegen();
217
218 void CreateArgumentAllocas(Function *F);
219};
220
221/// FunctionAST - This class represents a function definition itself.
222class FunctionAST {
223 PrototypeAST *Proto;
224 ExprAST *Body;
225public:
226 FunctionAST(PrototypeAST *proto, ExprAST *body)
227 : Proto(proto), Body(body) {}
228
229 Function *Codegen();
230};
231
232//===----------------------------------------------------------------------===//
233// Parser
234//===----------------------------------------------------------------------===//
235
236/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000237/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky9f856342009-04-12 20:47:23 +0000238/// lexer and updates CurTok with its results.
239static int CurTok;
240static int getNextToken() {
241 return CurTok = gettok();
242}
243
244/// BinopPrecedence - This holds the precedence for each binary operator that is
245/// defined.
246static std::map<char, int> BinopPrecedence;
247
248/// GetTokPrecedence - Get the precedence of the pending binary operator token.
249static int GetTokPrecedence() {
250 if (!isascii(CurTok))
251 return -1;
252
253 // Make sure it's a declared binop.
254 int TokPrec = BinopPrecedence[CurTok];
255 if (TokPrec <= 0) return -1;
256 return TokPrec;
257}
258
259/// Error* - These are little helper functions for error handling.
260ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
261PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
262FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
263
264static ExprAST *ParseExpression();
265
266/// identifierexpr
267/// ::= identifier
268/// ::= identifier '(' expression* ')'
269static ExprAST *ParseIdentifierExpr() {
270 std::string IdName = IdentifierStr;
271
272 getNextToken(); // eat identifier.
273
274 if (CurTok != '(') // Simple variable ref.
275 return new VariableExprAST(IdName);
276
277 // Call.
278 getNextToken(); // eat (
279 std::vector<ExprAST*> Args;
280 if (CurTok != ')') {
281 while (1) {
282 ExprAST *Arg = ParseExpression();
283 if (!Arg) return 0;
284 Args.push_back(Arg);
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000285
Nick Lewycky9f856342009-04-12 20:47:23 +0000286 if (CurTok == ')') break;
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000287
Nick Lewycky9f856342009-04-12 20:47:23 +0000288 if (CurTok != ',')
289 return Error("Expected ')' or ',' in argument list");
290 getNextToken();
291 }
292 }
293
294 // Eat the ')'.
295 getNextToken();
296
297 return new CallExprAST(IdName, Args);
298}
299
300/// numberexpr ::= number
301static ExprAST *ParseNumberExpr() {
302 ExprAST *Result = new NumberExprAST(NumVal);
303 getNextToken(); // consume the number
304 return Result;
305}
306
307/// parenexpr ::= '(' expression ')'
308static ExprAST *ParseParenExpr() {
309 getNextToken(); // eat (.
310 ExprAST *V = ParseExpression();
311 if (!V) return 0;
312
313 if (CurTok != ')')
314 return Error("expected ')'");
315 getNextToken(); // eat ).
316 return V;
317}
318
319/// ifexpr ::= 'if' expression 'then' expression 'else' expression
320static ExprAST *ParseIfExpr() {
321 getNextToken(); // eat the if.
322
323 // condition.
324 ExprAST *Cond = ParseExpression();
325 if (!Cond) return 0;
326
327 if (CurTok != tok_then)
328 return Error("expected then");
329 getNextToken(); // eat the then
330
331 ExprAST *Then = ParseExpression();
332 if (Then == 0) return 0;
333
334 if (CurTok != tok_else)
335 return Error("expected else");
336
337 getNextToken();
338
339 ExprAST *Else = ParseExpression();
340 if (!Else) return 0;
341
342 return new IfExprAST(Cond, Then, Else);
343}
344
345/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
346static ExprAST *ParseForExpr() {
347 getNextToken(); // eat the for.
348
349 if (CurTok != tok_identifier)
350 return Error("expected identifier after for");
351
352 std::string IdName = IdentifierStr;
353 getNextToken(); // eat identifier.
354
355 if (CurTok != '=')
356 return Error("expected '=' after for");
357 getNextToken(); // eat '='.
358
359
360 ExprAST *Start = ParseExpression();
361 if (Start == 0) return 0;
362 if (CurTok != ',')
363 return Error("expected ',' after for start value");
364 getNextToken();
365
366 ExprAST *End = ParseExpression();
367 if (End == 0) return 0;
368
369 // The step value is optional.
370 ExprAST *Step = 0;
371 if (CurTok == ',') {
372 getNextToken();
373 Step = ParseExpression();
374 if (Step == 0) return 0;
375 }
376
377 if (CurTok != tok_in)
378 return Error("expected 'in' after for");
379 getNextToken(); // eat 'in'.
380
381 ExprAST *Body = ParseExpression();
382 if (Body == 0) return 0;
383
384 return new ForExprAST(IdName, Start, End, Step, Body);
385}
386
387/// varexpr ::= 'var' identifier ('=' expression)?
388// (',' identifier ('=' expression)?)* 'in' expression
389static ExprAST *ParseVarExpr() {
390 getNextToken(); // eat the var.
391
392 std::vector<std::pair<std::string, ExprAST*> > VarNames;
393
394 // At least one variable name is required.
395 if (CurTok != tok_identifier)
396 return Error("expected identifier after var");
397
398 while (1) {
399 std::string Name = IdentifierStr;
400 getNextToken(); // eat identifier.
401
402 // Read the optional initializer.
403 ExprAST *Init = 0;
404 if (CurTok == '=') {
405 getNextToken(); // eat the '='.
406
407 Init = ParseExpression();
408 if (Init == 0) return 0;
409 }
410
411 VarNames.push_back(std::make_pair(Name, Init));
412
413 // End of var list, exit loop.
414 if (CurTok != ',') break;
415 getNextToken(); // eat the ','.
416
417 if (CurTok != tok_identifier)
418 return Error("expected identifier list after var");
419 }
420
421 // At this point, we have to have 'in'.
422 if (CurTok != tok_in)
423 return Error("expected 'in' keyword after 'var'");
424 getNextToken(); // eat 'in'.
425
426 ExprAST *Body = ParseExpression();
427 if (Body == 0) return 0;
428
429 return new VarExprAST(VarNames, Body);
430}
431
Nick Lewycky9f856342009-04-12 20:47:23 +0000432/// primary
433/// ::= identifierexpr
434/// ::= numberexpr
435/// ::= parenexpr
436/// ::= ifexpr
437/// ::= forexpr
438/// ::= varexpr
439static ExprAST *ParsePrimary() {
440 switch (CurTok) {
441 default: return Error("unknown token when expecting an expression");
442 case tok_identifier: return ParseIdentifierExpr();
443 case tok_number: return ParseNumberExpr();
444 case '(': return ParseParenExpr();
445 case tok_if: return ParseIfExpr();
446 case tok_for: return ParseForExpr();
447 case tok_var: return ParseVarExpr();
448 }
449}
450
451/// unary
452/// ::= primary
453/// ::= '!' unary
454static ExprAST *ParseUnary() {
455 // If the current token is not an operator, it must be a primary expr.
456 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
457 return ParsePrimary();
458
459 // If this is a unary operator, read it.
460 int Opc = CurTok;
461 getNextToken();
462 if (ExprAST *Operand = ParseUnary())
463 return new UnaryExprAST(Opc, Operand);
464 return 0;
465}
466
467/// binoprhs
468/// ::= ('+' unary)*
469static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
470 // If this is a binop, find its precedence.
471 while (1) {
472 int TokPrec = GetTokPrecedence();
473
474 // If this is a binop that binds at least as tightly as the current binop,
475 // consume it, otherwise we are done.
476 if (TokPrec < ExprPrec)
477 return LHS;
478
479 // Okay, we know this is a binop.
480 int BinOp = CurTok;
481 getNextToken(); // eat binop
482
483 // Parse the unary expression after the binary operator.
484 ExprAST *RHS = ParseUnary();
485 if (!RHS) return 0;
486
487 // If BinOp binds less tightly with RHS than the operator after RHS, let
488 // the pending operator take RHS as its LHS.
489 int NextPrec = GetTokPrecedence();
490 if (TokPrec < NextPrec) {
491 RHS = ParseBinOpRHS(TokPrec+1, RHS);
492 if (RHS == 0) return 0;
493 }
494
495 // Merge LHS/RHS.
496 LHS = new BinaryExprAST(BinOp, LHS, RHS);
497 }
498}
499
500/// expression
501/// ::= unary binoprhs
502///
503static ExprAST *ParseExpression() {
504 ExprAST *LHS = ParseUnary();
505 if (!LHS) return 0;
506
507 return ParseBinOpRHS(0, LHS);
508}
509
510/// prototype
511/// ::= id '(' id* ')'
512/// ::= binary LETTER number? (id, id)
513/// ::= unary LETTER (id)
514static PrototypeAST *ParsePrototype() {
515 std::string FnName;
516
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000517 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky9f856342009-04-12 20:47:23 +0000518 unsigned BinaryPrecedence = 30;
519
520 switch (CurTok) {
521 default:
522 return ErrorP("Expected function name in prototype");
523 case tok_identifier:
524 FnName = IdentifierStr;
525 Kind = 0;
526 getNextToken();
527 break;
528 case tok_unary:
529 getNextToken();
530 if (!isascii(CurTok))
531 return ErrorP("Expected unary operator");
532 FnName = "unary";
533 FnName += (char)CurTok;
534 Kind = 1;
535 getNextToken();
536 break;
537 case tok_binary:
538 getNextToken();
539 if (!isascii(CurTok))
540 return ErrorP("Expected binary operator");
541 FnName = "binary";
542 FnName += (char)CurTok;
543 Kind = 2;
544 getNextToken();
545
546 // Read the precedence if present.
547 if (CurTok == tok_number) {
548 if (NumVal < 1 || NumVal > 100)
549 return ErrorP("Invalid precedecnce: must be 1..100");
550 BinaryPrecedence = (unsigned)NumVal;
551 getNextToken();
552 }
553 break;
554 }
555
556 if (CurTok != '(')
557 return ErrorP("Expected '(' in prototype");
558
559 std::vector<std::string> ArgNames;
560 while (getNextToken() == tok_identifier)
561 ArgNames.push_back(IdentifierStr);
562 if (CurTok != ')')
563 return ErrorP("Expected ')' in prototype");
564
565 // success.
566 getNextToken(); // eat ')'.
567
568 // Verify right number of names for operator.
569 if (Kind && ArgNames.size() != Kind)
570 return ErrorP("Invalid number of operands for operator");
571
572 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
573}
574
575/// definition ::= 'def' prototype expression
576static FunctionAST *ParseDefinition() {
577 getNextToken(); // eat def.
578 PrototypeAST *Proto = ParsePrototype();
579 if (Proto == 0) return 0;
580
581 if (ExprAST *E = ParseExpression())
582 return new FunctionAST(Proto, E);
583 return 0;
584}
585
586/// toplevelexpr ::= expression
587static FunctionAST *ParseTopLevelExpr() {
588 if (ExprAST *E = ParseExpression()) {
589 // Make an anonymous proto.
590 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
591 return new FunctionAST(Proto, E);
592 }
593 return 0;
594}
595
596/// external ::= 'extern' prototype
597static PrototypeAST *ParseExtern() {
598 getNextToken(); // eat extern.
599 return ParsePrototype();
600}
601
602//===----------------------------------------------------------------------===//
603// Code Generation
604//===----------------------------------------------------------------------===//
605
606static Module *TheModule;
Owen Andersond1fbd142009-07-08 20:50:47 +0000607static IRBuilder<> Builder(getGlobalContext());
Nick Lewycky9f856342009-04-12 20:47:23 +0000608static std::map<std::string, AllocaInst*> NamedValues;
609static FunctionPassManager *TheFPM;
610
611Value *ErrorV(const char *Str) { Error(Str); return 0; }
612
613/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
614/// the function. This is used for mutable variables etc.
615static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
616 const std::string &VarName) {
617 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
618 TheFunction->getEntryBlock().begin());
Owen Anderson1d0be152009-08-13 21:58:54 +0000619 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
620 VarName.c_str());
Nick Lewycky9f856342009-04-12 20:47:23 +0000621}
622
Nick Lewycky9f856342009-04-12 20:47:23 +0000623Value *NumberExprAST::Codegen() {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000624 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky9f856342009-04-12 20:47:23 +0000625}
626
627Value *VariableExprAST::Codegen() {
628 // Look this variable up in the function.
629 Value *V = NamedValues[Name];
630 if (V == 0) return ErrorV("Unknown variable name");
631
632 // Load the value.
633 return Builder.CreateLoad(V, Name.c_str());
634}
635
636Value *UnaryExprAST::Codegen() {
637 Value *OperandV = Operand->Codegen();
638 if (OperandV == 0) return 0;
639
640 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
641 if (F == 0)
642 return ErrorV("Unknown unary operator");
643
644 return Builder.CreateCall(F, OperandV, "unop");
645}
646
Nick Lewycky9f856342009-04-12 20:47:23 +0000647Value *BinaryExprAST::Codegen() {
648 // Special case '=' because we don't want to emit the LHS as an expression.
649 if (Op == '=') {
650 // Assignment requires the LHS to be an identifier.
651 VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
652 if (!LHSE)
653 return ErrorV("destination of '=' must be a variable");
654 // Codegen the RHS.
655 Value *Val = RHS->Codegen();
656 if (Val == 0) return 0;
657
658 // Look up the name.
659 Value *Variable = NamedValues[LHSE->getName()];
660 if (Variable == 0) return ErrorV("Unknown variable name");
661
662 Builder.CreateStore(Val, Variable);
663 return Val;
664 }
665
Nick Lewycky9f856342009-04-12 20:47:23 +0000666 Value *L = LHS->Codegen();
667 Value *R = RHS->Codegen();
668 if (L == 0 || R == 0) return 0;
669
670 switch (Op) {
Eric Christopher2632bbf2010-06-14 06:03:16 +0000671 case '+': return Builder.CreateFAdd(L, R, "addtmp");
672 case '-': return Builder.CreateFSub(L, R, "subtmp");
673 case '*': return Builder.CreateFMul(L, R, "multmp");
Nick Lewycky9f856342009-04-12 20:47:23 +0000674 case '<':
675 L = Builder.CreateFCmpULT(L, R, "cmptmp");
676 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson1d0be152009-08-13 21:58:54 +0000677 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
678 "booltmp");
Nick Lewycky9f856342009-04-12 20:47:23 +0000679 default: break;
680 }
681
682 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
683 // a call to it.
684 Function *F = TheModule->getFunction(std::string("binary")+Op);
685 assert(F && "binary operator not found!");
686
687 Value *Ops[] = { L, R };
688 return Builder.CreateCall(F, Ops, Ops+2, "binop");
689}
690
691Value *CallExprAST::Codegen() {
692 // Look up the name in the global module table.
693 Function *CalleeF = TheModule->getFunction(Callee);
694 if (CalleeF == 0)
695 return ErrorV("Unknown function referenced");
696
697 // If argument mismatch error.
698 if (CalleeF->arg_size() != Args.size())
699 return ErrorV("Incorrect # arguments passed");
700
701 std::vector<Value*> ArgsV;
702 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
703 ArgsV.push_back(Args[i]->Codegen());
704 if (ArgsV.back() == 0) return 0;
705 }
706
707 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
708}
709
710Value *IfExprAST::Codegen() {
711 Value *CondV = Cond->Codegen();
712 if (CondV == 0) return 0;
713
714 // Convert condition to a bool by comparing equal to 0.0.
715 CondV = Builder.CreateFCmpONE(CondV,
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000716 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
Nick Lewycky9f856342009-04-12 20:47:23 +0000717 "ifcond");
718
719 Function *TheFunction = Builder.GetInsertBlock()->getParent();
720
721 // Create blocks for the then and else cases. Insert the 'then' block at the
722 // end of the function.
Owen Anderson1d0be152009-08-13 21:58:54 +0000723 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
724 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
725 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Nick Lewycky9f856342009-04-12 20:47:23 +0000726
727 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
728
729 // Emit then value.
730 Builder.SetInsertPoint(ThenBB);
731
732 Value *ThenV = Then->Codegen();
733 if (ThenV == 0) return 0;
734
735 Builder.CreateBr(MergeBB);
736 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
737 ThenBB = Builder.GetInsertBlock();
738
739 // Emit else block.
740 TheFunction->getBasicBlockList().push_back(ElseBB);
741 Builder.SetInsertPoint(ElseBB);
742
743 Value *ElseV = Else->Codegen();
744 if (ElseV == 0) return 0;
745
746 Builder.CreateBr(MergeBB);
747 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
748 ElseBB = Builder.GetInsertBlock();
749
750 // Emit merge block.
751 TheFunction->getBasicBlockList().push_back(MergeBB);
752 Builder.SetInsertPoint(MergeBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000753 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
754 "iftmp");
Jay Foadd8b4fb42011-03-30 11:19:20 +0000755 PN->reserveOperandSpace(2);
Nick Lewycky9f856342009-04-12 20:47:23 +0000756
757 PN->addIncoming(ThenV, ThenBB);
758 PN->addIncoming(ElseV, ElseBB);
759 return PN;
760}
761
762Value *ForExprAST::Codegen() {
763 // Output this as:
764 // var = alloca double
765 // ...
766 // start = startexpr
767 // store start -> var
768 // goto loop
769 // loop:
770 // ...
771 // bodyexpr
772 // ...
773 // loopend:
774 // step = stepexpr
775 // endcond = endexpr
776 //
777 // curvar = load var
778 // nextvar = curvar + step
779 // store nextvar -> var
780 // br endcond, loop, endloop
781 // outloop:
782
783 Function *TheFunction = Builder.GetInsertBlock()->getParent();
784
785 // Create an alloca for the variable in the entry block.
786 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
787
788 // Emit the start code first, without 'variable' in scope.
789 Value *StartVal = Start->Codegen();
790 if (StartVal == 0) return 0;
791
792 // Store the value into the alloca.
793 Builder.CreateStore(StartVal, Alloca);
794
795 // Make the new basic block for the loop header, inserting after current
796 // block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000797 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
Nick Lewycky9f856342009-04-12 20:47:23 +0000798
799 // Insert an explicit fall through from the current block to the LoopBB.
800 Builder.CreateBr(LoopBB);
801
802 // Start insertion in LoopBB.
803 Builder.SetInsertPoint(LoopBB);
804
805 // Within the loop, the variable is defined equal to the PHI node. If it
806 // shadows an existing variable, we have to restore it, so save it now.
807 AllocaInst *OldVal = NamedValues[VarName];
808 NamedValues[VarName] = Alloca;
809
810 // Emit the body of the loop. This, like any other expr, can change the
811 // current BB. Note that we ignore the value computed by the body, but don't
812 // allow an error.
813 if (Body->Codegen() == 0)
814 return 0;
815
816 // Emit the step value.
817 Value *StepVal;
818 if (Step) {
819 StepVal = Step->Codegen();
820 if (StepVal == 0) return 0;
821 } else {
822 // If not specified, use 1.0.
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000823 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky9f856342009-04-12 20:47:23 +0000824 }
825
826 // Compute the end condition.
827 Value *EndCond = End->Codegen();
828 if (EndCond == 0) return EndCond;
829
830 // Reload, increment, and restore the alloca. This handles the case where
831 // the body of the loop mutates the variable.
832 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
Chris Lattnerb0e9ead2010-06-21 22:51:14 +0000833 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
Nick Lewycky9f856342009-04-12 20:47:23 +0000834 Builder.CreateStore(NextVar, Alloca);
835
836 // Convert condition to a bool by comparing equal to 0.0.
837 EndCond = Builder.CreateFCmpONE(EndCond,
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000838 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
Nick Lewycky9f856342009-04-12 20:47:23 +0000839 "loopcond");
840
841 // Create the "after loop" block and insert it.
Owen Anderson1d0be152009-08-13 21:58:54 +0000842 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
Nick Lewycky9f856342009-04-12 20:47:23 +0000843
844 // Insert the conditional branch into the end of LoopEndBB.
845 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
846
847 // Any new code will be inserted in AfterBB.
848 Builder.SetInsertPoint(AfterBB);
849
850 // Restore the unshadowed variable.
851 if (OldVal)
852 NamedValues[VarName] = OldVal;
853 else
854 NamedValues.erase(VarName);
855
856
857 // for expr always returns 0.0.
Owen Anderson1d0be152009-08-13 21:58:54 +0000858 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky9f856342009-04-12 20:47:23 +0000859}
860
861Value *VarExprAST::Codegen() {
862 std::vector<AllocaInst *> OldBindings;
863
864 Function *TheFunction = Builder.GetInsertBlock()->getParent();
865
866 // Register all variables and emit their initializer.
867 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
868 const std::string &VarName = VarNames[i].first;
869 ExprAST *Init = VarNames[i].second;
870
871 // Emit the initializer before adding the variable to scope, this prevents
872 // the initializer from referencing the variable itself, and permits stuff
873 // like this:
874 // var a = 1 in
875 // var a = a in ... # refers to outer 'a'.
876 Value *InitVal;
877 if (Init) {
878 InitVal = Init->Codegen();
879 if (InitVal == 0) return 0;
880 } else { // If not specified, use 0.0.
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000881 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky9f856342009-04-12 20:47:23 +0000882 }
883
884 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
885 Builder.CreateStore(InitVal, Alloca);
886
887 // Remember the old variable binding so that we can restore the binding when
888 // we unrecurse.
889 OldBindings.push_back(NamedValues[VarName]);
890
891 // Remember this binding.
892 NamedValues[VarName] = Alloca;
893 }
894
895 // Codegen the body, now that all vars are in scope.
896 Value *BodyVal = Body->Codegen();
897 if (BodyVal == 0) return 0;
898
899 // Pop all our variables from scope.
900 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
901 NamedValues[VarNames[i].first] = OldBindings[i];
902
903 // Return the body computation.
904 return BodyVal;
905}
906
Nick Lewycky9f856342009-04-12 20:47:23 +0000907Function *PrototypeAST::Codegen() {
908 // Make the function type: double(double,double) etc.
Owen Anderson1d0be152009-08-13 21:58:54 +0000909 std::vector<const Type*> Doubles(Args.size(),
910 Type::getDoubleTy(getGlobalContext()));
911 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
912 Doubles, false);
Nick Lewycky9f856342009-04-12 20:47:23 +0000913
914 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
915
916 // If F conflicted, there was already something named 'Name'. If it has a
917 // body, don't allow redefinition or reextern.
918 if (F->getName() != Name) {
919 // Delete the one we just made and get the existing one.
920 F->eraseFromParent();
921 F = TheModule->getFunction(Name);
922
923 // If F already has a body, reject this.
924 if (!F->empty()) {
925 ErrorF("redefinition of function");
926 return 0;
927 }
928
929 // If F took a different number of args, reject.
930 if (F->arg_size() != Args.size()) {
931 ErrorF("redefinition of function with different # args");
932 return 0;
933 }
934 }
935
936 // Set names for all arguments.
937 unsigned Idx = 0;
938 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
939 ++AI, ++Idx)
940 AI->setName(Args[Idx]);
941
942 return F;
943}
944
945/// CreateArgumentAllocas - Create an alloca for each argument and register the
946/// argument in the symbol table so that references to it will succeed.
947void PrototypeAST::CreateArgumentAllocas(Function *F) {
948 Function::arg_iterator AI = F->arg_begin();
949 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
950 // Create an alloca for this variable.
951 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
952
953 // Store the initial value into the alloca.
954 Builder.CreateStore(AI, Alloca);
955
956 // Add arguments to variable symbol table.
957 NamedValues[Args[Idx]] = Alloca;
958 }
959}
960
Nick Lewycky9f856342009-04-12 20:47:23 +0000961Function *FunctionAST::Codegen() {
962 NamedValues.clear();
963
964 Function *TheFunction = Proto->Codegen();
965 if (TheFunction == 0)
966 return 0;
967
968 // If this is an operator, install it.
969 if (Proto->isBinaryOp())
970 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
971
972 // Create a new basic block to start insertion into.
Owen Anderson1d0be152009-08-13 21:58:54 +0000973 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky9f856342009-04-12 20:47:23 +0000974 Builder.SetInsertPoint(BB);
975
976 // Add all arguments to the symbol table and create their allocas.
977 Proto->CreateArgumentAllocas(TheFunction);
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000978
Nick Lewycky9f856342009-04-12 20:47:23 +0000979 if (Value *RetVal = Body->Codegen()) {
980 // Finish off the function.
981 Builder.CreateRet(RetVal);
982
983 // Validate the generated code, checking for consistency.
984 verifyFunction(*TheFunction);
985
986 // Optimize the function.
987 TheFPM->run(*TheFunction);
988
989 return TheFunction;
990 }
991
992 // Error reading body, remove function.
993 TheFunction->eraseFromParent();
994
995 if (Proto->isBinaryOp())
996 BinopPrecedence.erase(Proto->getOperatorName());
997 return 0;
998}
999
1000//===----------------------------------------------------------------------===//
1001// Top-Level parsing and JIT Driver
1002//===----------------------------------------------------------------------===//
1003
1004static ExecutionEngine *TheExecutionEngine;
1005
1006static void HandleDefinition() {
1007 if (FunctionAST *F = ParseDefinition()) {
1008 if (Function *LF = F->Codegen()) {
1009 fprintf(stderr, "Read function definition:");
1010 LF->dump();
1011 }
1012 } else {
1013 // Skip token for error recovery.
1014 getNextToken();
1015 }
1016}
1017
1018static void HandleExtern() {
1019 if (PrototypeAST *P = ParseExtern()) {
1020 if (Function *F = P->Codegen()) {
1021 fprintf(stderr, "Read extern: ");
1022 F->dump();
1023 }
1024 } else {
1025 // Skip token for error recovery.
1026 getNextToken();
1027 }
1028}
1029
1030static void HandleTopLevelExpression() {
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001031 // Evaluate a top-level expression into an anonymous function.
Nick Lewycky9f856342009-04-12 20:47:23 +00001032 if (FunctionAST *F = ParseTopLevelExpr()) {
1033 if (Function *LF = F->Codegen()) {
1034 // JIT the function, returning a function pointer.
1035 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1036
1037 // Cast it to the right type (takes no arguments, returns a double) so we
1038 // can call it as a native function.
Chris Lattnerd25bff62009-04-15 00:16:05 +00001039 double (*FP)() = (double (*)())(intptr_t)FPtr;
Nick Lewycky9f856342009-04-12 20:47:23 +00001040 fprintf(stderr, "Evaluated to %f\n", FP());
1041 }
1042 } else {
1043 // Skip token for error recovery.
1044 getNextToken();
1045 }
1046}
1047
1048/// top ::= definition | external | expression | ';'
1049static void MainLoop() {
1050 while (1) {
1051 fprintf(stderr, "ready> ");
1052 switch (CurTok) {
1053 case tok_eof: return;
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001054 case ';': getNextToken(); break; // ignore top-level semicolons.
Nick Lewycky9f856342009-04-12 20:47:23 +00001055 case tok_def: HandleDefinition(); break;
1056 case tok_extern: HandleExtern(); break;
1057 default: HandleTopLevelExpression(); break;
1058 }
1059 }
1060}
1061
Nick Lewycky9f856342009-04-12 20:47:23 +00001062//===----------------------------------------------------------------------===//
1063// "Library" functions that can be "extern'd" from user code.
1064//===----------------------------------------------------------------------===//
1065
1066/// putchard - putchar that takes a double and returns 0.
1067extern "C"
1068double putchard(double X) {
1069 putchar((char)X);
1070 return 0;
1071}
1072
1073/// printd - printf that takes a double prints it as "%f\n", returning 0.
1074extern "C"
1075double printd(double X) {
1076 printf("%f\n", X);
1077 return 0;
1078}
1079
1080//===----------------------------------------------------------------------===//
1081// Main driver code.
1082//===----------------------------------------------------------------------===//
1083
1084int main() {
Chris Lattnerda062882009-06-17 16:48:44 +00001085 InitializeNativeTarget();
Owen Anderson914e50c2009-07-16 19:05:41 +00001086 LLVMContext &Context = getGlobalContext();
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001087
Nick Lewycky9f856342009-04-12 20:47:23 +00001088 // Install standard binary operators.
1089 // 1 is lowest precedence.
1090 BinopPrecedence['='] = 2;
1091 BinopPrecedence['<'] = 10;
1092 BinopPrecedence['+'] = 20;
1093 BinopPrecedence['-'] = 20;
1094 BinopPrecedence['*'] = 40; // highest.
1095
1096 // Prime the first token.
1097 fprintf(stderr, "ready> ");
1098 getNextToken();
1099
1100 // Make the module, which holds all the code.
Owen Anderson31895e72009-07-01 21:22:36 +00001101 TheModule = new Module("my cool jit", Context);
Nick Lewycky9f856342009-04-12 20:47:23 +00001102
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001103 // Create the JIT. This takes ownership of the module.
Jeffrey Yasskin42fc5582010-02-11 19:15:20 +00001104 std::string ErrStr;
1105 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
1106 if (!TheExecutionEngine) {
1107 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1108 exit(1);
1109 }
Reid Kleckner9e6f3f22009-08-24 05:42:21 +00001110
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001111 FunctionPassManager OurFPM(TheModule);
Nick Lewycky9f856342009-04-12 20:47:23 +00001112
Reid Kleckner60130f02009-08-26 20:58:25 +00001113 // Set up the optimizer pipeline. Start with registering info about how the
1114 // target lays out data structures.
1115 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
Dan Gohmandfa1a792010-11-15 18:41:10 +00001116 // Provide basic AliasAnalysis support for GVN.
1117 OurFPM.add(createBasicAliasAnalysisPass());
Reid Kleckner60130f02009-08-26 20:58:25 +00001118 // Promote allocas to registers.
1119 OurFPM.add(createPromoteMemoryToRegisterPass());
1120 // Do simple "peephole" optimizations and bit-twiddling optzns.
1121 OurFPM.add(createInstructionCombiningPass());
1122 // Reassociate expressions.
1123 OurFPM.add(createReassociatePass());
1124 // Eliminate Common SubExpressions.
1125 OurFPM.add(createGVNPass());
1126 // Simplify the control flow graph (deleting unreachable blocks, etc).
1127 OurFPM.add(createCFGSimplificationPass());
Eli Friedman8e9b1712009-07-20 14:50:07 +00001128
Reid Kleckner60130f02009-08-26 20:58:25 +00001129 OurFPM.doInitialization();
Nick Lewycky9f856342009-04-12 20:47:23 +00001130
Reid Kleckner60130f02009-08-26 20:58:25 +00001131 // Set the global so the code gen can use this.
1132 TheFPM = &OurFPM;
1133
1134 // Run the main "interpreter loop" now.
1135 MainLoop();
1136
1137 TheFPM = 0;
1138
1139 // Print out all of the generated code.
1140 TheModule->dump();
1141
Nick Lewycky9f856342009-04-12 20:47:23 +00001142 return 0;
1143}