@@ -333,6 +333,25 @@ private String newCondAtom(ParseTree treeNode) {
333333 return "" ;
334334 }
335335
336+ private String compOpToLlvmOp (String compOp ) {
337+ switch (compOp ) {
338+ case "==" :
339+ return "eq" ;
340+ case "<" :
341+ return "slt" ;
342+ case "<=" :
343+ return "sle" ;
344+ default :
345+ throw new IllegalStateException ("Unknow comparison opeartor: " + compOp );
346+ }
347+ }
348+
349+ /**
350+ * Write a new comparison in llvm ir.
351+ *
352+ * @param treeNode node of the comparison.
353+ * @return String id of the unamed i32 holding the result.
354+ */
336355 private String newCondComp (ParseTree treeNode ) {
337356
338357 List <ParseTree > children = treeNode .getChildren ();
@@ -341,30 +360,39 @@ private String newCondComp(ParseTree treeNode) {
341360 String op = null ;
342361 String righti32Id = null ;
343362
363+ // lest
344364 lefti32Id = newExprArith (children .get (0 ));
345365
346- LexicalUnit type = child .getLabel ().getType ();
366+ // comparison operator
367+ ParseTree comp = children .get (1 );
368+ LexicalUnit opType = comp .getLabel ().getType ();
347369
348- if (type == LexicalUnit .EQUAL || type == LexicalUnit .SMALLER || type == LexicalUnit .SMALEQ ) {
349- op = child .getLabel ().getValue ().toString ();
350- break ;
370+ if (opType == LexicalUnit .EQUAL || opType == LexicalUnit .SMALLER || opType == LexicalUnit .SMALEQ ) {
371+ op = comp .getLabel ().getValue ().toString ();
351372 }
352373
374+ // right
353375 righti32Id = newExprArith (children .get (2 ));
354376
377+ String compId = compOpToLlvmOp (op );
378+
379+ String resultId = newUnamedI32Id ();
380+ newLine ("; Comparison" );
381+ newLine (resultId + " = icmp " + compId + " i32 " + lefti32Id + ", " + righti32Id );
382+
383+ return resultId ;
355384 }
356385
357386 private void newWhile (ParseTree treeNode ) {
358387 ParseTree condNode = null ;
359388 ParseTree codeNode = null ;
360389
361390 List <ParseTree > children = treeNode .getChildren ();
362- for (int i = 0 ; i < children .size (); i ++) {
363- ParseTree child = children .get (i );
391+ for (ParseTree child : children ) {
364392 if (child .getLabel ().getValue () == NonTerminal .COND_IMPL ) {
365393 condNode = child ;
366- } else if (child .getLabel ().getType () == LexicalUnit . DO ) {
367- codeNode = children . get ( 1 + i ) ;
394+ } else if (child .getLabel ().getValue () == NonTerminal . CODE ) {
395+ codeNode = child ;
368396 }
369397 }
370398
@@ -374,13 +402,14 @@ private void newWhile(ParseTree treeNode) {
374402 String endWhileLabel = newLabel ();
375403
376404 // condition check
405+ newLine ("; Condition check" );
377406 newLine ("br label %" + startWhileLabel );
378407 newLine (startWhileLabel + ":" );
379408 indentLevel ++;
380- String condId = newCond (condNode );
409+ String condResultId = newCond (condNode );
381410 newLine (
382411 "br i1 " +
383- condId +
412+ condResultId +
384413 ", label %" +
385414 codeWhileLabel +
386415 ", label %" +
0 commit comments