· 4 years ago · May 15, 2021, 06:34 AM
1#include "llvm/ADT/APFloat.h"
2#include "llvm/ADT/Optional.h"
3#include "llvm/ADT/STLExtras.h"
4#include "llvm/IR/BasicBlock.h"
5#include "llvm/IR/Constants.h"
6#include "llvm/IR/DerivedTypes.h"
7#include "llvm/IR/Function.h"
8#include "llvm/IR/Instructions.h"
9#include "llvm/IR/IRBuilder.h"
10#include "llvm/IR/LLVMContext.h"
11#include "llvm/IR/LegacyPassManager.h"
12#include "llvm/IR/Module.h"
13#include "llvm/IR/Type.h"
14#include "llvm/IR/Verifier.h"
15#include "llvm/Support/FileSystem.h"
16#include "llvm/Support/Host.h"
17#include "llvm/Support/raw_ostream.h"
18#include "llvm/Support/TargetRegistry.h"
19#include "llvm/Support/TargetSelect.h"
20#include "llvm/Target/TargetMachine.h"
21#include "llvm/Target/TargetOptions.h"
22#include <algorithm>
23#include <cassert>
24#include <cctype>
25#include <cstdio>
26#include <cstdlib>
27#include <map>
28#include <memory>
29#include <string>
30#include <system_error>
31#include <utility>
32#include <vector>
33#include <iostream>
34using namespace llvm;
35using namespace llvm::sys;
36
37
38enum VariableType {
39 Double='d',
40 String='s',
41 Unknown='e'
42};
43
44static VariableType ConvertStrTypeToEnum(std::string strType) {
45 if (strType == "Double")
46 return VariableType::Double;
47 if (strType == "String")
48 return VariableType::String;
49 return VariableType::Unknown;
50}
51
52static std::map<std::string, VariableType> VarTypes;
53
54//===----------------------------------------------------------------------===//
55// Lexer
56//===----------------------------------------------------------------------===//
57
58// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
59// of these for known things.
60enum Token {
61 tok_eof = -1,
62
63 // commands
64 tok_func= -2,
65 tok_extern = -3,
66
67 // primary
68 tok_identifier = -4,
69 tok_number = -5,
70 tok_str = -6,
71
72 // control
73 tok_if = -7,
74 tok_then = -8,
75 tok_else = -9,
76 tok_for = -10,
77 tok_in = -11,
78 tok_return = -12,
79
80 // operators
81 tok_binary = -13,
82 tok_unary = -14,
83
84 // var definition
85 tok_var = -15,
86
87
88 // unique property
89 tok_watch = -16
90
91};
92static const std::string WATCH_VARIABLE_PREFIX = "__";
93static std::string IdentifierStr; // Filled in if tok_identifier
94static double NumVal; // Filled in if tok_number
95static std::string StringVal; // Filled in if tok_str
96
97
98
99/// gettok - Return the next token from standard input.
100static int gettok() {
101 static int LastChar = ' ';
102
103 // Skip any whitespace.
104 while (isspace(LastChar))
105 LastChar = getchar();
106
107 if(LastChar == '"'){
108 std::string value = "";
109 LastChar = getchar();
110 while(LastChar != '"'){
111 value += LastChar;
112 LastChar = getchar();
113 }
114 LastChar = getchar();
115 StringVal = value;
116 return tok_str;
117 }
118
119 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
120 IdentifierStr = LastChar;
121 while (isalnum((LastChar = getchar())))
122 IdentifierStr += LastChar;
123
124 if (IdentifierStr == "func")
125 return tok_func;
126 if (IdentifierStr == "extern")
127 return tok_extern;
128 if (IdentifierStr == "if")
129 return tok_if;
130 if (IdentifierStr == "then")
131 return tok_then;
132 if (IdentifierStr == "else")
133 return tok_else;
134 if (IdentifierStr == "for")
135 return tok_for;
136 if (IdentifierStr == "in")
137 return tok_in;
138 if (IdentifierStr == "binary")
139 return tok_binary;
140 if (IdentifierStr == "unary")
141 return tok_unary;
142 if (IdentifierStr == "return")
143 return tok_return;
144 if (IdentifierStr == "WATCH")
145 return tok_watch;
146 if (ConvertStrTypeToEnum(IdentifierStr) != VariableType::Unknown)
147 return tok_var;
148
149
150 // If not a token, then an identifier
151 return tok_identifier;
152 }
153
154 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
155 std::string NumStr;
156 do {
157 NumStr += LastChar;
158 LastChar = getchar();
159 } while (isdigit(LastChar) || LastChar == '.');
160
161 NumVal = strtod(NumStr.c_str(), nullptr);
162 return tok_number;
163 }
164
165 if (LastChar == '#') {
166 // Comment until end of line.
167 do
168 LastChar = getchar();
169 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
170
171 if (LastChar != EOF)
172 return gettok();
173 }
174
175 // Check for end of file. Don't eat the EOF.
176 if (LastChar == EOF)
177 return tok_eof;
178
179 // Otherwise, just return the character as its ascii value.
180 int ThisChar = LastChar;
181 LastChar = getchar();
182 return ThisChar;
183}
184
185//===----------------------------------------------------------------------===//
186// Abstract Syntax Tree (aka Parse Tree)
187//===----------------------------------------------------------------------===//
188
189namespace {
190
191/// ExprAST - Base class for all expression nodes.
192 class ExprAST {
193 public:
194 virtual ~ExprAST() = default;
195
196 virtual Value *codegen() = 0;
197 virtual std::string getType() {return "Unknown"; };
198 };
199
200/// NumberExprAST - Expression class for numeric literals like "1.0".
201 class NumberExprAST : public ExprAST {
202 double Val;
203
204 public:
205 NumberExprAST(double Val) : Val(Val) {}
206
207 virtual std::string getType() override { return "Double"; }
208
209 Value *codegen() override;
210 };
211 class StringExprAST : public ExprAST {
212 std::string Val;
213
214 public:
215 StringExprAST(std::string Val) : Val(Val) {}
216 virtual std::string getType() override { return "String"; }
217
218 Value *codegen() override;
219 };
220
221/// VariableExprAST - Expression class for referencing a variable, like "a".
222 class VariableExprAST : public ExprAST {
223 std::string Name;
224
225 public:
226 VariableExprAST(const std::string &Name) : Name(Name) {}
227
228 Value *codegen() override;
229 const std::string &getName() const { return Name; }
230 };
231
232/// UnaryExprAST - Expression class for a unary operator.
233 class UnaryExprAST : public ExprAST {
234 char Opcode;
235 std::unique_ptr<ExprAST> Operand;
236
237 public:
238 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
239 : Opcode(Opcode), Operand(std::move(Operand)) {}
240
241 Value *codegen() override;
242 };
243
244/// BinaryExprAST - Expression class for a binary operator.
245 class BinaryExprAST : public ExprAST {
246 char Op;
247 std::unique_ptr<ExprAST> LHS, RHS;
248 std::string LeftParamName;
249
250 public:
251 BinaryExprAST(
252 char Op,
253 std::unique_ptr<ExprAST> LHS,
254 std::unique_ptr<ExprAST> RHS,
255 std::string *LeftParam = nullptr
256 ) : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {
257 if (LeftParam != nullptr) {
258 this->LeftParamName = *LeftParam;
259 }
260 }
261
262 Value *codegen() override;
263 };
264
265/// CallExprAST - Expression class for function calls.
266 class CallExprAST : public ExprAST {
267 std::string Callee;
268 std::vector<std::unique_ptr<ExprAST>> Args;
269
270 public:
271 CallExprAST(const std::string &Callee,
272 std::vector<std::unique_ptr<ExprAST>> Args)
273 : Callee(Callee), Args(std::move(Args)) {}
274
275 Value *codegen() override;
276 };
277
278/// IfExprAST - Expression class for if/then/else.
279 class IfExprAST : public ExprAST {
280 std::unique_ptr<ExprAST> Cond, Then, Else;
281
282 public:
283 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
284 std::unique_ptr<ExprAST> Else)
285 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
286
287 Value *codegen() override;
288 };
289
290/// ForExprAST - Expression class for for/in.
291 class ForExprAST : public ExprAST {
292 std::string VarName;
293 std::unique_ptr<ExprAST> Start, End, Step, Body;
294
295 public:
296 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
297 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
298 std::unique_ptr<ExprAST> Body)
299 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
300 Step(std::move(Step)), Body(std::move(Body)) {}
301
302 Value *codegen() override;
303 };
304
305/// VarExprAST - Expression class for var/in
306 class VarExprAST : public ExprAST {
307 VariableType type;
308 std::string name;
309 std::unique_ptr<ExprAST> value;
310 public:
311 VarExprAST(
312 VariableType _type, std::string _name, std::unique_ptr<ExprAST> _value)
313 : type(_type), name(_name), value(std::move(_value)) {}
314
315 Value *codegen() override;
316 };
317
318/// PrototypeAST - This class represents the "prototype" for a function,
319/// which captures its name, and its argument names (thus implicitly the number
320/// of arguments the function takes), as well as if it is an operator.
321 class PrototypeAST {
322 std::string Name;
323 VariableType ReturnType;
324 // type, value
325 std::vector<std::pair<VariableType, std::string>> Args;
326 bool IsOperator;
327 unsigned Precedence; // Precedence if a binary op.
328
329 public:
330 PrototypeAST(
331 const std::string &Name,
332 const VariableType returnType,
333 std::vector<std::pair<VariableType, std::string>> Args,
334 bool IsOperator = false,
335 unsigned Prec = 0)
336 : Name(Name),
337 ReturnType(returnType),
338 Args(std::move(Args)), IsOperator(IsOperator),
339 Precedence(Prec) {}
340
341 Function *codegen();
342 const std::string &getName() const { return Name; }
343
344 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
345 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
346
347 char getOperatorName() const {
348 assert(isUnaryOp() || isBinaryOp());
349 return Name[Name.size() - 1];
350 }
351
352 unsigned getBinaryPrecedence() const { return Precedence; }
353 };
354
355/// FunctionAST - This class represents a function definition itself.
356 class FunctionAST {
357 std::unique_ptr<PrototypeAST> Proto;
358 std::unique_ptr<ExprAST> Body;
359
360 public:
361 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
362 std::unique_ptr<ExprAST> Body)
363 : Proto(std::move(Proto)), Body(std::move(Body)) {}
364
365 Function *codegen();
366 };
367
368} // end anonymous namespace
369
370//===----------------------------------------------------------------------===//
371// Parser
372//===----------------------------------------------------------------------===//
373
374/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
375/// token the parser is looking at. getNextToken reads another token from the
376/// lexer and updates CurTok with its results.
377static int CurTok;
378static int getNextToken() { return CurTok = gettok(); }
379
380/// BinopPrecedence - This holds the precedence for each binary operator that is
381/// defined.
382static std::map<char, int> BinopPrecedence;
383
384/// GetTokPrecedence - Get the precedence of the pending binary operator token.
385static int GetTokPrecedence() {
386 if (!isascii(CurTok))
387 return -1;
388
389 // Make sure it's a declared binop.
390 int TokPrec = BinopPrecedence[CurTok];
391 if (TokPrec <= 0)
392 return -1;
393 return TokPrec;
394}
395
396/// LogError* - These are little helper functions for error handling.
397std::unique_ptr<ExprAST> LogError(const char *Str) {
398 fprintf(stderr, "Error: %s\n", Str);
399 return nullptr;
400}
401
402std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
403 LogError(Str);
404 return nullptr;
405}
406
407static std::unique_ptr<ExprAST> ParseExpression();
408
409/// numberexpr ::= number
410static std::unique_ptr<ExprAST> ParseNumberExpr() {
411 auto Result = std::make_unique<NumberExprAST>(NumVal);
412 getNextToken(); // consume the number
413 return std::move(Result);
414}
415/// stringexpr ::= string
416static std::unique_ptr<ExprAST> ParseStringExpr() {
417 auto Result = std::make_unique<StringExprAST>(StringVal);
418
419 getNextToken(); // consume the number
420 return std::move(Result);
421}
422
423/// parenexpr ::= '(' expression ')'
424static std::unique_ptr<ExprAST> ParseParenExpr() {
425 getNextToken(); // eat (.
426 auto V = ParseExpression();
427 if (!V)
428 return nullptr;
429
430 if (CurTok != ')')
431 return LogError("expected ')'");
432 getNextToken(); // eat ).
433 return V;
434}
435
436/// identifierexpr
437/// ::= identifier
438/// ::= identifier '(' expression* ')'
439static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
440 std::string IdName = IdentifierStr;
441 getNextToken(); // eat identifier.
442
443 // Create normal variable.
444 if (CurTok != '(') {
445 return std::make_unique<VariableExprAST>(IdName);
446 }
447
448 // Call.
449 getNextToken(); // eat (
450 std::vector<std::unique_ptr<ExprAST>> Args;
451 if (CurTok != ')') {
452 while (true) {
453 if (auto Arg = ParseExpression())
454 Args.push_back(std::move(Arg));
455 else
456 return nullptr;
457
458 if (CurTok == ')')
459 break;
460
461 if (CurTok != ',')
462 return LogError("Expected ')' or ',' in argument list");
463 getNextToken();
464 }
465 }
466
467 // Eat the ')'.
468 getNextToken();
469
470 return std::make_unique<CallExprAST>(IdName, std::move(Args));
471}
472
473static std::unique_ptr<ExprAST> ParseBlock() {
474
475 if (CurTok != '{') {
476 std::cerr << "Block did not start with '{'" << std::endl;
477 return nullptr;
478 }
479 // Eat '{'
480 getNextToken();
481
482 std::unique_ptr<ExprAST> body = nullptr;
483 while (CurTok != '}') {
484 // Check if end of file
485 if (CurTok == tok_eof) {
486 std::cerr << "Body did not end with '}'" << std::endl;
487 return nullptr;
488 }
489
490 // Parse current expression
491 auto expr = ParseExpression();
492 getNextToken();
493 if(body == nullptr) {
494 body = std::move(expr);
495 } else {
496 body = std::make_unique<BinaryExprAST>('n', std::move(body), std::move(expr));
497 }
498 }
499
500 return std::move(body);
501}
502
503/// ifexpr ::= 'if' expression 'then' expression 'else' expression
504static std::unique_ptr<ExprAST> ParseIfExpr() {
505 getNextToken(); // eat the if.
506 // condition.
507 auto Cond = ParseExpression();
508 if (!Cond)
509 return nullptr;
510 auto Then = ParseBlock();
511 if (!Then)
512 return nullptr;
513 getNextToken();
514 if (CurTok != tok_else)
515 return LogError("expected else");
516
517 getNextToken();
518
519 auto Else = ParseBlock();
520 if (!Else)
521 return nullptr;
522
523 getNextToken();
524
525 return std::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
526 std::move(Else));
527}
528
529/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
530static std::unique_ptr<ExprAST> ParseForExpr() {
531 getNextToken(); // eat the for.
532
533 if (CurTok != tok_identifier)
534 return LogError("expected identifier after for");
535
536 std::string IdName = IdentifierStr;
537 getNextToken(); // eat identifier.
538
539 if (CurTok != '=')
540 return LogError("expected '=' after for");
541 getNextToken(); // eat '='.
542
543 auto Start = ParseExpression();
544 if (!Start)
545 return nullptr;
546 if (CurTok != ',')
547 return LogError("expected ',' after for start value");
548 getNextToken();
549
550 auto End = ParseExpression();
551 if (!End)
552 return nullptr;
553
554 // The step value is optional.
555 std::unique_ptr<ExprAST> Step;
556 if (CurTok == ',') {
557 getNextToken();
558 Step = ParseExpression();
559 if (!Step)
560 return nullptr;
561 }
562
563 if (CurTok != tok_in)
564 return LogError("expected 'in' after for");
565 getNextToken(); // eat 'in'.
566
567 auto Body = ParseExpression();
568 if (!Body)
569 return nullptr;
570
571 return std::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
572 std::move(Step), std::move(Body));
573}
574
575
576/// definition ::= 'def' prototype expression
577static std::unique_ptr<FunctionAST> ParseWatchFunc(VariableType varType, std::string varName) {
578 // Eat WATCH
579 getNextToken();
580
581 if (CurTok != '{') {
582 std::cerr << "Expected '{'" << std::endl;
583 return nullptr;
584 }
585
586 // Eat '{'
587 getNextToken();
588
589 // create function header / prototype
590 std::vector<std::pair<VariableType, std::string>> FuncArguments = {
591 std::make_pair(varType, "old"),
592 std::make_pair(varType, "new"),
593 };
594 auto Proto = std::make_unique<PrototypeAST>(WATCH_VARIABLE_PREFIX + varName, varType, FuncArguments, 0, 30);
595
596 // Whole function body
597 std::unique_ptr<ExprAST> FuncBody = nullptr;
598 while (CurTok != '}') {
599 // Check if end of file
600 if (CurTok == tok_eof) {
601 std::cerr << "Function did not end with '}'" << std::endl;
602 return nullptr;
603 }
604
605 // Return statement is met
606 if (CurTok == tok_return) {
607 // Eat return
608 getNextToken();
609
610 // Get parse expression
611 if (auto expr = ParseExpression()) {
612 // Add this to return expression
613 if (FuncBody != nullptr) {
614 FuncBody = std::make_unique<BinaryExprAST>('n', std::move(FuncBody), std::move(expr));
615 } else {
616 FuncBody = std::move(expr);
617 }
618 // Check if function actually ends
619 for (;CurTok != '}';getNextToken()) {
620 if (CurTok == tok_eof) {
621 std::cerr << "Function did not end with '}'" << std::endl;
622 return nullptr;
623 }
624
625 }
626
627 getNextToken();
628 return std::make_unique<FunctionAST>(std::move(Proto), std::move(FuncBody));
629 }
630
631
632 return nullptr;
633 } else {
634 // Parse current expression
635 auto expr = ParseExpression();
636 getNextToken();
637 if(FuncBody == nullptr) {
638 FuncBody = std::move(expr);
639 } else {
640 FuncBody = std::make_unique<BinaryExprAST>('n', std::move(FuncBody), std::move(expr));
641 }
642 }
643 }
644 std::cerr << "No return statement in function" << std::endl;
645 return nullptr;
646}
647
648static void HandleWatchFunction(VariableType watchedVariableType, std::string watchedVariableName) {
649 if (auto FnAST = ParseWatchFunc(watchedVariableType, watchedVariableName)) {
650 if (auto *FnIR = FnAST->codegen()) {
651 fprintf(stderr, "Read function definition:");
652 FnIR->print(errs());
653 fprintf(stderr, "\n");
654 }
655 } else {
656 // Skip token for error recovery.
657 getNextToken();
658 }
659}
660
661/// varexpr ::= 'var' identifier ('=' expression)?
662// (',' identifier ('=' expression)?)* 'in' expression
663static std::unique_ptr<ExprAST> ParseVarExpr() {
664
665 VariableType varType = ConvertStrTypeToEnum(IdentifierStr);
666
667 if(varType == VariableType::Unknown)
668 return LogError("Unknown variable type");
669
670 getNextToken(); // eat the type.
671
672 if(CurTok != tok_identifier)
673 return LogError("Expected identifier after variable type.");
674
675 std::string varName = IdentifierStr;
676 getNextToken(); // eat identifier.
677 // Read the optional initializer.
678 std::unique_ptr<ExprAST> Init = nullptr;
679 if (CurTok == '=') {
680 getNextToken(); // eat the '='.
681 Init = ParseExpression();
682 if (!Init)
683 return nullptr;
684 }
685
686 VarTypes[varName] = varType;
687
688 // Handle watch function
689 if (CurTok == tok_watch) {
690 HandleWatchFunction(varType, varName);
691 }
692 // Must add ';' at the end of the variable declaration OR after
693 // WATCH {}; function
694 if (CurTok != ';') {
695 std::cerr << "Missing ';' after variable declaration" << std::endl;
696 return nullptr;
697 }
698 //getNextToken(); // eat the ';'.
699
700 return std::make_unique<VarExprAST>(varType, varName, std::move(Init));
701}
702
703/// primary
704/// ::= identifierexpr
705/// ::= numberexpr
706/// ::= parenexpr
707/// ::= ifexpr
708/// ::= forexpr
709/// ::= varexpr
710static std::unique_ptr<ExprAST> ParsePrimary() {
711 switch (CurTok) {
712 case tok_identifier:
713 return ParseIdentifierExpr();
714 case tok_number:
715 return ParseNumberExpr();
716 case tok_str:
717 return ParseStringExpr();
718 case '(':
719 return ParseParenExpr();
720 case tok_if:
721 return ParseIfExpr();
722 case tok_for:
723 return ParseForExpr();
724 case tok_var:
725 return ParseVarExpr();
726 default:
727 return LogError("unknown token when expecting an expression");
728 }
729}
730
731/// unary
732/// ::= primary
733/// ::= '!' unary
734static std::unique_ptr<ExprAST> ParseUnary() {
735 // If the current token is not an operator, it must be a primary expr.
736 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
737 return ParsePrimary();
738
739 // If this is a unary operator, read it.
740 int Opc = CurTok;
741 getNextToken();
742 if (auto Operand = ParseUnary())
743 return std::make_unique<UnaryExprAST>(Opc, std::move(Operand));
744 return nullptr;
745}
746
747/// binoprhs
748/// ::= ('+' unary)*
749static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
750 std::unique_ptr<ExprAST> LHS, std::string *LeftName = nullptr) {
751
752 // If this is a binop, find its precedence.
753 while (true) {
754 int TokPrec = GetTokPrecedence();
755
756 // If this is a binop that binds at least as tightly as the current binop,
757 // consume it, otherwise we are done.
758 if (TokPrec < ExprPrec)
759 return LHS;
760
761 // Okay, we know this is a binop.
762 int BinOp = CurTok;
763 getNextToken(); // eat binop
764
765 // Parse the unary expression after the binary operator.
766 auto RHS = ParseUnary();
767 if (!RHS)
768 return nullptr;
769
770 // If BinOp binds less tightly with RHS than the operator after RHS, let
771 // the pending operator take RHS as its LHS.
772 int NextPrec = GetTokPrecedence();
773 if (TokPrec < NextPrec) {
774 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS), LeftName);
775 if (!RHS)
776 return nullptr;
777 }
778
779 // Merge LHS/RHS.
780 LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS), BinOp == '=' ? LeftName : nullptr);
781 }
782}
783
784/// expression
785/// ::= unary binoprhs
786///
787static std::unique_ptr<ExprAST> ParseExpression() {
788 std::string LeftName = IdentifierStr;
789 //auto LHS = ParseUnary();
790 auto LHS = ParsePrimary();
791 if (!LHS)
792 return nullptr;
793 return ParseBinOpRHS(0, std::move(LHS), &LeftName);
794}
795
796/// prototype
797/// ::= id '(' id* ')'
798/// ::= binary LETTER number? (id, id)
799/// ::= unary LETTER (id)
800static std::unique_ptr<PrototypeAST> ParsePrototype() {
801 std::string FnName = IdentifierStr;
802
803 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
804 unsigned BinaryPrecedence = 30;
805 getNextToken();
806 if (CurTok != '(') {
807 return LogErrorP("Expected '(' in prototype");
808 }
809
810 std::vector<std::pair<VariableType, std::string>> ArgNames;
811 std::string dataType = "";
812 bool seenSeperator = false;
813 for (getNextToken();(CurTok == tok_identifier || CurTok == tok_var || CurTok==',');getNextToken()) {
814 if (CurTok == ',') {
815 seenSeperator = true;
816 if ((dataType.size() > 0 || ArgNames.size() == 0)) {
817 return LogErrorP("Only expected ',' after a variable name");
818 }
819 continue;
820 }
821
822 if (CurTok == tok_var) {
823 if (!seenSeperator && ArgNames.size() > 0) {
824 return LogErrorP("Seperate variable names with ','");
825 }
826 if (dataType.size() > 0) {
827 return LogErrorP("Expected variable name after a data type");
828 }
829 if (ConvertStrTypeToEnum(IdentifierStr) == VariableType::Unknown) {
830 return LogErrorP("Invalid data type");
831 }
832 dataType = IdentifierStr;
833 seenSeperator = false;
834 } else {
835 if (dataType.size() == 0) {
836 return LogErrorP("Expected a datatype before variable name");
837 }
838 ArgNames.push_back({ConvertStrTypeToEnum(dataType), IdentifierStr});
839 dataType = "";
840 }
841 }
842 if (CurTok != ')')
843 return LogErrorP("Expected ')' in prototype");
844
845 // success.
846 getNextToken(); // eat ')'.
847
848 auto functionType = ConvertStrTypeToEnum(IdentifierStr);
849 if (functionType != VariableType::Unknown) {
850 getNextToken();
851 } else {
852 // TODO: Make void in the future
853 functionType = VariableType::Unknown;
854 return LogErrorP("Unknown function return type");
855 }
856
857 // Verify right number of names for operator.
858 if (Kind && ArgNames.size() != Kind)
859 return LogErrorP("Invalid number of operands for operator");
860
861 return std::make_unique<PrototypeAST>(FnName, functionType, ArgNames, Kind != 0,
862 BinaryPrecedence);
863}
864
865/// definition ::= 'def' prototype expression
866static std::unique_ptr<FunctionAST> ParseFunc() {
867 getNextToken();
868 auto Proto = ParsePrototype();
869 if (!Proto)
870 return nullptr;
871
872 if (CurTok != '{') {
873 std::cerr << "Expected '{'" << std::endl;
874 return nullptr;
875 }
876
877 // Eat '{'
878 getNextToken();
879 // Whole function body
880 std::unique_ptr<ExprAST> FuncBody = nullptr;
881 while (CurTok != '}') {
882 // Check if end of file
883 if (CurTok == tok_eof) {
884 std::cerr << "Function did not end with '}'" << std::endl;
885 return nullptr;
886 }
887
888 // Return statement is met
889 if (CurTok == tok_return) {
890 // Eat return
891 getNextToken();
892
893 // Get parse expression
894 if (auto expr = ParseExpression()) {
895 // Add this to return expression
896 if (FuncBody != nullptr) {
897 FuncBody = std::make_unique<BinaryExprAST>('n', std::move(FuncBody), std::move(expr));
898 } else {
899 FuncBody = std::move(expr);
900 }
901 // Check if function actually ends
902 for (;CurTok != '}';getNextToken()) {
903 if (CurTok == tok_eof) {
904 std::cerr << "Function did not end with '}'" << std::endl;
905 return nullptr;
906 }
907
908 }
909
910 getNextToken();
911 return std::make_unique<FunctionAST>(std::move(Proto), std::move(FuncBody));
912 }
913
914
915 return nullptr;
916 } else {
917 // Parse current expression
918 auto expr = ParseExpression();
919 getNextToken();
920 if(FuncBody == nullptr) {
921 FuncBody = std::move(expr);
922 } else {
923 FuncBody = std::make_unique<BinaryExprAST>('n', std::move(FuncBody), std::move(expr));
924 }
925 }
926 }
927 return nullptr;
928}
929
930/// toplevelexpr ::= expression
931static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
932 if (auto E = ParseExpression()) {
933 // Make an anonymous proto.
934 auto Proto = std::make_unique<PrototypeAST>("__anon_expr", VariableType::Double,
935 std::vector<std::pair<VariableType, std::string>>());
936 return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
937 }
938 return nullptr;
939}
940
941/// external ::= 'extern' prototype
942static std::unique_ptr<PrototypeAST> ParseExtern() {
943 getNextToken(); // eat extern.
944 return ParsePrototype();
945}
946
947//===----------------------------------------------------------------------===//
948// Code Generation
949//===----------------------------------------------------------------------===//
950
951static std::unique_ptr<LLVMContext> TheContext;
952static std::unique_ptr<Module> TheModule;
953static std::unique_ptr<IRBuilder<>> Builder;
954static std::map<std::string, AllocaInst *> NamedValues;
955static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
956static ExitOnError ExitOnErr;
957
958Value *LogErrorV(const char *Str) {
959 LogError(Str);
960 return nullptr;
961}
962
963Function *getFunction(std::string Name) {
964
965 // First, see if the function has already been added to the current module.
966 if (auto *F = TheModule->getFunction(Name))
967 return F;
968
969 // If not, check whether we can codegen the declaration from some existing
970 // prototype.
971 auto FI = FunctionProtos.find(Name);
972
973 if (FI != FunctionProtos.end()) {
974 return FI->second->codegen();
975 }
976
977
978 // If no existing prototype exists, return null.
979 return nullptr;
980}
981
982static llvm::Type *GetTypeAlloc(VariableType varType) {
983 switch(varType) {
984 case VariableType::String:
985 return Type::getInt8PtrTy(*TheContext);
986 case VariableType::Double:
987 return Type::getDoubleTy(*TheContext);
988 case VariableType::Unknown:
989 default:
990 return nullptr;
991 }
992}
993/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
994/// the function. This is used for mutable variables etc.
995static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
996 StringRef VarName) {
997 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
998 TheFunction->getEntryBlock().begin());
999 const VariableType varType = VarTypes[VarName.str()];
1000 return TmpB.CreateAlloca(GetTypeAlloc(varType), nullptr, VarName);
1001}
1002
1003Value* createString(std::string StringValue){
1004 return Builder->CreateGlobalStringPtr(StringRef(StringValue));
1005}
1006
1007Value *NumberExprAST::codegen() {
1008 return ConstantFP::get(*TheContext, APFloat(Val));
1009}
1010
1011Value *StringExprAST::codegen() {
1012 return createString(this->Val);
1013}
1014
1015Value *VariableExprAST::codegen() {
1016 // Look this variable up in the function.
1017 Value *V = NamedValues[Name];
1018 if (!V)
1019 return LogErrorV("Unknown variable name");
1020
1021 // Load the value.
1022 return Builder->CreateLoad(V, Name.c_str());
1023}
1024
1025Value *UnaryExprAST::codegen() {
1026 Value *OperandV = Operand->codegen();
1027 if (!OperandV)
1028 return nullptr;
1029
1030 Function *F = getFunction(std::string("unary") + Opcode);
1031 if (!F)
1032 return LogErrorV("Unknown unary operator");
1033
1034 return Builder->CreateCall(F, OperandV, "unop");
1035}
1036
1037Value *BinaryExprAST::codegen() {
1038 // Special case '=' because we don't want to emit the LHS as an expression.
1039 if (Op == '=') {
1040 // Assignment requires the LHS to be an identifier.
1041 // This assume we're building without RTTI because LLVM builds that way by
1042 // default. If you build LLVM with RTTI this can be changed to a
1043 // dynamic_cast for automatic error checking.
1044 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
1045 if (!LHSE)
1046 return LogErrorV("destination of '=' must be a variable");
1047 // Codegen the RHS.
1048 Value *Val = RHS->codegen();
1049
1050 if (!Val)
1051 return nullptr;
1052
1053 // Look up the name.
1054 Value *Variable = NamedValues[LHSE->getName()];
1055 if (!Variable)
1056 return LogErrorV("Unknown variable name");
1057
1058
1059 // First check if this function is being watched
1060 Function *CalleeF = getFunction(WATCH_VARIABLE_PREFIX + LeftParamName);
1061 if (CalleeF != nullptr) {
1062 std::vector<Value *> argsV = {LHS->codegen(), RHS->codegen()};
1063 Val = Builder->CreateCall(CalleeF, argsV, "calltmp");
1064 }
1065
1066 Builder->CreateStore(Val, Variable);
1067 return Val;
1068 }
1069
1070 Value *L = LHS->codegen();
1071 Value *R = RHS->codegen();
1072
1073 if (!L || !R)
1074 return nullptr;
1075
1076 switch (Op) {
1077 case '+':
1078 return Builder->CreateFAdd(L, R, "addtmp");
1079 case '-':
1080 return Builder->CreateFSub(L, R, "subtmp");
1081 case '*':
1082 return Builder->CreateFMul(L, R, "multmp");
1083 case '<':
1084 L = Builder->CreateFCmpULT(L, R, "cmptmp");
1085 // Convert bool 0/1 to double 0.0 or 1.0
1086 return Builder->CreateUIToFP(L, Type::getDoubleTy(*TheContext), "booltmp");
1087 case 'n':
1088 return R;
1089 default:
1090 break;
1091 }
1092
1093 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
1094 // a call to it.
1095 Function *F = getFunction(std::string("binary") + Op);
1096 assert(F && "binary operator not found!");
1097
1098 Value *Ops[] = {L, R};
1099 return Builder->CreateCall(F, Ops, "binop");
1100}
1101
1102Value *CallExprAST::codegen() {
1103
1104 // Look up the name in the global module table.
1105 Function *CalleeF = getFunction(Callee);
1106 if (!CalleeF) {
1107 std::cerr << "Unknown function referenced " << Callee << std::endl;
1108 return LogErrorV("Unknown function referenced");
1109 }
1110 // If argument mismatch error.
1111 if (CalleeF->arg_size() != Args.size())
1112 return LogErrorV("Incorrect # arguments passed");
1113
1114 std::vector<Value *> ArgsV;
1115 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
1116 ArgsV.push_back(Args[i]->codegen());
1117 if (!ArgsV.back())
1118 return nullptr;
1119 }
1120
1121 return Builder->CreateCall(CalleeF, ArgsV, "calltmp");
1122}
1123
1124Value *IfExprAST::codegen() {
1125 Value *CondV = Cond->codegen();
1126 if (!CondV)
1127 return nullptr;
1128
1129 // Convert condition to a bool by comparing non-equal to 0.0.
1130 CondV = Builder->CreateFCmpONE(
1131 CondV, ConstantFP::get(*TheContext, APFloat(0.0)), "ifcond");
1132
1133 Function *TheFunction = Builder->GetInsertBlock()->getParent();
1134
1135 // Create blocks for the then and else cases. Insert the 'then' block at the
1136 // end of the function.
1137 BasicBlock *ThenBB = BasicBlock::Create(*TheContext, "then", TheFunction);
1138 BasicBlock *ElseBB = BasicBlock::Create(*TheContext, "else");
1139 BasicBlock *MergeBB = BasicBlock::Create(*TheContext, "ifcont");
1140
1141 Builder->CreateCondBr(CondV, ThenBB, ElseBB);
1142
1143 // Emit then value.
1144 Builder->SetInsertPoint(ThenBB);
1145
1146 Value *ThenV = Then->codegen();
1147 if (!ThenV)
1148 return nullptr;
1149
1150 Builder->CreateBr(MergeBB);
1151 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
1152 ThenBB = Builder->GetInsertBlock();
1153
1154 // Emit else block.
1155 TheFunction->getBasicBlockList().push_back(ElseBB);
1156 Builder->SetInsertPoint(ElseBB);
1157
1158 Value *ElseV = Else->codegen();
1159 if (!ElseV)
1160 return nullptr;
1161
1162 Builder->CreateBr(MergeBB);
1163 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
1164 ElseBB = Builder->GetInsertBlock();
1165
1166 // Emit merge block.
1167 TheFunction->getBasicBlockList().push_back(MergeBB);
1168 Builder->SetInsertPoint(MergeBB);
1169 PHINode *PN = Builder->CreatePHI(Type::getDoubleTy(*TheContext), 2, "iftmp");
1170
1171 PN->addIncoming(ThenV, ThenBB);
1172 PN->addIncoming(ElseV, ElseBB);
1173 return PN;
1174}
1175
1176// Output for-loop as:
1177// var = alloca double
1178// ...
1179// start = startexpr
1180// store start -> var
1181// goto loop
1182// loop:
1183// ...
1184// bodyexpr
1185// ...
1186// loopend:
1187// step = stepexpr
1188// endcond = endexpr
1189//
1190// curvar = load var
1191// nextvar = curvar + step
1192// store nextvar -> var
1193// br endcond, loop, endloop
1194// outloop:
1195Value *ForExprAST::codegen() {
1196 Function *TheFunction = Builder->GetInsertBlock()->getParent();
1197
1198 // Create an alloca for the variable in the entry block.
1199 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
1200
1201 // Emit the start code first, without 'variable' in scope.
1202 Value *StartVal = Start->codegen();
1203 if (!StartVal)
1204 return nullptr;
1205
1206 // Store the value into the alloca.
1207 Builder->CreateStore(StartVal, Alloca);
1208
1209 // Make the new basic block for the loop header, inserting after current
1210 // block.
1211 BasicBlock *LoopBB = BasicBlock::Create(*TheContext, "loop", TheFunction);
1212
1213 // Insert an explicit fall through from the current block to the LoopBB.
1214 Builder->CreateBr(LoopBB);
1215
1216 // Start insertion in LoopBB.
1217 Builder->SetInsertPoint(LoopBB);
1218
1219 // Within the loop, the variable is defined equal to the PHI node. If it
1220 // shadows an existing variable, we have to restore it, so save it now.
1221 AllocaInst *OldVal = NamedValues[VarName];
1222 NamedValues[VarName] = Alloca;
1223
1224 // Emit the body of the loop. This, like any other expr, can change the
1225 // current BB. Note that we ignore the value computed by the body, but don't
1226 // allow an error.
1227 if (!Body->codegen())
1228 return nullptr;
1229
1230 // Emit the step value.
1231 Value *StepVal = nullptr;
1232 if (Step) {
1233 StepVal = Step->codegen();
1234 if (!StepVal)
1235 return nullptr;
1236 } else {
1237 // If not specified, use 1.0.
1238 StepVal = ConstantFP::get(*TheContext, APFloat(1.0));
1239 }
1240
1241 // Compute the end condition.
1242 Value *EndCond = End->codegen();
1243 if (!EndCond)
1244 return nullptr;
1245
1246 // Reload, increment, and restore the alloca. This handles the case where
1247 // the body of the loop mutates the variable.
1248 Value *CurVar = Builder->CreateLoad(Type::getDoubleTy(*TheContext), Alloca,
1249 VarName.c_str());
1250 Value *NextVar = Builder->CreateFAdd(CurVar, StepVal, "nextvar");
1251 Builder->CreateStore(NextVar, Alloca);
1252
1253 // Convert condition to a bool by comparing non-equal to 0.0.
1254 EndCond = Builder->CreateFCmpONE(
1255 EndCond, ConstantFP::get(*TheContext, APFloat(0.0)), "loopcond");
1256
1257 // Create the "after loop" block and insert it.
1258 BasicBlock *AfterBB =
1259 BasicBlock::Create(*TheContext, "afterloop", TheFunction);
1260
1261 // Insert the conditional branch into the end of LoopEndBB.
1262 Builder->CreateCondBr(EndCond, LoopBB, AfterBB);
1263
1264 // Any new code will be inserted in AfterBB.
1265 Builder->SetInsertPoint(AfterBB);
1266
1267 // Restore the unshadowed variable.
1268 if (OldVal)
1269 NamedValues[VarName] = OldVal;
1270 else
1271 NamedValues.erase(VarName);
1272
1273 // for expr always returns 0.0.
1274 return Constant::getNullValue(Type::getDoubleTy(*TheContext));
1275}
1276
1277Value *VarExprAST::codegen() {
1278 Function *TheFunction = Builder->GetInsertBlock()->getParent();
1279 Value *Init = value->codegen();
1280
1281 // if could not generate init then use a default value
1282 if (!Init) {
1283 if(type == VariableType::String){
1284 Init = createString("");
1285 }else if(type == VariableType::Double){
1286 Init = ConstantFP::get(*TheContext, APFloat(0.0));
1287 }else{
1288 return LogErrorV("Fatal crash");
1289 }
1290 }
1291
1292 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, name);
1293 Builder->CreateStore(Init, Alloca);
1294
1295 // Remember this binding.
1296 NamedValues[name] = Alloca;
1297 return Init;
1298}
1299
1300
1301Function *PrototypeAST::codegen() {
1302 // Make the function type: double(double,double) etc.
1303 std::vector<Type *> types;
1304 // Type::getDoubleTy(*TheContext));
1305 for (auto &arg : Args) {
1306 types.push_back(GetTypeAlloc(arg.first));
1307 }
1308
1309 FunctionType *FT =
1310 FunctionType::get(GetTypeAlloc(ReturnType), types, false);
1311 Function *F =
1312 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
1313
1314 // Set names for all arguments.
1315 unsigned Idx = 0;
1316 for (auto &Arg : F->args()) {
1317 VarTypes[Args[Idx].second] = Args[Idx].first;
1318 Arg.setName(Args[Idx++].second);
1319 }
1320 return F;
1321}
1322
1323Function *FunctionAST::codegen() {
1324 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1325 // reference to it for use below.
1326 auto &P = *Proto;
1327
1328 FunctionProtos[Proto->getName()] = std::move(Proto);
1329 Function *TheFunction = getFunction(P.getName());
1330
1331 // Function does not exists inside scope
1332 if (!TheFunction) {
1333 return nullptr;
1334 }
1335
1336 // Create a new basic block to start insertion into.
1337 BasicBlock *block = BasicBlock::Create(*TheContext, "entry", TheFunction);
1338 Builder->SetInsertPoint(block);
1339
1340 // Record the function arguments in the NamedValues map.
1341 NamedValues.clear();
1342 for (auto &Arg : TheFunction->args()) {
1343 // Create an alloca for this variable.
1344 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
1345
1346 // Store the initial value into the alloca.
1347 Builder->CreateStore(&Arg, Alloca);
1348
1349 // Add arguments to variable symbol table.
1350 NamedValues[std::string(Arg.getName())] = Alloca;
1351 }
1352
1353 if (Value *returnValue = Body->codegen()) {
1354 // Finish off the function.
1355 Builder->CreateRet(returnValue);
1356
1357 // Validate the generated code, checking for consistency.
1358 verifyFunction(*TheFunction);
1359 return TheFunction;
1360 }
1361 // Error reading body, remove function.
1362 TheFunction->eraseFromParent();
1363
1364 if (P.isBinaryOp())
1365 BinopPrecedence.erase(P.getOperatorName());
1366 return nullptr;
1367}
1368
1369//===----------------------------------------------------------------------===//
1370// Top-Level parsing and JIT Driver
1371//===----------------------------------------------------------------------===//
1372
1373static void InitializeModuleAndPassManager() {
1374 // Open a new module.
1375 TheContext = std::make_unique<LLVMContext>();
1376 TheModule = std::make_unique<Module>("my cool jit", *TheContext);
1377
1378 // Create a new builder for the module.
1379 Builder = std::make_unique<IRBuilder<>>(*TheContext);
1380}
1381
1382static void HandleFunc() {
1383 if (auto FnAST = ParseFunc()) {
1384 if (auto *FnIR = FnAST->codegen()) {
1385 fprintf(stderr, "Read function definition:");
1386 FnIR->print(errs());
1387 fprintf(stderr, "\n");
1388 }
1389 } else {
1390 // Skip token for error recovery.
1391 getNextToken();
1392 }
1393}
1394
1395static void HandleExtern() {
1396 if (auto ProtoAST = ParseExtern()) {
1397 if (auto *FnIR = ProtoAST->codegen()) {
1398 fprintf(stderr, "Read extern: ");
1399 FnIR->print(errs());
1400 fprintf(stderr, "\n");
1401 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
1402 }
1403 } else {
1404 // Skip token for error recovery.
1405 getNextToken();
1406 }
1407}
1408
1409static void HandleTopLevelExpression() {
1410 // Evaluate a top-level expression into an anonymous function.
1411 if (auto FnAST = ParseTopLevelExpr()) {
1412 FnAST->codegen();
1413 } else {
1414 // Skip token for error recovery.
1415 getNextToken();
1416 }
1417}
1418
1419/// top ::= definition | external | expression | ';'
1420static void MainLoop() {
1421 while (true) {
1422 switch (CurTok) {
1423 case tok_eof:
1424 return;
1425 case ';': // ignore top-level semicolons.
1426 getNextToken();
1427 break;
1428 case tok_func:
1429 HandleFunc();
1430 break;
1431 case tok_extern:
1432 HandleExtern();
1433 break;
1434 default:
1435 HandleTopLevelExpression();
1436 break;
1437 }
1438 }
1439}
1440
1441//===----------------------------------------------------------------------===//
1442// "Library" functions that can be "extern'd" from user code.
1443//===----------------------------------------------------------------------===//
1444
1445#ifdef _WIN32
1446#define DLLEXPORT __declspec(dllexport)
1447#else
1448#define DLLEXPORT
1449#endif
1450
1451/// putchard - putchar that takes a double and returns 0.
1452extern "C" DLLEXPORT double putchard(double X) {
1453 fputc((char)X, stderr);
1454 return 0;
1455}
1456
1457/// printd - printf that takes a double prints it as "%f\n", returning 0.
1458extern "C" DLLEXPORT double printd(double X) {
1459 fprintf(stderr, "%f\n", X);
1460 return 0;
1461}
1462
1463//===----------------------------------------------------------------------===//
1464// Main driver code.
1465//===----------------------------------------------------------------------===//
1466
1467int main() {
1468 // Install standard binary operators.
1469 // 1 is lowest precedence.
1470 BinopPrecedence['='] = 2;
1471 BinopPrecedence['<'] = 10;
1472 BinopPrecedence['+'] = 20;
1473 BinopPrecedence['-'] = 20;
1474 BinopPrecedence['*'] = 40; // highest.
1475
1476 // Prime the first token.
1477 fprintf(stderr, "stalk> ");
1478 getNextToken();
1479
1480 InitializeModuleAndPassManager();
1481
1482 // Run the main "interpreter loop" now.
1483 MainLoop();
1484
1485 // Initialize the target registry etc.
1486 InitializeAllTargetInfos();
1487 InitializeAllTargets();
1488 InitializeAllTargetMCs();
1489 InitializeAllAsmParsers();
1490 InitializeAllAsmPrinters();
1491
1492 auto TargetTriple = sys::getDefaultTargetTriple();
1493 TheModule->setTargetTriple(TargetTriple);
1494
1495 std::string Error;
1496 auto Target = TargetRegistry::lookupTarget(TargetTriple, Error);
1497
1498 // Print an error and exit if we couldn't find the requested target.
1499 // This generally occurs if we've forgotten to initialise the
1500 // TargetRegistry or we have a bogus target triple.
1501 if (!Target) {
1502 errs() << Error;
1503 return 1;
1504 }
1505
1506 auto CPU = "generic";
1507 auto Features = "";
1508
1509 TargetOptions opt;
1510 auto RM = Optional<Reloc::Model>();
1511 auto TheTargetMachine =
1512 Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM);
1513
1514 TheModule->setDataLayout(TheTargetMachine->createDataLayout());
1515
1516 auto Filename = "output.o";
1517 std::error_code EC;
1518 raw_fd_ostream dest(Filename, EC, sys::fs::OF_None);
1519
1520 if (EC) {
1521 errs() << "Could not open file: " << EC.message();
1522 return 1;
1523 }
1524
1525 legacy::PassManager pass;
1526 auto FileType = CGFT_ObjectFile;
1527
1528 if (TheTargetMachine->addPassesToEmitFile(pass, dest, nullptr, FileType)) {
1529 errs() << "TheTargetMachine can't emit a file of this type";
1530 return 1;
1531 }
1532
1533 pass.run(*TheModule);
1534 dest.flush();
1535
1536 outs() << "Wrote " << Filename << "\n";
1537
1538 return 0;
1539}
1540