blob: c75014a69ba40ff632fc1c811a62224e0ec7d723 [file] [log] [blame]
Nick Lewycky9f856342009-04-12 20:47:23 +00001#include "llvm/DerivedTypes.h"
2#include "llvm/ExecutionEngine/ExecutionEngine.h"
3#include "llvm/Module.h"
4#include "llvm/ModuleProvider.h"
5#include "llvm/PassManager.h"
6#include "llvm/Analysis/Verifier.h"
7#include "llvm/Target/TargetData.h"
Chris Lattnerda062882009-06-17 16:48:44 +00008#include "llvm/Target/TargetSelect.h"
Nick Lewycky9f856342009-04-12 20:47:23 +00009#include "llvm/Transforms/Scalar.h"
10#include "llvm/Support/IRBuilder.h"
11#include <cstdio>
12#include <string>
13#include <map>
14#include <vector>
15using namespace llvm;
16
17//===----------------------------------------------------------------------===//
18// Lexer
19//===----------------------------------------------------------------------===//
20
21// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
22// of these for known things.
23enum Token {
24 tok_eof = -1,
25
26 // commands
27 tok_def = -2, tok_extern = -3,
28
29 // primary
30 tok_identifier = -4, tok_number = -5,
31
32 // control
33 tok_if = -6, tok_then = -7, tok_else = -8,
34 tok_for = -9, tok_in = -10,
35
36 // operators
37 tok_binary = -11, tok_unary = -12,
38
39 // var definition
40 tok_var = -13
41};
42
43static std::string IdentifierStr; // Filled in if tok_identifier
44static double NumVal; // Filled in if tok_number
45
46/// gettok - Return the next token from standard input.
47static int gettok() {
48 static int LastChar = ' ';
49
50 // Skip any whitespace.
51 while (isspace(LastChar))
52 LastChar = getchar();
53
54 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
55 IdentifierStr = LastChar;
56 while (isalnum((LastChar = getchar())))
57 IdentifierStr += LastChar;
58
59 if (IdentifierStr == "def") return tok_def;
60 if (IdentifierStr == "extern") return tok_extern;
61 if (IdentifierStr == "if") return tok_if;
62 if (IdentifierStr == "then") return tok_then;
63 if (IdentifierStr == "else") return tok_else;
64 if (IdentifierStr == "for") return tok_for;
65 if (IdentifierStr == "in") return tok_in;
66 if (IdentifierStr == "binary") return tok_binary;
67 if (IdentifierStr == "unary") return tok_unary;
68 if (IdentifierStr == "var") return tok_var;
69 return tok_identifier;
70 }
71
72 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
73 std::string NumStr;
74 do {
75 NumStr += LastChar;
76 LastChar = getchar();
77 } while (isdigit(LastChar) || LastChar == '.');
78
79 NumVal = strtod(NumStr.c_str(), 0);
80 return tok_number;
81 }
82
83 if (LastChar == '#') {
84 // Comment until end of line.
85 do LastChar = getchar();
86 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
87
88 if (LastChar != EOF)
89 return gettok();
90 }
91
92 // Check for end of file. Don't eat the EOF.
93 if (LastChar == EOF)
94 return tok_eof;
95
96 // Otherwise, just return the character as its ascii value.
97 int ThisChar = LastChar;
98 LastChar = getchar();
99 return ThisChar;
100}
101
102//===----------------------------------------------------------------------===//
103// Abstract Syntax Tree (aka Parse Tree)
104//===----------------------------------------------------------------------===//
105
106/// ExprAST - Base class for all expression nodes.
107class ExprAST {
108public:
109 virtual ~ExprAST() {}
110 virtual Value *Codegen() = 0;
111};
112
113/// NumberExprAST - Expression class for numeric literals like "1.0".
114class NumberExprAST : public ExprAST {
115 double Val;
116public:
117 NumberExprAST(double val) : Val(val) {}
118 virtual Value *Codegen();
119};
120
121/// VariableExprAST - Expression class for referencing a variable, like "a".
122class VariableExprAST : public ExprAST {
123 std::string Name;
124public:
125 VariableExprAST(const std::string &name) : Name(name) {}
126 const std::string &getName() const { return Name; }
127 virtual Value *Codegen();
128};
129
130/// UnaryExprAST - Expression class for a unary operator.
131class UnaryExprAST : public ExprAST {
132 char Opcode;
133 ExprAST *Operand;
134public:
135 UnaryExprAST(char opcode, ExprAST *operand)
136 : Opcode(opcode), Operand(operand) {}
137 virtual Value *Codegen();
138};
139
140/// BinaryExprAST - Expression class for a binary operator.
141class BinaryExprAST : public ExprAST {
142 char Op;
143 ExprAST *LHS, *RHS;
144public:
145 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
146 : Op(op), LHS(lhs), RHS(rhs) {}
147 virtual Value *Codegen();
148};
149
150/// CallExprAST - Expression class for function calls.
151class CallExprAST : public ExprAST {
152 std::string Callee;
153 std::vector<ExprAST*> Args;
154public:
155 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
156 : Callee(callee), Args(args) {}
157 virtual Value *Codegen();
158};
159
160/// IfExprAST - Expression class for if/then/else.
161class IfExprAST : public ExprAST {
162 ExprAST *Cond, *Then, *Else;
163public:
164 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
165 : Cond(cond), Then(then), Else(_else) {}
166 virtual Value *Codegen();
167};
168
169/// ForExprAST - Expression class for for/in.
170class ForExprAST : public ExprAST {
171 std::string VarName;
172 ExprAST *Start, *End, *Step, *Body;
173public:
174 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
175 ExprAST *step, ExprAST *body)
176 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
177 virtual Value *Codegen();
178};
179
180/// VarExprAST - Expression class for var/in
181class VarExprAST : public ExprAST {
182 std::vector<std::pair<std::string, ExprAST*> > VarNames;
183 ExprAST *Body;
184public:
185 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
186 ExprAST *body)
187 : VarNames(varnames), Body(body) {}
188
189 virtual Value *Codegen();
190};
191
192/// PrototypeAST - This class represents the "prototype" for a function,
193/// which captures its argument names as well as if it is an operator.
194class PrototypeAST {
195 std::string Name;
196 std::vector<std::string> Args;
197 bool isOperator;
198 unsigned Precedence; // Precedence if a binary op.
199public:
200 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
201 bool isoperator = false, unsigned prec = 0)
202 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
203
204 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
205 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
206
207 char getOperatorName() const {
208 assert(isUnaryOp() || isBinaryOp());
209 return Name[Name.size()-1];
210 }
211
212 unsigned getBinaryPrecedence() const { return Precedence; }
213
214 Function *Codegen();
215
216 void CreateArgumentAllocas(Function *F);
217};
218
219/// FunctionAST - This class represents a function definition itself.
220class FunctionAST {
221 PrototypeAST *Proto;
222 ExprAST *Body;
223public:
224 FunctionAST(PrototypeAST *proto, ExprAST *body)
225 : Proto(proto), Body(body) {}
226
227 Function *Codegen();
228};
229
230//===----------------------------------------------------------------------===//
231// Parser
232//===----------------------------------------------------------------------===//
233
234/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
235/// token the parser it looking at. getNextToken reads another token from the
236/// lexer and updates CurTok with its results.
237static int CurTok;
238static int getNextToken() {
239 return CurTok = gettok();
240}
241
242/// BinopPrecedence - This holds the precedence for each binary operator that is
243/// defined.
244static std::map<char, int> BinopPrecedence;
245
246/// GetTokPrecedence - Get the precedence of the pending binary operator token.
247static int GetTokPrecedence() {
248 if (!isascii(CurTok))
249 return -1;
250
251 // Make sure it's a declared binop.
252 int TokPrec = BinopPrecedence[CurTok];
253 if (TokPrec <= 0) return -1;
254 return TokPrec;
255}
256
257/// Error* - These are little helper functions for error handling.
258ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
259PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
260FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
261
262static ExprAST *ParseExpression();
263
264/// identifierexpr
265/// ::= identifier
266/// ::= identifier '(' expression* ')'
267static ExprAST *ParseIdentifierExpr() {
268 std::string IdName = IdentifierStr;
269
270 getNextToken(); // eat identifier.
271
272 if (CurTok != '(') // Simple variable ref.
273 return new VariableExprAST(IdName);
274
275 // Call.
276 getNextToken(); // eat (
277 std::vector<ExprAST*> Args;
278 if (CurTok != ')') {
279 while (1) {
280 ExprAST *Arg = ParseExpression();
281 if (!Arg) return 0;
282 Args.push_back(Arg);
283
284 if (CurTok == ')') break;
285
286 if (CurTok != ',')
287 return Error("Expected ')' or ',' in argument list");
288 getNextToken();
289 }
290 }
291
292 // Eat the ')'.
293 getNextToken();
294
295 return new CallExprAST(IdName, Args);
296}
297
298/// numberexpr ::= number
299static ExprAST *ParseNumberExpr() {
300 ExprAST *Result = new NumberExprAST(NumVal);
301 getNextToken(); // consume the number
302 return Result;
303}
304
305/// parenexpr ::= '(' expression ')'
306static ExprAST *ParseParenExpr() {
307 getNextToken(); // eat (.
308 ExprAST *V = ParseExpression();
309 if (!V) return 0;
310
311 if (CurTok != ')')
312 return Error("expected ')'");
313 getNextToken(); // eat ).
314 return V;
315}
316
317/// ifexpr ::= 'if' expression 'then' expression 'else' expression
318static ExprAST *ParseIfExpr() {
319 getNextToken(); // eat the if.
320
321 // condition.
322 ExprAST *Cond = ParseExpression();
323 if (!Cond) return 0;
324
325 if (CurTok != tok_then)
326 return Error("expected then");
327 getNextToken(); // eat the then
328
329 ExprAST *Then = ParseExpression();
330 if (Then == 0) return 0;
331
332 if (CurTok != tok_else)
333 return Error("expected else");
334
335 getNextToken();
336
337 ExprAST *Else = ParseExpression();
338 if (!Else) return 0;
339
340 return new IfExprAST(Cond, Then, Else);
341}
342
343/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
344static ExprAST *ParseForExpr() {
345 getNextToken(); // eat the for.
346
347 if (CurTok != tok_identifier)
348 return Error("expected identifier after for");
349
350 std::string IdName = IdentifierStr;
351 getNextToken(); // eat identifier.
352
353 if (CurTok != '=')
354 return Error("expected '=' after for");
355 getNextToken(); // eat '='.
356
357
358 ExprAST *Start = ParseExpression();
359 if (Start == 0) return 0;
360 if (CurTok != ',')
361 return Error("expected ',' after for start value");
362 getNextToken();
363
364 ExprAST *End = ParseExpression();
365 if (End == 0) return 0;
366
367 // The step value is optional.
368 ExprAST *Step = 0;
369 if (CurTok == ',') {
370 getNextToken();
371 Step = ParseExpression();
372 if (Step == 0) return 0;
373 }
374
375 if (CurTok != tok_in)
376 return Error("expected 'in' after for");
377 getNextToken(); // eat 'in'.
378
379 ExprAST *Body = ParseExpression();
380 if (Body == 0) return 0;
381
382 return new ForExprAST(IdName, Start, End, Step, Body);
383}
384
385/// varexpr ::= 'var' identifier ('=' expression)?
386// (',' identifier ('=' expression)?)* 'in' expression
387static ExprAST *ParseVarExpr() {
388 getNextToken(); // eat the var.
389
390 std::vector<std::pair<std::string, ExprAST*> > VarNames;
391
392 // At least one variable name is required.
393 if (CurTok != tok_identifier)
394 return Error("expected identifier after var");
395
396 while (1) {
397 std::string Name = IdentifierStr;
398 getNextToken(); // eat identifier.
399
400 // Read the optional initializer.
401 ExprAST *Init = 0;
402 if (CurTok == '=') {
403 getNextToken(); // eat the '='.
404
405 Init = ParseExpression();
406 if (Init == 0) return 0;
407 }
408
409 VarNames.push_back(std::make_pair(Name, Init));
410
411 // End of var list, exit loop.
412 if (CurTok != ',') break;
413 getNextToken(); // eat the ','.
414
415 if (CurTok != tok_identifier)
416 return Error("expected identifier list after var");
417 }
418
419 // At this point, we have to have 'in'.
420 if (CurTok != tok_in)
421 return Error("expected 'in' keyword after 'var'");
422 getNextToken(); // eat 'in'.
423
424 ExprAST *Body = ParseExpression();
425 if (Body == 0) return 0;
426
427 return new VarExprAST(VarNames, Body);
428}
429
430
431/// 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
Bill Wendling71267022009-04-13 19:45:05 +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;
606static IRBuilder<> Builder;
607static 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());
618 return TmpB.CreateAlloca(Type::DoubleTy, 0, VarName.c_str());
619}
620
621
622Value *NumberExprAST::Codegen() {
623 return ConstantFP::get(APFloat(Val));
624}
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
646
647Value *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
666
667 Value *L = LHS->Codegen();
668 Value *R = RHS->Codegen();
669 if (L == 0 || R == 0) return 0;
670
671 switch (Op) {
672 case '+': return Builder.CreateAdd(L, R, "addtmp");
673 case '-': return Builder.CreateSub(L, R, "subtmp");
674 case '*': return Builder.CreateMul(L, R, "multmp");
675 case '<':
676 L = Builder.CreateFCmpULT(L, R, "cmptmp");
677 // Convert bool 0/1 to double 0.0 or 1.0
678 return Builder.CreateUIToFP(L, Type::DoubleTy, "booltmp");
679 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,
716 ConstantFP::get(APFloat(0.0)),
717 "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.
723 BasicBlock *ThenBB = BasicBlock::Create("then", TheFunction);
724 BasicBlock *ElseBB = BasicBlock::Create("else");
725 BasicBlock *MergeBB = BasicBlock::Create("ifcont");
726
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);
753 PHINode *PN = Builder.CreatePHI(Type::DoubleTy, "iftmp");
754
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.
Nick Lewycky9f856342009-04-12 20:47:23 +0000795 BasicBlock *LoopBB = BasicBlock::Create("loop", TheFunction);
796
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.
821 StepVal = ConstantFP::get(APFloat(1.0));
822 }
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,
836 ConstantFP::get(APFloat(0.0)),
837 "loopcond");
838
839 // Create the "after loop" block and insert it.
Nick Lewycky9f856342009-04-12 20:47:23 +0000840 BasicBlock *AfterBB = BasicBlock::Create("afterloop", TheFunction);
841
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.
856 return Constant::getNullValue(Type::DoubleTy);
857}
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.
879 InitVal = ConstantFP::get(APFloat(0.0));
880 }
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
905
906Function *PrototypeAST::Codegen() {
907 // Make the function type: double(double,double) etc.
908 std::vector<const Type*> Doubles(Args.size(), Type::DoubleTy);
909 FunctionType *FT = FunctionType::get(Type::DoubleTy, Doubles, false);
910
911 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
912
913 // If F conflicted, there was already something named 'Name'. If it has a
914 // body, don't allow redefinition or reextern.
915 if (F->getName() != Name) {
916 // Delete the one we just made and get the existing one.
917 F->eraseFromParent();
918 F = TheModule->getFunction(Name);
919
920 // If F already has a body, reject this.
921 if (!F->empty()) {
922 ErrorF("redefinition of function");
923 return 0;
924 }
925
926 // If F took a different number of args, reject.
927 if (F->arg_size() != Args.size()) {
928 ErrorF("redefinition of function with different # args");
929 return 0;
930 }
931 }
932
933 // Set names for all arguments.
934 unsigned Idx = 0;
935 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
936 ++AI, ++Idx)
937 AI->setName(Args[Idx]);
938
939 return F;
940}
941
942/// CreateArgumentAllocas - Create an alloca for each argument and register the
943/// argument in the symbol table so that references to it will succeed.
944void PrototypeAST::CreateArgumentAllocas(Function *F) {
945 Function::arg_iterator AI = F->arg_begin();
946 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
947 // Create an alloca for this variable.
948 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
949
950 // Store the initial value into the alloca.
951 Builder.CreateStore(AI, Alloca);
952
953 // Add arguments to variable symbol table.
954 NamedValues[Args[Idx]] = Alloca;
955 }
956}
957
958
959Function *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.
971 BasicBlock *BB = BasicBlock::Create("entry", TheFunction);
972 Builder.SetInsertPoint(BB);
973
974 // Add all arguments to the symbol table and create their allocas.
975 Proto->CreateArgumentAllocas(TheFunction);
976
977 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() {
1029 // Evaluate a top level expression into an anonymous function.
1030 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;
1052 case ';': getNextToken(); break; // ignore top level semicolons.
1053 case tok_def: HandleDefinition(); break;
1054 case tok_extern: HandleExtern(); break;
1055 default: HandleTopLevelExpression(); break;
1056 }
1057 }
1058}
1059
1060
1061
1062//===----------------------------------------------------------------------===//
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();
1086
Nick Lewycky9f856342009-04-12 20:47:23 +00001087 // Install standard binary operators.
1088 // 1 is lowest precedence.
1089 BinopPrecedence['='] = 2;
1090 BinopPrecedence['<'] = 10;
1091 BinopPrecedence['+'] = 20;
1092 BinopPrecedence['-'] = 20;
1093 BinopPrecedence['*'] = 40; // highest.
1094
1095 // Prime the first token.
1096 fprintf(stderr, "ready> ");
1097 getNextToken();
1098
1099 // Make the module, which holds all the code.
1100 TheModule = new Module("my cool jit");
1101
1102 // Create the JIT.
1103 TheExecutionEngine = ExecutionEngine::create(TheModule);
1104
1105 {
1106 ExistingModuleProvider OurModuleProvider(TheModule);
1107 FunctionPassManager OurFPM(&OurModuleProvider);
1108
1109 // Set up the optimizer pipeline. Start with registering info about how the
1110 // target lays out data structures.
1111 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
1112 // Promote allocas to registers.
1113 OurFPM.add(createPromoteMemoryToRegisterPass());
1114 // Do simple "peephole" optimizations and bit-twiddling optzns.
1115 OurFPM.add(createInstructionCombiningPass());
1116 // Reassociate expressions.
1117 OurFPM.add(createReassociatePass());
1118 // Eliminate Common SubExpressions.
1119 OurFPM.add(createGVNPass());
1120 // Simplify the control flow graph (deleting unreachable blocks, etc).
1121 OurFPM.add(createCFGSimplificationPass());
1122
1123 // Set the global so the code gen can use this.
1124 TheFPM = &OurFPM;
1125
1126 // Run the main "interpreter loop" now.
1127 MainLoop();
1128
1129 TheFPM = 0;
1130
1131 // Print out all of the generated code.
1132 TheModule->dump();
1133
1134 } // Free module provider (and thus the module) and pass manager.
1135
1136 return 0;
1137}
1138