blob: 5ffc4ca55b3be066f6c08b5c2e19d37a89d10bd9 [file] [log] [blame]
NAKAMURA Takumi85c9bac2015-03-02 01:04:34 +00001#include "llvm/ADT/STLExtras.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00002#include "llvm/ADT/Triple.h"
3#include "llvm/Analysis/Passes.h"
4#include "llvm/ExecutionEngine/ExecutionEngine.h"
5#include "llvm/ExecutionEngine/MCJIT.h"
6#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Chandler Carruth1f832f72015-02-13 09:14:30 +00007#include "llvm/IR/DIBuilder.h"
Eric Christopher05917fa2014-12-08 18:00:47 +00008#include "llvm/IR/DataLayout.h"
9#include "llvm/IR/DerivedTypes.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000010#include "llvm/IR/IRBuilder.h"
11#include "llvm/IR/LLVMContext.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000012#include "llvm/IR/LegacyPassManager.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000013#include "llvm/IR/Module.h"
14#include "llvm/IR/Verifier.h"
Eric Christopher05917fa2014-12-08 18:00:47 +000015#include "llvm/Support/Host.h"
16#include "llvm/Support/TargetSelect.h"
17#include "llvm/Transforms/Scalar.h"
18#include <cctype>
19#include <cstdio>
Chandler Carruth1f832f72015-02-13 09:14:30 +000020#include <iostream>
Eric Christopher05917fa2014-12-08 18:00:47 +000021#include <map>
22#include <string>
23#include <vector>
Eric Christopher05917fa2014-12-08 18:00:47 +000024using namespace llvm;
25
26//===----------------------------------------------------------------------===//
27// Lexer
28//===----------------------------------------------------------------------===//
29
30// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
31// of these for known things.
32enum Token {
33 tok_eof = -1,
34
35 // commands
36 tok_def = -2,
37 tok_extern = -3,
38
39 // primary
40 tok_identifier = -4,
41 tok_number = -5,
42
43 // control
44 tok_if = -6,
45 tok_then = -7,
46 tok_else = -8,
47 tok_for = -9,
48 tok_in = -10,
49
50 // operators
51 tok_binary = -11,
52 tok_unary = -12,
53
54 // var definition
55 tok_var = -13
56};
57
58std::string getTokName(int Tok) {
59 switch (Tok) {
60 case tok_eof:
61 return "eof";
62 case tok_def:
63 return "def";
64 case tok_extern:
65 return "extern";
66 case tok_identifier:
67 return "identifier";
68 case tok_number:
69 return "number";
70 case tok_if:
71 return "if";
72 case tok_then:
73 return "then";
74 case tok_else:
75 return "else";
76 case tok_for:
77 return "for";
78 case tok_in:
79 return "in";
80 case tok_binary:
81 return "binary";
82 case tok_unary:
83 return "unary";
84 case tok_var:
85 return "var";
86 }
87 return std::string(1, (char)Tok);
88}
89
90namespace {
91class PrototypeAST;
92class ExprAST;
93}
94static IRBuilder<> Builder(getGlobalContext());
95struct DebugInfo {
96 DICompileUnit TheCU;
97 DIType DblTy;
98 std::vector<DIScope *> LexicalBlocks;
99 std::map<const PrototypeAST *, DIScope> FnScopeMap;
100
101 void emitLocation(ExprAST *AST);
102 DIType getDoubleTy();
103} KSDbgInfo;
104
105static std::string IdentifierStr; // Filled in if tok_identifier
106static double NumVal; // Filled in if tok_number
107struct SourceLocation {
108 int Line;
109 int Col;
110};
111static SourceLocation CurLoc;
112static SourceLocation LexLoc = { 1, 0 };
113
114static int advance() {
115 int LastChar = getchar();
116
117 if (LastChar == '\n' || LastChar == '\r') {
118 LexLoc.Line++;
119 LexLoc.Col = 0;
120 } else
121 LexLoc.Col++;
122 return LastChar;
123}
124
125/// gettok - Return the next token from standard input.
126static int gettok() {
127 static int LastChar = ' ';
128
129 // Skip any whitespace.
130 while (isspace(LastChar))
131 LastChar = advance();
132
133 CurLoc = LexLoc;
134
135 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
136 IdentifierStr = LastChar;
137 while (isalnum((LastChar = advance())))
138 IdentifierStr += LastChar;
139
140 if (IdentifierStr == "def")
141 return tok_def;
142 if (IdentifierStr == "extern")
143 return tok_extern;
144 if (IdentifierStr == "if")
145 return tok_if;
146 if (IdentifierStr == "then")
147 return tok_then;
148 if (IdentifierStr == "else")
149 return tok_else;
150 if (IdentifierStr == "for")
151 return tok_for;
152 if (IdentifierStr == "in")
153 return tok_in;
154 if (IdentifierStr == "binary")
155 return tok_binary;
156 if (IdentifierStr == "unary")
157 return tok_unary;
158 if (IdentifierStr == "var")
159 return tok_var;
160 return tok_identifier;
161 }
162
163 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
164 std::string NumStr;
165 do {
166 NumStr += LastChar;
167 LastChar = advance();
168 } while (isdigit(LastChar) || LastChar == '.');
169
170 NumVal = strtod(NumStr.c_str(), 0);
171 return tok_number;
172 }
173
174 if (LastChar == '#') {
175 // Comment until end of line.
176 do
177 LastChar = advance();
178 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
179
180 if (LastChar != EOF)
181 return gettok();
182 }
183
184 // Check for end of file. Don't eat the EOF.
185 if (LastChar == EOF)
186 return tok_eof;
187
188 // Otherwise, just return the character as its ascii value.
189 int ThisChar = LastChar;
190 LastChar = advance();
191 return ThisChar;
192}
193
194//===----------------------------------------------------------------------===//
195// Abstract Syntax Tree (aka Parse Tree)
196//===----------------------------------------------------------------------===//
197namespace {
198
199std::ostream &indent(std::ostream &O, int size) {
200 return O << std::string(size, ' ');
201}
202
203/// ExprAST - Base class for all expression nodes.
204class ExprAST {
205 SourceLocation Loc;
206
207public:
208 int getLine() const { return Loc.Line; }
209 int getCol() const { return Loc.Col; }
210 ExprAST(SourceLocation Loc = CurLoc) : Loc(Loc) {}
211 virtual std::ostream &dump(std::ostream &out, int ind) {
212 return out << ':' << getLine() << ':' << getCol() << '\n';
213 }
214 virtual ~ExprAST() {}
215 virtual Value *Codegen() = 0;
216};
217
218/// NumberExprAST - Expression class for numeric literals like "1.0".
219class NumberExprAST : public ExprAST {
220 double Val;
221
222public:
223 NumberExprAST(double val) : Val(val) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000224 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000225 return ExprAST::dump(out << Val, ind);
226 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000227 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000228};
229
230/// VariableExprAST - Expression class for referencing a variable, like "a".
231class VariableExprAST : public ExprAST {
232 std::string Name;
233
234public:
235 VariableExprAST(SourceLocation Loc, const std::string &name)
236 : ExprAST(Loc), Name(name) {}
237 const std::string &getName() const { return Name; }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000238 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000239 return ExprAST::dump(out << Name, ind);
240 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000241 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000242};
243
244/// UnaryExprAST - Expression class for a unary operator.
245class UnaryExprAST : public ExprAST {
246 char Opcode;
247 ExprAST *Operand;
248
249public:
250 UnaryExprAST(char opcode, ExprAST *operand)
251 : Opcode(opcode), Operand(operand) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000252 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000253 ExprAST::dump(out << "unary" << Opcode, ind);
254 Operand->dump(out, ind + 1);
255 return out;
256 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000257 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000258};
259
260/// BinaryExprAST - Expression class for a binary operator.
261class BinaryExprAST : public ExprAST {
262 char Op;
263 ExprAST *LHS, *RHS;
264
265public:
266 BinaryExprAST(SourceLocation Loc, char op, ExprAST *lhs, ExprAST *rhs)
267 : ExprAST(Loc), Op(op), LHS(lhs), RHS(rhs) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000268 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000269 ExprAST::dump(out << "binary" << Op, ind);
270 LHS->dump(indent(out, ind) << "LHS:", ind + 1);
271 RHS->dump(indent(out, ind) << "RHS:", ind + 1);
272 return out;
273 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000274 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000275};
276
277/// CallExprAST - Expression class for function calls.
278class CallExprAST : public ExprAST {
279 std::string Callee;
280 std::vector<ExprAST *> Args;
281
282public:
283 CallExprAST(SourceLocation Loc, const std::string &callee,
284 std::vector<ExprAST *> &args)
285 : ExprAST(Loc), Callee(callee), Args(args) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000286 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000287 ExprAST::dump(out << "call " << Callee, ind);
288 for (ExprAST *Arg : Args)
289 Arg->dump(indent(out, ind + 1), ind + 1);
290 return out;
291 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000292 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000293};
294
295/// IfExprAST - Expression class for if/then/else.
296class IfExprAST : public ExprAST {
297 ExprAST *Cond, *Then, *Else;
298
299public:
300 IfExprAST(SourceLocation Loc, ExprAST *cond, ExprAST *then, ExprAST *_else)
301 : ExprAST(Loc), Cond(cond), Then(then), Else(_else) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000302 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000303 ExprAST::dump(out << "if", ind);
304 Cond->dump(indent(out, ind) << "Cond:", ind + 1);
305 Then->dump(indent(out, ind) << "Then:", ind + 1);
306 Else->dump(indent(out, ind) << "Else:", ind + 1);
307 return out;
308 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000309 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000310};
311
312/// ForExprAST - Expression class for for/in.
313class ForExprAST : public ExprAST {
314 std::string VarName;
315 ExprAST *Start, *End, *Step, *Body;
316
317public:
318 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
319 ExprAST *step, ExprAST *body)
320 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000321 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000322 ExprAST::dump(out << "for", ind);
323 Start->dump(indent(out, ind) << "Cond:", ind + 1);
324 End->dump(indent(out, ind) << "End:", ind + 1);
325 Step->dump(indent(out, ind) << "Step:", ind + 1);
326 Body->dump(indent(out, ind) << "Body:", ind + 1);
327 return out;
328 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000329 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000330};
331
332/// VarExprAST - Expression class for var/in
333class VarExprAST : public ExprAST {
334 std::vector<std::pair<std::string, ExprAST *> > VarNames;
335 ExprAST *Body;
336
337public:
338 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
339 ExprAST *body)
340 : VarNames(varnames), Body(body) {}
341
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000342 std::ostream &dump(std::ostream &out, int ind) override {
Eric Christopher05917fa2014-12-08 18:00:47 +0000343 ExprAST::dump(out << "var", ind);
344 for (const auto &NamedVar : VarNames)
345 NamedVar.second->dump(indent(out, ind) << NamedVar.first << ':', ind + 1);
346 Body->dump(indent(out, ind) << "Body:", ind + 1);
347 return out;
348 }
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000349 Value *Codegen() override;
Eric Christopher05917fa2014-12-08 18:00:47 +0000350};
351
352/// PrototypeAST - This class represents the "prototype" for a function,
353/// which captures its argument names as well as if it is an operator.
354class PrototypeAST {
355 std::string Name;
356 std::vector<std::string> Args;
357 bool isOperator;
358 unsigned Precedence; // Precedence if a binary op.
359 int Line;
360
361public:
362 PrototypeAST(SourceLocation Loc, const std::string &name,
363 const std::vector<std::string> &args, bool isoperator = false,
364 unsigned prec = 0)
365 : Name(name), Args(args), isOperator(isoperator), Precedence(prec),
366 Line(Loc.Line) {}
367
368 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
369 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
370
371 char getOperatorName() const {
372 assert(isUnaryOp() || isBinaryOp());
373 return Name[Name.size() - 1];
374 }
375
376 unsigned getBinaryPrecedence() const { return Precedence; }
377
378 Function *Codegen();
379
380 void CreateArgumentAllocas(Function *F);
381 const std::vector<std::string> &getArgs() const { return Args; }
382};
383
384/// FunctionAST - This class represents a function definition itself.
385class FunctionAST {
386 PrototypeAST *Proto;
387 ExprAST *Body;
388
389public:
390 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
391
392 std::ostream &dump(std::ostream &out, int ind) {
393 indent(out, ind) << "FunctionAST\n";
394 ++ind;
395 indent(out, ind) << "Body:";
396 return Body ? Body->dump(out, ind) : out << "null\n";
397 }
398
399 Function *Codegen();
400};
401} // end anonymous namespace
402
403//===----------------------------------------------------------------------===//
404// Parser
405//===----------------------------------------------------------------------===//
406
407/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
408/// token the parser is looking at. getNextToken reads another token from the
409/// lexer and updates CurTok with its results.
410static int CurTok;
411static int getNextToken() { return CurTok = gettok(); }
412
413/// BinopPrecedence - This holds the precedence for each binary operator that is
414/// defined.
415static std::map<char, int> BinopPrecedence;
416
417/// GetTokPrecedence - Get the precedence of the pending binary operator token.
418static int GetTokPrecedence() {
419 if (!isascii(CurTok))
420 return -1;
421
422 // Make sure it's a declared binop.
423 int TokPrec = BinopPrecedence[CurTok];
424 if (TokPrec <= 0)
425 return -1;
426 return TokPrec;
427}
428
429/// Error* - These are little helper functions for error handling.
430ExprAST *Error(const char *Str) {
431 fprintf(stderr, "Error: %s\n", Str);
432 return 0;
433}
434PrototypeAST *ErrorP(const char *Str) {
435 Error(Str);
436 return 0;
437}
438FunctionAST *ErrorF(const char *Str) {
439 Error(Str);
440 return 0;
441}
442
443static ExprAST *ParseExpression();
444
445/// identifierexpr
446/// ::= identifier
447/// ::= identifier '(' expression* ')'
448static ExprAST *ParseIdentifierExpr() {
449 std::string IdName = IdentifierStr;
450
451 SourceLocation LitLoc = CurLoc;
452
453 getNextToken(); // eat identifier.
454
455 if (CurTok != '(') // Simple variable ref.
456 return new VariableExprAST(LitLoc, IdName);
457
458 // Call.
459 getNextToken(); // eat (
460 std::vector<ExprAST *> Args;
461 if (CurTok != ')') {
462 while (1) {
463 ExprAST *Arg = ParseExpression();
464 if (!Arg)
465 return 0;
466 Args.push_back(Arg);
467
468 if (CurTok == ')')
469 break;
470
471 if (CurTok != ',')
472 return Error("Expected ')' or ',' in argument list");
473 getNextToken();
474 }
475 }
476
477 // Eat the ')'.
478 getNextToken();
479
480 return new CallExprAST(LitLoc, IdName, Args);
481}
482
483/// numberexpr ::= number
484static ExprAST *ParseNumberExpr() {
485 ExprAST *Result = new NumberExprAST(NumVal);
486 getNextToken(); // consume the number
487 return Result;
488}
489
490/// parenexpr ::= '(' expression ')'
491static ExprAST *ParseParenExpr() {
492 getNextToken(); // eat (.
493 ExprAST *V = ParseExpression();
494 if (!V)
495 return 0;
496
497 if (CurTok != ')')
498 return Error("expected ')'");
499 getNextToken(); // eat ).
500 return V;
501}
502
503/// ifexpr ::= 'if' expression 'then' expression 'else' expression
504static ExprAST *ParseIfExpr() {
505 SourceLocation IfLoc = CurLoc;
506
507 getNextToken(); // eat the if.
508
509 // condition.
510 ExprAST *Cond = ParseExpression();
511 if (!Cond)
512 return 0;
513
514 if (CurTok != tok_then)
515 return Error("expected then");
516 getNextToken(); // eat the then
517
518 ExprAST *Then = ParseExpression();
519 if (Then == 0)
520 return 0;
521
522 if (CurTok != tok_else)
523 return Error("expected else");
524
525 getNextToken();
526
527 ExprAST *Else = ParseExpression();
528 if (!Else)
529 return 0;
530
531 return new IfExprAST(IfLoc, Cond, Then, Else);
532}
533
534/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
535static ExprAST *ParseForExpr() {
536 getNextToken(); // eat the for.
537
538 if (CurTok != tok_identifier)
539 return Error("expected identifier after for");
540
541 std::string IdName = IdentifierStr;
542 getNextToken(); // eat identifier.
543
544 if (CurTok != '=')
545 return Error("expected '=' after for");
546 getNextToken(); // eat '='.
547
548 ExprAST *Start = ParseExpression();
549 if (Start == 0)
550 return 0;
551 if (CurTok != ',')
552 return Error("expected ',' after for start value");
553 getNextToken();
554
555 ExprAST *End = ParseExpression();
556 if (End == 0)
557 return 0;
558
559 // The step value is optional.
560 ExprAST *Step = 0;
561 if (CurTok == ',') {
562 getNextToken();
563 Step = ParseExpression();
564 if (Step == 0)
565 return 0;
566 }
567
568 if (CurTok != tok_in)
569 return Error("expected 'in' after for");
570 getNextToken(); // eat 'in'.
571
572 ExprAST *Body = ParseExpression();
573 if (Body == 0)
574 return 0;
575
576 return new ForExprAST(IdName, Start, End, Step, Body);
577}
578
579/// varexpr ::= 'var' identifier ('=' expression)?
580// (',' identifier ('=' expression)?)* 'in' expression
581static ExprAST *ParseVarExpr() {
582 getNextToken(); // eat the var.
583
584 std::vector<std::pair<std::string, ExprAST *> > VarNames;
585
586 // At least one variable name is required.
587 if (CurTok != tok_identifier)
588 return Error("expected identifier after var");
589
590 while (1) {
591 std::string Name = IdentifierStr;
592 getNextToken(); // eat identifier.
593
594 // Read the optional initializer.
595 ExprAST *Init = 0;
596 if (CurTok == '=') {
597 getNextToken(); // eat the '='.
598
599 Init = ParseExpression();
600 if (Init == 0)
601 return 0;
602 }
603
604 VarNames.push_back(std::make_pair(Name, Init));
605
606 // End of var list, exit loop.
607 if (CurTok != ',')
608 break;
609 getNextToken(); // eat the ','.
610
611 if (CurTok != tok_identifier)
612 return Error("expected identifier list after var");
613 }
614
615 // At this point, we have to have 'in'.
616 if (CurTok != tok_in)
617 return Error("expected 'in' keyword after 'var'");
618 getNextToken(); // eat 'in'.
619
620 ExprAST *Body = ParseExpression();
621 if (Body == 0)
622 return 0;
623
624 return new VarExprAST(VarNames, Body);
625}
626
627/// primary
628/// ::= identifierexpr
629/// ::= numberexpr
630/// ::= parenexpr
631/// ::= ifexpr
632/// ::= forexpr
633/// ::= varexpr
634static ExprAST *ParsePrimary() {
635 switch (CurTok) {
636 default:
637 return Error("unknown token when expecting an expression");
638 case tok_identifier:
639 return ParseIdentifierExpr();
640 case tok_number:
641 return ParseNumberExpr();
642 case '(':
643 return ParseParenExpr();
644 case tok_if:
645 return ParseIfExpr();
646 case tok_for:
647 return ParseForExpr();
648 case tok_var:
649 return ParseVarExpr();
650 }
651}
652
653/// unary
654/// ::= primary
655/// ::= '!' unary
656static ExprAST *ParseUnary() {
657 // If the current token is not an operator, it must be a primary expr.
658 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
659 return ParsePrimary();
660
661 // If this is a unary operator, read it.
662 int Opc = CurTok;
663 getNextToken();
664 if (ExprAST *Operand = ParseUnary())
665 return new UnaryExprAST(Opc, Operand);
666 return 0;
667}
668
669/// binoprhs
670/// ::= ('+' unary)*
671static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
672 // If this is a binop, find its precedence.
673 while (1) {
674 int TokPrec = GetTokPrecedence();
675
676 // If this is a binop that binds at least as tightly as the current binop,
677 // consume it, otherwise we are done.
678 if (TokPrec < ExprPrec)
679 return LHS;
680
681 // Okay, we know this is a binop.
682 int BinOp = CurTok;
683 SourceLocation BinLoc = CurLoc;
684 getNextToken(); // eat binop
685
686 // Parse the unary expression after the binary operator.
687 ExprAST *RHS = ParseUnary();
688 if (!RHS)
689 return 0;
690
691 // If BinOp binds less tightly with RHS than the operator after RHS, let
692 // the pending operator take RHS as its LHS.
693 int NextPrec = GetTokPrecedence();
694 if (TokPrec < NextPrec) {
695 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
696 if (RHS == 0)
697 return 0;
698 }
699
700 // Merge LHS/RHS.
701 LHS = new BinaryExprAST(BinLoc, BinOp, LHS, RHS);
702 }
703}
704
705/// expression
706/// ::= unary binoprhs
707///
708static ExprAST *ParseExpression() {
709 ExprAST *LHS = ParseUnary();
710 if (!LHS)
711 return 0;
712
713 return ParseBinOpRHS(0, LHS);
714}
715
716/// prototype
717/// ::= id '(' id* ')'
718/// ::= binary LETTER number? (id, id)
719/// ::= unary LETTER (id)
720static PrototypeAST *ParsePrototype() {
721 std::string FnName;
722
723 SourceLocation FnLoc = CurLoc;
724
725 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
726 unsigned BinaryPrecedence = 30;
727
728 switch (CurTok) {
729 default:
730 return ErrorP("Expected function name in prototype");
731 case tok_identifier:
732 FnName = IdentifierStr;
733 Kind = 0;
734 getNextToken();
735 break;
736 case tok_unary:
737 getNextToken();
738 if (!isascii(CurTok))
739 return ErrorP("Expected unary operator");
740 FnName = "unary";
741 FnName += (char)CurTok;
742 Kind = 1;
743 getNextToken();
744 break;
745 case tok_binary:
746 getNextToken();
747 if (!isascii(CurTok))
748 return ErrorP("Expected binary operator");
749 FnName = "binary";
750 FnName += (char)CurTok;
751 Kind = 2;
752 getNextToken();
753
754 // Read the precedence if present.
755 if (CurTok == tok_number) {
756 if (NumVal < 1 || NumVal > 100)
757 return ErrorP("Invalid precedecnce: must be 1..100");
758 BinaryPrecedence = (unsigned)NumVal;
759 getNextToken();
760 }
761 break;
762 }
763
764 if (CurTok != '(')
765 return ErrorP("Expected '(' in prototype");
766
767 std::vector<std::string> ArgNames;
768 while (getNextToken() == tok_identifier)
769 ArgNames.push_back(IdentifierStr);
770 if (CurTok != ')')
771 return ErrorP("Expected ')' in prototype");
772
773 // success.
774 getNextToken(); // eat ')'.
775
776 // Verify right number of names for operator.
777 if (Kind && ArgNames.size() != Kind)
778 return ErrorP("Invalid number of operands for operator");
779
780 return new PrototypeAST(FnLoc, FnName, ArgNames, Kind != 0, BinaryPrecedence);
781}
782
783/// definition ::= 'def' prototype expression
784static FunctionAST *ParseDefinition() {
785 getNextToken(); // eat def.
786 PrototypeAST *Proto = ParsePrototype();
787 if (Proto == 0)
788 return 0;
789
790 if (ExprAST *E = ParseExpression())
791 return new FunctionAST(Proto, E);
792 return 0;
793}
794
795/// toplevelexpr ::= expression
796static FunctionAST *ParseTopLevelExpr() {
797 SourceLocation FnLoc = CurLoc;
798 if (ExprAST *E = ParseExpression()) {
799 // Make an anonymous proto.
800 PrototypeAST *Proto =
801 new PrototypeAST(FnLoc, "main", std::vector<std::string>());
802 return new FunctionAST(Proto, E);
803 }
804 return 0;
805}
806
807/// external ::= 'extern' prototype
808static PrototypeAST *ParseExtern() {
809 getNextToken(); // eat extern.
810 return ParsePrototype();
811}
812
813//===----------------------------------------------------------------------===//
814// Debug Info Support
815//===----------------------------------------------------------------------===//
816
817static DIBuilder *DBuilder;
818
819DIType DebugInfo::getDoubleTy() {
820 if (DblTy.isValid())
821 return DblTy;
822
823 DblTy = DBuilder->createBasicType("double", 64, 64, dwarf::DW_ATE_float);
824 return DblTy;
825}
826
827void DebugInfo::emitLocation(ExprAST *AST) {
828 if (!AST)
829 return Builder.SetCurrentDebugLocation(DebugLoc());
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000830 MDScope *Scope;
Eric Christopher05917fa2014-12-08 18:00:47 +0000831 if (LexicalBlocks.empty())
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000832 Scope = TheCU;
Eric Christopher05917fa2014-12-08 18:00:47 +0000833 else
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000834 Scope = *LexicalBlocks.back();
Eric Christopher05917fa2014-12-08 18:00:47 +0000835 Builder.SetCurrentDebugLocation(
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000836 DebugLoc::get(AST->getLine(), AST->getCol(), Scope));
Eric Christopher05917fa2014-12-08 18:00:47 +0000837}
838
839static DICompositeType CreateFunctionType(unsigned NumArgs, DIFile Unit) {
Duncan P. N. Exon Smith4e752fb2015-01-06 23:48:22 +0000840 SmallVector<Metadata *, 8> EltTys;
Eric Christopher05917fa2014-12-08 18:00:47 +0000841 DIType DblTy = KSDbgInfo.getDoubleTy();
842
843 // Add the result type.
844 EltTys.push_back(DblTy);
845
846 for (unsigned i = 0, e = NumArgs; i != e; ++i)
847 EltTys.push_back(DblTy);
848
849 DITypeArray EltTypeArray = DBuilder->getOrCreateTypeArray(EltTys);
850 return DBuilder->createSubroutineType(Unit, EltTypeArray);
851}
852
853//===----------------------------------------------------------------------===//
854// Code Generation
855//===----------------------------------------------------------------------===//
856
857static Module *TheModule;
858static std::map<std::string, AllocaInst *> NamedValues;
Chandler Carruth7ecd9912015-02-13 10:21:05 +0000859static legacy::FunctionPassManager *TheFPM;
Eric Christopher05917fa2014-12-08 18:00:47 +0000860
861Value *ErrorV(const char *Str) {
862 Error(Str);
863 return 0;
864}
865
866/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
867/// the function. This is used for mutable variables etc.
868static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
869 const std::string &VarName) {
870 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
871 TheFunction->getEntryBlock().begin());
872 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
873 VarName.c_str());
874}
875
876Value *NumberExprAST::Codegen() {
877 KSDbgInfo.emitLocation(this);
878 return ConstantFP::get(getGlobalContext(), APFloat(Val));
879}
880
881Value *VariableExprAST::Codegen() {
882 // Look this variable up in the function.
883 Value *V = NamedValues[Name];
884 if (V == 0)
885 return ErrorV("Unknown variable name");
886
887 KSDbgInfo.emitLocation(this);
888 // Load the value.
889 return Builder.CreateLoad(V, Name.c_str());
890}
891
892Value *UnaryExprAST::Codegen() {
893 Value *OperandV = Operand->Codegen();
894 if (OperandV == 0)
895 return 0;
896
897 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
898 if (F == 0)
899 return ErrorV("Unknown unary operator");
900
901 KSDbgInfo.emitLocation(this);
902 return Builder.CreateCall(F, OperandV, "unop");
903}
904
905Value *BinaryExprAST::Codegen() {
906 KSDbgInfo.emitLocation(this);
907
908 // Special case '=' because we don't want to emit the LHS as an expression.
909 if (Op == '=') {
910 // Assignment requires the LHS to be an identifier.
911 VariableExprAST *LHSE = dynamic_cast<VariableExprAST *>(LHS);
912 if (!LHSE)
913 return ErrorV("destination of '=' must be a variable");
914 // Codegen the RHS.
915 Value *Val = RHS->Codegen();
916 if (Val == 0)
917 return 0;
918
919 // Look up the name.
920 Value *Variable = NamedValues[LHSE->getName()];
921 if (Variable == 0)
922 return ErrorV("Unknown variable name");
923
924 Builder.CreateStore(Val, Variable);
925 return Val;
926 }
927
928 Value *L = LHS->Codegen();
929 Value *R = RHS->Codegen();
930 if (L == 0 || R == 0)
931 return 0;
932
933 switch (Op) {
934 case '+':
935 return Builder.CreateFAdd(L, R, "addtmp");
936 case '-':
937 return Builder.CreateFSub(L, R, "subtmp");
938 case '*':
939 return Builder.CreateFMul(L, R, "multmp");
940 case '<':
941 L = Builder.CreateFCmpULT(L, R, "cmptmp");
942 // Convert bool 0/1 to double 0.0 or 1.0
943 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
944 "booltmp");
945 default:
946 break;
947 }
948
949 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
950 // a call to it.
951 Function *F = TheModule->getFunction(std::string("binary") + Op);
952 assert(F && "binary operator not found!");
953
954 Value *Ops[] = { L, R };
955 return Builder.CreateCall(F, Ops, "binop");
956}
957
958Value *CallExprAST::Codegen() {
959 KSDbgInfo.emitLocation(this);
960
961 // Look up the name in the global module table.
962 Function *CalleeF = TheModule->getFunction(Callee);
963 if (CalleeF == 0)
964 return ErrorV("Unknown function referenced");
965
966 // If argument mismatch error.
967 if (CalleeF->arg_size() != Args.size())
968 return ErrorV("Incorrect # arguments passed");
969
970 std::vector<Value *> ArgsV;
971 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
972 ArgsV.push_back(Args[i]->Codegen());
973 if (ArgsV.back() == 0)
974 return 0;
975 }
976
977 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
978}
979
980Value *IfExprAST::Codegen() {
981 KSDbgInfo.emitLocation(this);
982
983 Value *CondV = Cond->Codegen();
984 if (CondV == 0)
985 return 0;
986
987 // Convert condition to a bool by comparing equal to 0.0.
988 CondV = Builder.CreateFCmpONE(
989 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
990
991 Function *TheFunction = Builder.GetInsertBlock()->getParent();
992
993 // Create blocks for the then and else cases. Insert the 'then' block at the
994 // end of the function.
995 BasicBlock *ThenBB =
996 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
997 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
998 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
999
1000 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
1001
1002 // Emit then value.
1003 Builder.SetInsertPoint(ThenBB);
1004
1005 Value *ThenV = Then->Codegen();
1006 if (ThenV == 0)
1007 return 0;
1008
1009 Builder.CreateBr(MergeBB);
1010 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1011 ThenBB = Builder.GetInsertBlock();
1012
1013 // Emit else block.
1014 TheFunction->getBasicBlockList().push_back(ElseBB);
1015 Builder.SetInsertPoint(ElseBB);
1016
1017 Value *ElseV = Else->Codegen();
1018 if (ElseV == 0)
1019 return 0;
1020
1021 Builder.CreateBr(MergeBB);
1022 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1023 ElseBB = Builder.GetInsertBlock();
1024
1025 // Emit merge block.
1026 TheFunction->getBasicBlockList().push_back(MergeBB);
1027 Builder.SetInsertPoint(MergeBB);
1028 PHINode *PN =
1029 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
1030
1031 PN->addIncoming(ThenV, ThenBB);
1032 PN->addIncoming(ElseV, ElseBB);
1033 return PN;
1034}
1035
1036Value *ForExprAST::Codegen() {
1037 // Output this as:
1038 // var = alloca double
1039 // ...
1040 // start = startexpr
1041 // store start -> var
1042 // goto loop
1043 // loop:
1044 // ...
1045 // bodyexpr
1046 // ...
1047 // loopend:
1048 // step = stepexpr
1049 // endcond = endexpr
1050 //
1051 // curvar = load var
1052 // nextvar = curvar + step
1053 // store nextvar -> var
1054 // br endcond, loop, endloop
1055 // outloop:
1056
1057 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1058
1059 // Create an alloca for the variable in the entry block.
1060 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1061
1062 KSDbgInfo.emitLocation(this);
1063
1064 // Emit the start code first, without 'variable' in scope.
1065 Value *StartVal = Start->Codegen();
1066 if (StartVal == 0)
1067 return 0;
1068
1069 // Store the value into the alloca.
1070 Builder.CreateStore(StartVal, Alloca);
1071
1072 // Make the new basic block for the loop header, inserting after current
1073 // block.
1074 BasicBlock *LoopBB =
1075 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
1076
1077 // Insert an explicit fall through from the current block to the LoopBB.
1078 Builder.CreateBr(LoopBB);
1079
1080 // Start insertion in LoopBB.
1081 Builder.SetInsertPoint(LoopBB);
1082
1083 // Within the loop, the variable is defined equal to the PHI node. If it
1084 // shadows an existing variable, we have to restore it, so save it now.
1085 AllocaInst *OldVal = NamedValues[VarName];
1086 NamedValues[VarName] = Alloca;
1087
1088 // Emit the body of the loop. This, like any other expr, can change the
1089 // current BB. Note that we ignore the value computed by the body, but don't
1090 // allow an error.
1091 if (Body->Codegen() == 0)
1092 return 0;
1093
1094 // Emit the step value.
1095 Value *StepVal;
1096 if (Step) {
1097 StepVal = Step->Codegen();
1098 if (StepVal == 0)
1099 return 0;
1100 } else {
1101 // If not specified, use 1.0.
1102 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
1103 }
1104
1105 // Compute the end condition.
1106 Value *EndCond = End->Codegen();
1107 if (EndCond == 0)
1108 return EndCond;
1109
1110 // Reload, increment, and restore the alloca. This handles the case where
1111 // the body of the loop mutates the variable.
1112 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
1113 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
1114 Builder.CreateStore(NextVar, Alloca);
1115
1116 // Convert condition to a bool by comparing equal to 0.0.
1117 EndCond = Builder.CreateFCmpONE(
1118 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
1119
1120 // Create the "after loop" block and insert it.
1121 BasicBlock *AfterBB =
1122 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
1123
1124 // Insert the conditional branch into the end of LoopEndBB.
1125 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
1126
1127 // Any new code will be inserted in AfterBB.
1128 Builder.SetInsertPoint(AfterBB);
1129
1130 // Restore the unshadowed variable.
1131 if (OldVal)
1132 NamedValues[VarName] = OldVal;
1133 else
1134 NamedValues.erase(VarName);
1135
1136 // for expr always returns 0.0.
1137 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
1138}
1139
1140Value *VarExprAST::Codegen() {
1141 std::vector<AllocaInst *> OldBindings;
1142
1143 Function *TheFunction = Builder.GetInsertBlock()->getParent();
1144
1145 // Register all variables and emit their initializer.
1146 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
1147 const std::string &VarName = VarNames[i].first;
1148 ExprAST *Init = VarNames[i].second;
1149
1150 // Emit the initializer before adding the variable to scope, this prevents
1151 // the initializer from referencing the variable itself, and permits stuff
1152 // like this:
1153 // var a = 1 in
1154 // var a = a in ... # refers to outer 'a'.
1155 Value *InitVal;
1156 if (Init) {
1157 InitVal = Init->Codegen();
1158 if (InitVal == 0)
1159 return 0;
1160 } else { // If not specified, use 0.0.
1161 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
1162 }
1163
1164 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1165 Builder.CreateStore(InitVal, Alloca);
1166
1167 // Remember the old variable binding so that we can restore the binding when
1168 // we unrecurse.
1169 OldBindings.push_back(NamedValues[VarName]);
1170
1171 // Remember this binding.
1172 NamedValues[VarName] = Alloca;
1173 }
1174
1175 KSDbgInfo.emitLocation(this);
1176
1177 // Codegen the body, now that all vars are in scope.
1178 Value *BodyVal = Body->Codegen();
1179 if (BodyVal == 0)
1180 return 0;
1181
1182 // Pop all our variables from scope.
1183 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1184 NamedValues[VarNames[i].first] = OldBindings[i];
1185
1186 // Return the body computation.
1187 return BodyVal;
1188}
1189
1190Function *PrototypeAST::Codegen() {
1191 // Make the function type: double(double,double) etc.
1192 std::vector<Type *> Doubles(Args.size(),
1193 Type::getDoubleTy(getGlobalContext()));
1194 FunctionType *FT =
1195 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1196
1197 Function *F =
1198 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1199
1200 // If F conflicted, there was already something named 'Name'. If it has a
1201 // body, don't allow redefinition or reextern.
1202 if (F->getName() != Name) {
1203 // Delete the one we just made and get the existing one.
1204 F->eraseFromParent();
1205 F = TheModule->getFunction(Name);
1206
1207 // If F already has a body, reject this.
1208 if (!F->empty()) {
1209 ErrorF("redefinition of function");
1210 return 0;
1211 }
1212
1213 // If F took a different number of args, reject.
1214 if (F->arg_size() != Args.size()) {
1215 ErrorF("redefinition of function with different # args");
1216 return 0;
1217 }
1218 }
1219
1220 // Set names for all arguments.
1221 unsigned Idx = 0;
1222 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1223 ++AI, ++Idx)
1224 AI->setName(Args[Idx]);
1225
1226 // Create a subprogram DIE for this function.
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001227 DIFile Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1228 KSDbgInfo.TheCU->getDirectory());
1229 DIDescriptor FContext = Unit;
Eric Christopher05917fa2014-12-08 18:00:47 +00001230 unsigned LineNo = Line;
1231 unsigned ScopeLine = Line;
1232 DISubprogram SP = DBuilder->createFunction(
1233 FContext, Name, StringRef(), Unit, LineNo,
1234 CreateFunctionType(Args.size(), Unit), false /* internal linkage */,
1235 true /* definition */, ScopeLine, DIDescriptor::FlagPrototyped, false, F);
1236
Duncan P. N. Exon Smith754cf792015-04-14 16:19:44 +00001237 KSDbgInfo.FnScopeMap[this] = SP;
Eric Christopher05917fa2014-12-08 18:00:47 +00001238 return F;
1239}
1240
1241/// CreateArgumentAllocas - Create an alloca for each argument and register the
1242/// argument in the symbol table so that references to it will succeed.
1243void PrototypeAST::CreateArgumentAllocas(Function *F) {
1244 Function::arg_iterator AI = F->arg_begin();
1245 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1246 // Create an alloca for this variable.
1247 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1248
1249 // Create a debug descriptor for the variable.
1250 DIScope *Scope = KSDbgInfo.LexicalBlocks.back();
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001251 DIFile Unit = DBuilder->createFile(KSDbgInfo.TheCU->getFilename(),
1252 KSDbgInfo.TheCU->getDirectory());
Eric Christopher05917fa2014-12-08 18:00:47 +00001253 DIVariable D = DBuilder->createLocalVariable(dwarf::DW_TAG_arg_variable,
1254 *Scope, Args[Idx], Unit, Line,
1255 KSDbgInfo.getDoubleTy(), Idx);
1256
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +00001257 DBuilder->insertDeclare(Alloca, D, DBuilder->createExpression(),
1258 DebugLoc::get(Line, 0, *Scope),
1259 Builder.GetInsertBlock());
Eric Christopher05917fa2014-12-08 18:00:47 +00001260
1261 // Store the initial value into the alloca.
1262 Builder.CreateStore(AI, Alloca);
1263
1264 // Add arguments to variable symbol table.
1265 NamedValues[Args[Idx]] = Alloca;
1266 }
1267}
1268
1269Function *FunctionAST::Codegen() {
1270 NamedValues.clear();
1271
1272 Function *TheFunction = Proto->Codegen();
1273 if (TheFunction == 0)
1274 return 0;
1275
1276 // Push the current scope.
1277 KSDbgInfo.LexicalBlocks.push_back(&KSDbgInfo.FnScopeMap[Proto]);
1278
1279 // Unset the location for the prologue emission (leading instructions with no
1280 // location in a function are considered part of the prologue and the debugger
1281 // will run past them when breaking on a function)
1282 KSDbgInfo.emitLocation(nullptr);
1283
1284 // If this is an operator, install it.
1285 if (Proto->isBinaryOp())
1286 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1287
1288 // Create a new basic block to start insertion into.
1289 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1290 Builder.SetInsertPoint(BB);
1291
1292 // Add all arguments to the symbol table and create their allocas.
1293 Proto->CreateArgumentAllocas(TheFunction);
1294
1295 KSDbgInfo.emitLocation(Body);
1296
1297 if (Value *RetVal = Body->Codegen()) {
1298 // Finish off the function.
1299 Builder.CreateRet(RetVal);
1300
1301 // Pop off the lexical block for the function.
1302 KSDbgInfo.LexicalBlocks.pop_back();
1303
1304 // Validate the generated code, checking for consistency.
1305 verifyFunction(*TheFunction);
1306
1307 // Optimize the function.
1308 TheFPM->run(*TheFunction);
1309
1310 return TheFunction;
1311 }
1312
1313 // Error reading body, remove function.
1314 TheFunction->eraseFromParent();
1315
1316 if (Proto->isBinaryOp())
1317 BinopPrecedence.erase(Proto->getOperatorName());
1318
1319 // Pop off the lexical block for the function since we added it
1320 // unconditionally.
1321 KSDbgInfo.LexicalBlocks.pop_back();
1322
1323 return 0;
1324}
1325
1326//===----------------------------------------------------------------------===//
1327// Top-Level parsing and JIT Driver
1328//===----------------------------------------------------------------------===//
1329
1330static ExecutionEngine *TheExecutionEngine;
1331
1332static void HandleDefinition() {
1333 if (FunctionAST *F = ParseDefinition()) {
1334 if (!F->Codegen()) {
1335 fprintf(stderr, "Error reading function definition:");
1336 }
1337 } else {
1338 // Skip token for error recovery.
1339 getNextToken();
1340 }
1341}
1342
1343static void HandleExtern() {
1344 if (PrototypeAST *P = ParseExtern()) {
1345 if (!P->Codegen()) {
1346 fprintf(stderr, "Error reading extern");
1347 }
1348 } else {
1349 // Skip token for error recovery.
1350 getNextToken();
1351 }
1352}
1353
1354static void HandleTopLevelExpression() {
1355 // Evaluate a top-level expression into an anonymous function.
1356 if (FunctionAST *F = ParseTopLevelExpr()) {
1357 if (!F->Codegen()) {
1358 fprintf(stderr, "Error generating code for top level expr");
1359 }
1360 } else {
1361 // Skip token for error recovery.
1362 getNextToken();
1363 }
1364}
1365
1366/// top ::= definition | external | expression | ';'
1367static void MainLoop() {
1368 while (1) {
1369 switch (CurTok) {
1370 case tok_eof:
1371 return;
1372 case ';':
1373 getNextToken();
1374 break; // ignore top-level semicolons.
1375 case tok_def:
1376 HandleDefinition();
1377 break;
1378 case tok_extern:
1379 HandleExtern();
1380 break;
1381 default:
1382 HandleTopLevelExpression();
1383 break;
1384 }
1385 }
1386}
1387
1388//===----------------------------------------------------------------------===//
1389// "Library" functions that can be "extern'd" from user code.
1390//===----------------------------------------------------------------------===//
1391
1392/// putchard - putchar that takes a double and returns 0.
1393extern "C" double putchard(double X) {
1394 putchar((char)X);
1395 return 0;
1396}
1397
1398/// printd - printf that takes a double prints it as "%f\n", returning 0.
1399extern "C" double printd(double X) {
1400 printf("%f\n", X);
1401 return 0;
1402}
1403
1404//===----------------------------------------------------------------------===//
1405// Main driver code.
1406//===----------------------------------------------------------------------===//
1407
1408int main() {
1409 InitializeNativeTarget();
1410 InitializeNativeTargetAsmPrinter();
1411 InitializeNativeTargetAsmParser();
1412 LLVMContext &Context = getGlobalContext();
1413
1414 // Install standard binary operators.
1415 // 1 is lowest precedence.
1416 BinopPrecedence['='] = 2;
1417 BinopPrecedence['<'] = 10;
1418 BinopPrecedence['+'] = 20;
1419 BinopPrecedence['-'] = 20;
1420 BinopPrecedence['*'] = 40; // highest.
1421
1422 // Prime the first token.
1423 getNextToken();
1424
1425 // Make the module, which holds all the code.
1426 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1427 TheModule = Owner.get();
1428
1429 // Add the current debug info version into the module.
1430 TheModule->addModuleFlag(Module::Warning, "Debug Info Version",
1431 DEBUG_METADATA_VERSION);
1432
1433 // Darwin only supports dwarf2.
1434 if (Triple(sys::getProcessTriple()).isOSDarwin())
1435 TheModule->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2);
1436
1437 // Construct the DIBuilder, we do this here because we need the module.
1438 DBuilder = new DIBuilder(*TheModule);
1439
1440 // Create the compile unit for the module.
1441 // Currently down as "fib.ks" as a filename since we're redirecting stdin
1442 // but we'd like actual source locations.
1443 KSDbgInfo.TheCU = DBuilder->createCompileUnit(
1444 dwarf::DW_LANG_C, "fib.ks", ".", "Kaleidoscope Compiler", 0, "", 0);
1445
1446 // Create the JIT. This takes ownership of the module.
1447 std::string ErrStr;
Eric Christopherc0239362014-12-08 18:12:28 +00001448 TheExecutionEngine =
1449 EngineBuilder(std::move(Owner))
1450 .setErrorStr(&ErrStr)
1451 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1452 .create();
Eric Christopher05917fa2014-12-08 18:00:47 +00001453 if (!TheExecutionEngine) {
1454 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1455 exit(1);
1456 }
1457
Chandler Carruth7ecd9912015-02-13 10:21:05 +00001458 legacy::FunctionPassManager OurFPM(TheModule);
Eric Christopher05917fa2014-12-08 18:00:47 +00001459
1460 // Set up the optimizer pipeline. Start with registering info about how the
1461 // target lays out data structures.
Rafael Espindola265ffbe2015-03-04 19:15:29 +00001462 TheModule->setDataLayout(*TheExecutionEngine->getDataLayout());
Eric Christopher05917fa2014-12-08 18:00:47 +00001463#if 0
1464 // Provide basic AliasAnalysis support for GVN.
1465 OurFPM.add(createBasicAliasAnalysisPass());
1466 // Promote allocas to registers.
1467 OurFPM.add(createPromoteMemoryToRegisterPass());
1468 // Do simple "peephole" optimizations and bit-twiddling optzns.
1469 OurFPM.add(createInstructionCombiningPass());
1470 // Reassociate expressions.
1471 OurFPM.add(createReassociatePass());
1472 // Eliminate Common SubExpressions.
1473 OurFPM.add(createGVNPass());
1474 // Simplify the control flow graph (deleting unreachable blocks, etc).
1475 OurFPM.add(createCFGSimplificationPass());
1476 #endif
1477 OurFPM.doInitialization();
1478
1479 // Set the global so the code gen can use this.
1480 TheFPM = &OurFPM;
1481
1482 // Run the main "interpreter loop" now.
1483 MainLoop();
1484
1485 TheFPM = 0;
1486
1487 // Finalize the debug info.
1488 DBuilder->finalize();
1489
1490 // Print out all of the generated code.
1491 TheModule->dump();
1492
1493 return 0;
1494}