Chapter8.cpp 40 KB

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