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