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