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