]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
7f30bb11bdb24f719b8f57b4899c41b107a12b29
[cc65] / src / cc65 / expr.c
1 /* expr.c
2  *
3  * Ullrich von Bassewitz, 21.06.1998
4  */
5
6
7
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 /* common */
12 #include "check.h"
13 #include "debugflag.h"
14 #include "xmalloc.h"
15
16 /* cc65 */
17 #include "asmcode.h"
18 #include "asmlabel.h"
19 #include "asmstmt.h"
20 #include "assignment.h"
21 #include "codegen.h"
22 #include "declare.h"
23 #include "error.h"
24 #include "funcdesc.h"
25 #include "function.h"
26 #include "global.h"
27 #include "litpool.h"
28 #include "loadexpr.h"
29 #include "macrotab.h"
30 #include "preproc.h"
31 #include "scanner.h"
32 #include "shiftexpr.h"
33 #include "stackptr.h"
34 #include "standard.h"
35 #include "stdfunc.h"
36 #include "symtab.h"
37 #include "typecmp.h"
38 #include "typeconv.h"
39 #include "expr.h"
40
41
42
43 /*****************************************************************************/
44 /*                                   Data                                    */
45 /*****************************************************************************/
46
47
48
49 /* Generator attributes */
50 #define GEN_NOPUSH      0x01            /* Don't push lhs */
51
52 /* Map a generator function and its attributes to a token */
53 typedef struct {
54     token_t       Tok;                  /* Token to map to */
55     unsigned      Flags;                /* Flags for generator function */
56     void          (*Func) (unsigned, unsigned long);    /* Generator func */
57 } GenDesc;
58
59 /* Descriptors for the operations */
60 static GenDesc GenPASGN  = { TOK_PLUS_ASSIGN,   GEN_NOPUSH,     g_add };
61 static GenDesc GenSASGN  = { TOK_MINUS_ASSIGN,  GEN_NOPUSH,     g_sub };
62 static GenDesc GenMASGN  = { TOK_MUL_ASSIGN,    GEN_NOPUSH,     g_mul };
63 static GenDesc GenDASGN  = { TOK_DIV_ASSIGN,    GEN_NOPUSH,     g_div };
64 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN,    GEN_NOPUSH,     g_mod };
65 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN,    GEN_NOPUSH,     g_asl };
66 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN,    GEN_NOPUSH,     g_asr };
67 static GenDesc GenAASGN  = { TOK_AND_ASSIGN,    GEN_NOPUSH,     g_and };
68 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN,    GEN_NOPUSH,     g_xor };
69 static GenDesc GenOASGN  = { TOK_OR_ASSIGN,     GEN_NOPUSH,     g_or  };
70
71
72
73 /*****************************************************************************/
74 /*                             Helper functions                              */
75 /*****************************************************************************/
76
77
78
79 static unsigned GlobalModeFlags (const ExprDesc* Expr)
80 /* Return the addressing mode flags for the given expression */
81 {
82     switch (ED_GetLoc (Expr)) {
83         case E_LOC_ABS:         return CF_ABSOLUTE;
84         case E_LOC_GLOBAL:      return CF_EXTERNAL;
85         case E_LOC_STATIC:      return CF_STATIC;
86         case E_LOC_REGISTER:    return CF_REGVAR;
87         case E_LOC_STACK:       return CF_NONE;
88         case E_LOC_PRIMARY:     return CF_NONE;
89         case E_LOC_EXPR:        return CF_NONE;
90         case E_LOC_LITERAL:     return CF_STATIC;       /* Same as static */
91         default:
92             Internal ("GlobalModeFlags: Invalid location flags value: 0x%04X", Expr->Flags);
93             /* NOTREACHED */
94             return 0;
95     }
96 }
97
98
99
100 void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
101 /* Call an expression function with checks. */
102 {
103     /* Remember the stack pointer */
104     int OldSP = StackPtr;
105
106     /* Call the expression function */
107     (*Func) (Expr);
108
109     /* Do some checks if code generation is still constistent */
110     if (StackPtr != OldSP) {
111         if (Debug) {
112             fprintf (stderr,
113                      "Code generation messed up!\n"
114                      "StackPtr is %d, should be %d",
115                      StackPtr, OldSP);
116         } else {
117             Internal ("StackPtr is %d, should be %d\n", StackPtr, OldSP);
118         }
119     }
120 }
121
122
123
124 void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
125 /* Call an expression function with checks and record start and end of the
126  * generated code.
127  */
128 {
129     CodeMark Start, End;
130     GetCodePos (&Start);
131     ExprWithCheck (Func, Expr);
132     GetCodePos (&End);
133     ED_SetCodeRange (Expr, &Start, &End);
134 }
135
136
137
138 static Type* promoteint (Type* lhst, Type* rhst)
139 /* In an expression with two ints, return the type of the result */
140 {
141     /* Rules for integer types:
142      *   - If one of the values is a long, the result is long.
143      *   - If one of the values is unsigned, the result is also unsigned.
144      *   - Otherwise the result is an int.
145      */
146     if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
147         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
148             return type_ulong;
149         } else {
150             return type_long;
151         }
152     } else {
153         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
154             return type_uint;
155         } else {
156             return type_int;
157         }
158     }
159 }
160
161
162
163 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
164 /* Adjust the two values for a binary operation. lhs is expected on stack or
165  * to be constant, rhs is expected to be in the primary register or constant.
166  * The function will put the type of the result into lhs and return the
167  * code generator flags for the operation.
168  * If NoPush is given, it is assumed that the operation does not expect the lhs
169  * to be on stack, and that lhs is in a register instead.
170  * Beware: The function does only accept int types.
171  */
172 {
173     unsigned ltype, rtype;
174     unsigned flags;
175
176     /* Get the type strings */
177     Type* lhst = lhs->Type;
178     Type* rhst = rhs->Type;
179
180     /* Generate type adjustment code if needed */
181     ltype = TypeOf (lhst);
182     if (ED_IsLocAbs (lhs)) {
183         ltype |= CF_CONST;
184     }
185     if (NoPush) {
186         /* Value is in primary register*/
187         ltype |= CF_REG;
188     }
189     rtype = TypeOf (rhst);
190     if (ED_IsLocAbs (rhs)) {
191         rtype |= CF_CONST;
192     }
193     flags = g_typeadjust (ltype, rtype);
194
195     /* Set the type of the result */
196     lhs->Type = promoteint (lhst, rhst);
197
198     /* Return the code generator flags */
199     return flags;
200 }
201
202
203
204 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
205 /* Find a token in a generator table */
206 {
207     while (Table->Tok != TOK_INVALID) {
208         if (Table->Tok == Tok) {
209             return Table;
210         }
211         ++Table;
212     }
213     return 0;
214 }
215
216
217
218 static int TypeSpecAhead (void)
219 /* Return true if some sort of type is waiting (helper for cast and sizeof()
220  * in hie10).
221  */
222 {
223     SymEntry* Entry;
224
225     /* There's a type waiting if:
226      *
227      * We have an opening paren, and
228      *   a.  the next token is a type, or
229      *   b.  the next token is a type qualifier, or
230      *   c.  the next token is a typedef'd type
231      */
232     return CurTok.Tok == TOK_LPAREN && (
233            TokIsType (&NextTok)                         ||
234            TokIsTypeQual (&NextTok)                     ||
235            (NextTok.Tok  == TOK_IDENT                   &&
236            (Entry = FindSym (NextTok.Ident)) != 0       &&
237            SymIsTypeDef (Entry)));
238 }
239
240
241
242 void PushAddr (const ExprDesc* Expr)
243 /* If the expression contains an address that was somehow evaluated,
244  * push this address on the stack. This is a helper function for all
245  * sorts of implicit or explicit assignment functions where the lvalue
246  * must be saved if it's not constant, before evaluating the rhs.
247  */
248 {
249     /* Get the address on stack if needed */
250     if (ED_IsLocExpr (Expr)) {
251         /* Push the address (always a pointer) */
252         g_push (CF_PTR, 0);
253     }
254 }
255
256
257
258 /*****************************************************************************/
259 /*                                   code                                    */
260 /*****************************************************************************/
261
262
263
264 static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall)
265 /* Parse a function parameter list and pass the parameters to the called
266  * function. Depending on several criteria this may be done by just pushing
267  * each parameter separately, or creating the parameter frame once and then
268  * storing into this frame.
269  * The function returns the size of the parameters pushed.
270  */
271 {
272     ExprDesc Expr;
273
274     /* Initialize variables */
275     SymEntry* Param       = 0;  /* Keep gcc silent */
276     unsigned  ParamSize   = 0;  /* Size of parameters pushed */
277     unsigned  ParamCount  = 0;  /* Number of parameters pushed */
278     unsigned  FrameSize   = 0;  /* Size of parameter frame */
279     unsigned  FrameParams = 0;  /* Number of params in frame */
280     int       FrameOffs   = 0;  /* Offset into parameter frame */
281     int       Ellipsis    = 0;  /* Function is variadic */
282
283     /* As an optimization, we may allocate the complete parameter frame at
284      * once instead of pushing each parameter as it comes. We may do that,
285      * if...
286      *
287      *  - optimizations that increase code size are enabled (allocating the
288      *    stack frame at once gives usually larger code).
289      *  - we have more than one parameter to push (don't count the last param
290      *    for __fastcall__ functions).
291      *
292      * The FrameSize variable will contain a value > 0 if storing into a frame
293      * (instead of pushing) is enabled.
294      *
295      */
296     if (IS_Get (&CodeSizeFactor) >= 200) {
297
298         /* Calculate the number and size of the parameters */
299         FrameParams = Func->ParamCount;
300         FrameSize   = Func->ParamSize;
301         if (FrameParams > 0 && IsFastcall) {
302             /* Last parameter is not pushed */
303             FrameSize -= CheckedSizeOf (Func->LastParam->Type);
304             --FrameParams;
305         }
306
307         /* Do we have more than one parameter in the frame? */
308         if (FrameParams > 1) {
309             /* Okeydokey, setup the frame */
310             FrameOffs = StackPtr;
311             g_space (FrameSize);
312             StackPtr -= FrameSize;
313         } else {
314             /* Don't use a preallocated frame */
315             FrameSize = 0;
316         }
317     }
318
319     /* Parse the actual parameter list */
320     while (CurTok.Tok != TOK_RPAREN) {
321
322         unsigned Flags;
323
324         /* Count arguments */
325         ++ParamCount;
326
327         /* Fetch the pointer to the next argument, check for too many args */
328         if (ParamCount <= Func->ParamCount) {
329             /* Beware: If there are parameters with identical names, they
330              * cannot go into the same symbol table, which means that in this
331              * case of errorneous input, the number of nodes in the symbol
332              * table and ParamCount are NOT equal. We have to handle this case
333              * below to avoid segmentation violations. Since we know that this
334              * problem can only occur if there is more than one parameter,
335              * we will just use the last one.
336              */
337             if (ParamCount == 1) {
338                 /* First argument */
339                 Param = Func->SymTab->SymHead;
340             } else if (Param->NextSym != 0) {
341                 /* Next argument */
342                 Param = Param->NextSym;
343                 CHECK ((Param->Flags & SC_PARAM) != 0);
344             }
345         } else if (!Ellipsis) {
346             /* Too many arguments. Do we have an open param list? */
347             if ((Func->Flags & FD_VARIADIC) == 0) {
348                 /* End of param list reached, no ellipsis */
349                 Error ("Too many arguments in function call");
350             }
351             /* Assume an ellipsis even in case of errors to avoid an error
352              * message for each other argument.
353              */
354             Ellipsis = 1;
355         }
356
357         /* Evaluate the parameter expression */
358         hie1 (&Expr);
359
360         /* If we don't have an argument spec, accept anything, otherwise
361          * convert the actual argument to the type needed.
362          */
363         Flags = CF_NONE;
364         if (!Ellipsis) {
365
366             /* Convert the argument to the parameter type if needed */
367             TypeConversion (&Expr, Param->Type);
368
369             /* If we have a prototype, chars may be pushed as chars */
370             Flags |= CF_FORCECHAR;
371
372         } else {
373
374             /* No prototype available. Convert array to "pointer to first
375              * element", and function to "pointer to function".
376              */
377             Expr.Type = PtrConversion (Expr.Type);
378
379         }
380
381         /* Load the value into the primary if it is not already there */
382         LoadExpr (Flags, &Expr);
383
384         /* Use the type of the argument for the push */
385         Flags |= TypeOf (Expr.Type);
386
387         /* If this is a fastcall function, don't push the last argument */
388         if (ParamCount != Func->ParamCount || !IsFastcall) {
389             unsigned ArgSize = sizeofarg (Flags);
390             if (FrameSize > 0) {
391                 /* We have the space already allocated, store in the frame.
392                  * Because of invalid type conversions (that have produced an
393                  * error before), we can end up here with a non aligned stack
394                  * frame. Since no output will be generated anyway, handle
395                  * these cases gracefully instead of doing a CHECK.
396                  */
397                 if (FrameSize >= ArgSize) {
398                     FrameSize -= ArgSize;
399                 } else {
400                     FrameSize = 0;
401                 }
402                 FrameOffs -= ArgSize;
403                 /* Store */
404                 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
405             } else {
406                 /* Push the argument */
407                 g_push (Flags, Expr.IVal);
408             }
409
410             /* Calculate total parameter size */
411             ParamSize += ArgSize;
412         }
413
414         /* Check for end of argument list */
415         if (CurTok.Tok != TOK_COMMA) {
416             break;
417         }
418         NextToken ();
419     }
420
421     /* Check if we had enough parameters */
422     if (ParamCount < Func->ParamCount) {
423         Error ("Too few arguments in function call");
424     }
425
426     /* The function returns the size of all parameters pushed onto the stack.
427      * However, if there are parameters missing (which is an error and was
428      * flagged by the compiler) AND a stack frame was preallocated above,
429      * we would loose track of the stackpointer and generate an internal error
430      * later. So we correct the value by the parameters that should have been
431      * pushed to avoid an internal compiler error. Since an error was
432      * generated before, no code will be output anyway.
433      */
434     return ParamSize + FrameSize;
435 }
436
437
438
439 static void FunctionCall (ExprDesc* Expr)
440 /* Perform a function call. */
441 {
442     FuncDesc*     Func;           /* Function descriptor */
443     int           IsFuncPtr;      /* Flag */
444     unsigned      ParamSize;      /* Number of parameter bytes */
445     CodeMark      Mark;
446     int           PtrOffs = 0;    /* Offset of function pointer on stack */
447     int           IsFastcall = 0; /* True if it's a fast call function */
448     int           PtrOnStack = 0; /* True if a pointer copy is on stack */
449
450     /* Skip the left paren */
451     NextToken ();
452
453     /* Get a pointer to the function descriptor from the type string */
454     Func = GetFuncDesc (Expr->Type);
455
456     /* Handle function pointers transparently */
457     IsFuncPtr = IsTypeFuncPtr (Expr->Type);
458     if (IsFuncPtr) {
459
460         /* Check wether it's a fastcall function that has parameters */
461         IsFastcall = IsQualFastcall (Expr->Type + 1) && (Func->ParamCount > 0);
462
463         /* Things may be difficult, depending on where the function pointer
464          * resides. If the function pointer is an expression of some sort
465          * (not a local or global variable), we have to evaluate this
466          * expression now and save the result for later. Since calls to
467          * function pointers may be nested, we must save it onto the stack.
468          * For fastcall functions we do also need to place a copy of the
469          * pointer on stack, since we cannot use a/x.
470          */
471         PtrOnStack = IsFastcall || !ED_IsConst (Expr);
472         if (PtrOnStack) {
473
474             /* Not a global or local variable, or a fastcall function. Load
475              * the pointer into the primary and mark it as an expression.
476              */
477             LoadExpr (CF_NONE, Expr);
478             ED_MakeRValExpr (Expr);
479
480             /* Remember the code position */
481             GetCodePos (&Mark);
482
483             /* Push the pointer onto the stack and remember the offset */
484             g_push (CF_PTR, 0);
485             PtrOffs = StackPtr;
486         }
487
488     } else {
489         /* Check for known standard functions and inline them */
490         if (Expr->Name != 0) {
491             int StdFunc = FindStdFunc ((const char*) Expr->Name);
492             if (StdFunc >= 0) {
493                 /* Inline this function */
494                 HandleStdFunc (StdFunc, Func, Expr);
495                 return;
496             }
497         }
498
499         /* If we didn't inline the function, get fastcall info */
500         IsFastcall = IsQualFastcall (Expr->Type);
501     }
502
503     /* Parse the parameter list */
504     ParamSize = FunctionParamList (Func, IsFastcall);
505
506     /* We need the closing paren here */
507     ConsumeRParen ();
508
509     /* Special handling for function pointers */
510     if (IsFuncPtr) {
511
512         /* If the function is not a fastcall function, load the pointer to
513          * the function into the primary.
514          */
515         if (!IsFastcall) {
516
517             /* Not a fastcall function - we may use the primary */
518             if (PtrOnStack) {
519                 /* If we have no parameters, the pointer is still in the
520                  * primary. Remove the code to push it and correct the
521                  * stack pointer.
522                  */
523                 if (ParamSize == 0) {
524                     RemoveCode (&Mark);
525                     PtrOnStack = 0;
526                 } else {
527                     /* Load from the saved copy */
528                     g_getlocal (CF_PTR, PtrOffs);
529                 }
530             } else {
531                 /* Load from original location */
532                 LoadExpr (CF_NONE, Expr);
533             }
534
535             /* Call the function */
536             g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
537
538         } else {
539
540             /* Fastcall function. We cannot use the primary for the function
541              * pointer and must therefore use an offset to the stack location.
542              * Since fastcall functions may never be variadic, we can use the
543              * index register for this purpose.
544              */
545             g_callind (CF_LOCAL, ParamSize, PtrOffs);
546         }
547
548         /* If we have a pointer on stack, remove it */
549         if (PtrOnStack) {
550             g_space (- (int) sizeofarg (CF_PTR));
551             pop (CF_PTR);
552         }
553
554         /* Skip T_PTR */
555         ++Expr->Type;
556
557     } else {
558
559         /* Normal function */
560         g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
561
562     }
563
564     /* The function result is an rvalue in the primary register */
565     ED_MakeRValExpr (Expr);
566     Expr->Type = GetFuncReturn (Expr->Type);
567 }
568
569
570
571 static void Primary (ExprDesc* E)
572 /* This is the lowest level of the expression parser. */
573 {
574     SymEntry* Sym;
575
576     /* Initialize fields in the expression stucture */
577     ED_Init (E);
578
579     /* Character and integer constants. */
580     if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
581         E->IVal  = CurTok.IVal;
582         E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
583         E->Type  = CurTok.Type;
584         NextToken ();
585         return;
586     }
587
588     /* Floating point constant */
589     if (CurTok.Tok == TOK_FCONST) {
590         E->FVal  = CurTok.FVal;
591         E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
592         E->Type  = CurTok.Type;
593         NextToken ();
594         return;
595     }
596
597     /* Process parenthesized subexpression by calling the whole parser
598      * recursively.
599      */
600     if (CurTok.Tok == TOK_LPAREN) {
601         NextToken ();
602         hie0 (E);
603         ConsumeRParen ();
604         return;
605     }
606
607     /* If we run into an identifier in preprocessing mode, we assume that this
608      * is an undefined macro and replace it by a constant value of zero.
609      */
610     if (Preprocessing && CurTok.Tok == TOK_IDENT) {
611         NextToken ();
612         ED_MakeConstAbsInt (E, 0);
613         return;
614     }
615
616     /* All others may only be used if the expression evaluation is not called
617      * recursively by the preprocessor.
618      */
619     if (Preprocessing) {
620         /* Illegal expression in PP mode */
621         Error ("Preprocessor expression expected");
622         ED_MakeConstAbsInt (E, 1);
623         return;
624     }
625
626     switch (CurTok.Tok) {
627
628         case TOK_IDENT:
629             /* Identifier. Get a pointer to the symbol table entry */
630             Sym = E->Sym = FindSym (CurTok.Ident);
631
632             /* Is the symbol known? */
633             if (Sym) {
634
635                 /* We found the symbol - skip the name token */
636                 NextToken ();
637
638                 /* Check for illegal symbol types */
639                 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
640                 if (Sym->Flags & SC_TYPE) {
641                     /* Cannot use type symbols */
642                     Error ("Variable identifier expected");
643                     /* Assume an int type to make E valid */
644                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
645                     E->Type  = type_int;
646                     return;
647                 }
648
649                 /* Mark the symbol as referenced */
650                 Sym->Flags |= SC_REF;
651
652                 /* The expression type is the symbol type */
653                 E->Type = Sym->Type;
654
655                 /* Check for legal symbol types */
656                 if ((Sym->Flags & SC_CONST) == SC_CONST) {
657                     /* Enum or some other numeric constant */
658                     E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
659                     E->IVal = Sym->V.ConstVal;
660                 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
661                     /* Function */
662                     E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
663                     E->Name = (unsigned long) Sym->Name;
664                 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
665                     /* Local variable. If this is a parameter for a variadic
666                      * function, we have to add some address calculations, and the
667                      * address is not const.
668                      */
669                     if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
670                         /* Variadic parameter */
671                         g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
672                         E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
673                     } else {
674                         /* Normal parameter */
675                         E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
676                         E->IVal  = Sym->V.Offs;
677                     }
678                 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
679                     /* Register variable, zero page based */
680                     E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
681                     E->Name  = Sym->V.R.RegOffs;
682                 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
683                     /* Static variable */
684                     if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
685                         E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
686                         E->Name = (unsigned long) Sym->Name;
687                     } else {
688                         E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
689                         E->Name = Sym->V.Label;
690                     }
691                 } else {
692                     /* Local static variable */
693                     E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
694                     E->Name  = Sym->V.Offs;
695                 }
696
697                 /* We've made all variables lvalues above. However, this is
698                  * not always correct: An array is actually the address of its
699                  * first element, which is a rvalue, and a function is a
700                  * rvalue, too, because we cannot store anything in a function.
701                  * So fix the flags depending on the type.
702                  */
703                 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
704                     ED_MakeRVal (E);
705                 }
706
707             } else {
708
709                 /* We did not find the symbol. Remember the name, then skip it */
710                 ident Ident;
711                 strcpy (Ident, CurTok.Ident);
712                 NextToken ();
713
714                 /* IDENT is either an auto-declared function or an undefined variable. */
715                 if (CurTok.Tok == TOK_LPAREN) {
716                     /* C99 doesn't allow calls to undefined functions, so
717                      * generate an error and otherwise a warning. Declare a
718                      * function returning int. For that purpose, prepare a
719                      * function signature for a function having an empty param
720                      * list and returning int.
721                      */
722                     if (IS_Get (&Standard) >= STD_C99) {
723                         Error ("Call to undefined function `%s'", Ident);
724                     } else {
725                         Warning ("Call to undefined function `%s'", Ident);
726                     }
727                     Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
728                     E->Type  = Sym->Type;
729                     E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
730                     E->Name  = (unsigned long) Sym->Name;
731                 } else {
732                     /* Undeclared Variable */
733                     Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
734                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
735                     E->Type = type_int;
736                     Error ("Undefined symbol: `%s'", Ident);
737                 }
738
739             }
740             break;
741
742         case TOK_SCONST:
743             /* String literal */
744             E->Type  = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
745             E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
746             E->IVal  = CurTok.IVal;
747             E->Name  = LiteralPoolLabel;
748             NextToken ();
749             break;
750
751         case TOK_ASM:
752             /* ASM statement */
753             AsmStatement ();
754             E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
755             E->Type  = type_void;
756             break;
757
758         case TOK_A:
759             /* Register pseudo variable */
760             E->Type  = type_uchar;
761             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
762             NextToken ();
763             break;
764
765         case TOK_AX:
766             /* Register pseudo variable */
767             E->Type  = type_uint;
768             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
769             NextToken ();
770             break;
771
772         case TOK_EAX:
773             /* Register pseudo variable */
774             E->Type  = type_ulong;
775             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
776             NextToken ();
777             break;
778
779         default:
780             /* Illegal primary. Be sure to skip the token to avoid endless
781              * error loops.
782              */
783             Error ("Expression expected");
784             NextToken ();
785             ED_MakeConstAbsInt (E, 1);
786             break;
787     }
788 }
789
790
791
792 static void ArrayRef (ExprDesc* Expr)
793 /* Handle an array reference. This function needs a rewrite. */
794 {
795     int         ConstBaseAddr;
796     ExprDesc    Subscript;
797     CodeMark    Mark1;
798     CodeMark    Mark2;
799     Type*       ElementType;
800     Type*       tptr1;
801
802
803     /* Skip the bracket */
804     NextToken ();
805
806     /* Get the type of left side */
807     tptr1 = Expr->Type;
808
809     /* We can apply a special treatment for arrays that have a const base
810      * address. This is true for most arrays and will produce a lot better
811      * code. Check if this is a const base address.
812      */
813     ConstBaseAddr = ED_IsRVal (Expr) &&
814                     (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
815
816     /* If we have a constant base, we delay the address fetch */
817     GetCodePos (&Mark1);
818     if (!ConstBaseAddr) {
819         /* Get a pointer to the array into the primary */
820         LoadExpr (CF_NONE, Expr);
821
822         /* Get the array pointer on stack. Do not push more than 16
823          * bit, even if this value is greater, since we cannot handle
824          * other than 16bit stuff when doing indexing.
825          */
826         GetCodePos (&Mark2);
827         g_push (CF_PTR, 0);
828     }
829
830     /* TOS now contains ptr to array elements. Get the subscript. */
831     ExprWithCheck (hie0, &Subscript);
832
833     /* Check the types of array and subscript. We can either have a
834      * pointer/array to the left, in which case the subscript must be of an
835      * integer type, or we have an integer to the left, in which case the
836      * subscript must be a pointer/array.
837      * Since we do the necessary checking here, we can rely later on the
838      * correct types.
839      */
840     if (IsClassPtr (Expr->Type)) {
841         if (!IsClassInt (Subscript.Type))  {
842             Error ("Array subscript is not an integer");
843             /* To avoid any compiler errors, make the expression a valid int */
844             ED_MakeConstAbsInt (&Subscript, 0);
845         }
846         ElementType = Indirect (Expr->Type);
847     } else if (IsClassInt (Expr->Type)) {
848         if (!IsClassPtr (Subscript.Type)) {
849             Error ("Subscripted value is neither array nor pointer");
850             /* To avoid compiler errors, make the subscript a char[] at
851              * address 0.
852              */
853             ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
854         }
855         ElementType = Indirect (Subscript.Type);
856     } else {
857         Error ("Cannot subscript");
858         /* To avoid compiler errors, fake both the array and the subscript, so
859          * we can just proceed.
860          */
861         ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
862         ED_MakeConstAbsInt (&Subscript, 0);
863         ElementType = Indirect (Expr->Type);
864     }
865
866     /* If the subscript is a bit-field, load it and make it an rvalue */
867     if (ED_IsBitField (&Subscript)) {
868         LoadExpr (CF_NONE, &Subscript);
869         ED_MakeRValExpr (&Subscript);
870     }
871
872     /* Check if the subscript is constant absolute value */
873     if (ED_IsConstAbs (&Subscript)) {
874
875         /* The array subscript is a numeric constant. If we had pushed the
876          * array base address onto the stack before, we can remove this value,
877          * since we can generate expression+offset.
878          */
879         if (!ConstBaseAddr) {
880             RemoveCode (&Mark2);
881         } else {
882             /* Get an array pointer into the primary */
883             LoadExpr (CF_NONE, Expr);
884         }
885
886         if (IsClassPtr (Expr->Type)) {
887
888             /* Lhs is pointer/array. Scale the subscript value according to
889              * the element size.
890              */
891             Subscript.IVal *= CheckedSizeOf (ElementType);
892
893             /* Remove the address load code */
894             RemoveCode (&Mark1);
895
896             /* In case of an array, we can adjust the offset of the expression
897              * already in Expr. If the base address was a constant, we can even
898              * remove the code that loaded the address into the primary.
899              */
900             if (IsTypeArray (Expr->Type)) {
901
902                 /* Adjust the offset */
903                 Expr->IVal += Subscript.IVal;
904
905             } else {
906
907                 /* It's a pointer, so we do have to load it into the primary
908                  * first (if it's not already there).
909                  */
910                 if (ConstBaseAddr || ED_IsLVal (Expr)) {
911                     LoadExpr (CF_NONE, Expr);
912                     ED_MakeRValExpr (Expr);
913                 }
914
915                 /* Use the offset */
916                 Expr->IVal = Subscript.IVal;
917             }
918
919         } else {
920
921             /* Scale the rhs value according to the element type */
922             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
923
924             /* Add the subscript. Since arrays are indexed by integers,
925              * we will ignore the true type of the subscript here and
926              * use always an int. #### Use offset but beware of LoadExpr!
927              */
928             g_inc (CF_INT | CF_CONST, Subscript.IVal);
929
930         }
931
932     } else {
933
934         /* Array subscript is not constant. Load it into the primary */
935         GetCodePos (&Mark2);
936         LoadExpr (CF_NONE, &Subscript);
937
938         /* Do scaling */
939         if (IsClassPtr (Expr->Type)) {
940
941             /* Indexing is based on unsigneds, so we will just use the integer
942              * portion of the index (which is in (e)ax, so there's no further
943              * action required).
944              */
945             g_scale (CF_INT, CheckedSizeOf (ElementType));
946
947         } else {
948
949             /* Get the int value on top. If we come here, we're sure, both
950              * values are 16 bit (the first one was truncated if necessary
951              * and the second one is a pointer). Note: If ConstBaseAddr is
952              * true, we don't have a value on stack, so to "swap" both, just
953              * push the subscript.
954              */
955             if (ConstBaseAddr) {
956                 g_push (CF_INT, 0);
957                 LoadExpr (CF_NONE, Expr);
958                 ConstBaseAddr = 0;
959             } else {
960                 g_swap (CF_INT);
961             }
962
963             /* Scale it */
964             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
965
966         }
967
968         /* The offset is now in the primary register. It we didn't have a
969          * constant base address for the lhs, the lhs address is already
970          * on stack, and we must add the offset. If the base address was
971          * constant, we call special functions to add the address to the
972          * offset value.
973          */
974         if (!ConstBaseAddr) {
975
976             /* The array base address is on stack and the subscript is in the
977              * primary. Add both.
978              */
979             g_add (CF_INT, 0);
980
981         } else {
982
983             /* The subscript is in the primary, and the array base address is
984              * in Expr. If the subscript has itself a constant address, it is
985              * often a better idea to reverse again the order of the
986              * evaluation. This will generate better code if the subscript is
987              * a byte sized variable. But beware: This is only possible if the
988              * subscript was not scaled, that is, if this was a byte array
989              * or pointer.
990              */
991             if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
992                 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
993
994                 unsigned Flags;
995
996                 /* Reverse the order of evaluation */
997                 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
998                     Flags = CF_CHAR;
999                 } else {
1000                     Flags = CF_INT;
1001                 }
1002                 RemoveCode (&Mark2);
1003
1004                 /* Get a pointer to the array into the primary. */
1005                 LoadExpr (CF_NONE, Expr);
1006
1007                 /* Add the variable */
1008                 if (ED_IsLocStack (&Subscript)) {
1009                     g_addlocal (Flags, Subscript.IVal);
1010                 } else {
1011                     Flags |= GlobalModeFlags (&Subscript);
1012                     g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1013                 }
1014             } else {
1015
1016                 if (ED_IsLocAbs (Expr)) {
1017                     /* Constant numeric address. Just add it */
1018                     g_inc (CF_INT, Expr->IVal);
1019                 } else if (ED_IsLocStack (Expr)) {
1020                     /* Base address is a local variable address */
1021                     if (IsTypeArray (Expr->Type)) {
1022                         g_addaddr_local (CF_INT, Expr->IVal);
1023                     } else {
1024                         g_addlocal (CF_PTR, Expr->IVal);
1025                     }
1026                 } else {
1027                     /* Base address is a static variable address */
1028                     unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1029                     if (ED_IsRVal (Expr)) {
1030                         /* Add the address of the location */
1031                         g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1032                     } else {
1033                         /* Add the contents of the location */
1034                         g_addstatic (Flags, Expr->Name, Expr->IVal);
1035                     }
1036                 }
1037             }
1038
1039
1040         }
1041
1042         /* The result is an expression in the primary */
1043         ED_MakeRValExpr (Expr);
1044
1045     }
1046
1047     /* Result is of element type */
1048     Expr->Type = ElementType;
1049
1050     /* An array element is actually a variable. So the rules for variables
1051      * with respect to the reference type apply: If it's an array, it is
1052      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1053      * but an array cannot contain functions).
1054      */
1055     if (IsTypeArray (Expr->Type)) {
1056         ED_MakeRVal (Expr);
1057     } else {
1058         ED_MakeLVal (Expr);
1059     }
1060
1061     /* Consume the closing bracket */
1062     ConsumeRBrack ();
1063 }
1064
1065
1066
1067 static void StructRef (ExprDesc* Expr)
1068 /* Process struct field after . or ->. */
1069 {
1070     ident Ident;
1071     SymEntry* Field;
1072
1073     /* Skip the token and check for an identifier */
1074     NextToken ();
1075     if (CurTok.Tok != TOK_IDENT) {
1076         Error ("Identifier expected");
1077         Expr->Type = type_int;
1078         return;
1079     }
1080
1081     /* Get the symbol table entry and check for a struct field */
1082     strcpy (Ident, CurTok.Ident);
1083     NextToken ();
1084     Field = FindStructField (Expr->Type, Ident);
1085     if (Field == 0) {
1086         Error ("Struct/union has no field named `%s'", Ident);
1087         Expr->Type = type_int;
1088         return;
1089     }
1090
1091     /* If we have a struct pointer that is an lvalue and not already in the
1092      * primary, load it now.
1093      */
1094     if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1095
1096         /* Load into the primary */
1097         LoadExpr (CF_NONE, Expr);
1098
1099         /* Make it an lvalue expression */
1100         ED_MakeLValExpr (Expr);
1101     }
1102
1103     /* Set the struct field offset */
1104     Expr->IVal += Field->V.Offs;
1105
1106     /* The type is now the type of the field */
1107     Expr->Type = Field->Type;
1108
1109     /* An struct member is actually a variable. So the rules for variables
1110      * with respect to the reference type apply: If it's an array, it is
1111      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1112      * but a struct field cannot be a function).
1113      */
1114     if (IsTypeArray (Expr->Type)) {
1115         ED_MakeRVal (Expr);
1116     } else {
1117         ED_MakeLVal (Expr);
1118     }
1119
1120     /* Make the expression a bit field if necessary */
1121     if (SymIsBitField (Field)) {
1122         ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1123     }
1124 }
1125
1126
1127
1128 static void hie11 (ExprDesc *Expr)
1129 /* Handle compound types (structs and arrays) */
1130 {
1131     /* Name value used in invalid function calls */
1132     static const char IllegalFunc[] = "illegal_function_call";
1133
1134     /* Evaluate the lhs */
1135     Primary (Expr);
1136
1137     /* Check for a rhs */
1138     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1139            CurTok.Tok == TOK_DOT    || CurTok.Tok == TOK_PTR_REF) {
1140
1141         switch (CurTok.Tok) {
1142
1143             case TOK_LBRACK:
1144                 /* Array reference */
1145                 ArrayRef (Expr);
1146                 break;
1147
1148             case TOK_LPAREN:
1149                 /* Function call. */
1150                 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1151                     /* Not a function */
1152                     Error ("Illegal function call");
1153                     /* Force the type to be a implicitly defined function, one
1154                      * returning an int and taking any number of arguments.
1155                      * Since we don't have a name, invent one.
1156                      */
1157                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1158                     Expr->Name = (long) IllegalFunc;
1159                 }
1160                 /* Call the function */
1161                 FunctionCall (Expr);
1162                 break;
1163
1164             case TOK_DOT:
1165                 if (!IsClassStruct (Expr->Type)) {
1166                     Error ("Struct expected");
1167                 }
1168                 StructRef (Expr);
1169                 break;
1170
1171             case TOK_PTR_REF:
1172                 /* If we have an array, convert it to pointer to first element */
1173                 if (IsTypeArray (Expr->Type)) {
1174                     Expr->Type = ArrayToPtr (Expr->Type);
1175                 }
1176                 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1177                     Error ("Struct pointer expected");
1178                 }
1179                 StructRef (Expr);
1180                 break;
1181
1182             default:
1183                 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1184
1185         }
1186     }
1187 }
1188
1189
1190
1191 void Store (ExprDesc* Expr, const Type* StoreType)
1192 /* Store the primary register into the location denoted by Expr. If StoreType
1193  * is given, use this type when storing instead of Expr->Type. If StoreType
1194  * is NULL, use Expr->Type instead.
1195  */
1196 {
1197     unsigned Flags;
1198
1199     /* If StoreType was not given, use Expr->Type instead */
1200     if (StoreType == 0) {
1201         StoreType = Expr->Type;
1202     }
1203
1204     /* Prepare the code generator flags */
1205     Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1206
1207     /* Do the store depending on the location */
1208     switch (ED_GetLoc (Expr)) {
1209
1210         case E_LOC_ABS:
1211             /* Absolute: numeric address or const */
1212             g_putstatic (Flags, Expr->IVal, 0);
1213             break;
1214
1215         case E_LOC_GLOBAL:
1216             /* Global variable */
1217             g_putstatic (Flags, Expr->Name, Expr->IVal);
1218             break;
1219
1220         case E_LOC_STATIC:
1221         case E_LOC_LITERAL:
1222             /* Static variable or literal in the literal pool */
1223             g_putstatic (Flags, Expr->Name, Expr->IVal);
1224             break;
1225
1226         case E_LOC_REGISTER:
1227             /* Register variable */
1228             g_putstatic (Flags, Expr->Name, Expr->IVal);
1229             break;
1230
1231         case E_LOC_STACK:
1232             /* Value on the stack */
1233             g_putlocal (Flags, Expr->IVal, 0);
1234             break;
1235
1236         case E_LOC_PRIMARY:
1237             /* The primary register (value is already there) */
1238             break;
1239
1240         case E_LOC_EXPR:
1241             /* An expression in the primary register */
1242             g_putind (Flags, Expr->IVal);
1243             break;
1244
1245         default:
1246             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1247     }
1248
1249     /* Assume that each one of the stores will invalidate CC */
1250     ED_MarkAsUntested (Expr);
1251 }
1252
1253
1254
1255 static void PreInc (ExprDesc* Expr)
1256 /* Handle the preincrement operators */
1257 {
1258     unsigned Flags;
1259     unsigned long Val;
1260
1261     /* Skip the operator token */
1262     NextToken ();
1263
1264     /* Evaluate the expression and check that it is an lvalue */
1265     hie10 (Expr);
1266     if (!ED_IsLVal (Expr)) {
1267         Error ("Invalid lvalue");
1268         return;
1269     }
1270
1271     /* We cannot modify const values */
1272     if (IsQualConst (Expr->Type)) {
1273         Error ("Increment of read-only variable");
1274     }
1275
1276     /* Get the data type */
1277     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1278
1279     /* Get the increment value in bytes */
1280     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1281
1282     /* Check the location of the data */
1283     switch (ED_GetLoc (Expr)) {
1284
1285         case E_LOC_ABS:
1286             /* Absolute: numeric address or const */
1287             g_addeqstatic (Flags, Expr->IVal, 0, Val);
1288             break;
1289
1290         case E_LOC_GLOBAL:
1291             /* Global variable */
1292             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1293             break;
1294
1295         case E_LOC_STATIC:
1296         case E_LOC_LITERAL:
1297             /* Static variable or literal in the literal pool */
1298             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1299             break;
1300
1301         case E_LOC_REGISTER:
1302             /* Register variable */
1303             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1304             break;
1305
1306         case E_LOC_STACK:
1307             /* Value on the stack */
1308             g_addeqlocal (Flags, Expr->IVal, Val);
1309             break;
1310
1311         case E_LOC_PRIMARY:
1312             /* The primary register */
1313             g_inc (Flags, Val);
1314             break;
1315
1316         case E_LOC_EXPR:
1317             /* An expression in the primary register */
1318             g_addeqind (Flags, Expr->IVal, Val);
1319             break;
1320
1321         default:
1322             Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1323     }
1324
1325     /* Result is an expression, no reference */
1326     ED_MakeRValExpr (Expr);
1327 }
1328
1329
1330
1331 static void PreDec (ExprDesc* Expr)
1332 /* Handle the predecrement operators */
1333 {
1334     unsigned Flags;
1335     unsigned long Val;
1336
1337     /* Skip the operator token */
1338     NextToken ();
1339
1340     /* Evaluate the expression and check that it is an lvalue */
1341     hie10 (Expr);
1342     if (!ED_IsLVal (Expr)) {
1343         Error ("Invalid lvalue");
1344         return;
1345     }
1346
1347     /* We cannot modify const values */
1348     if (IsQualConst (Expr->Type)) {
1349         Error ("Decrement of read-only variable");
1350     }
1351
1352     /* Get the data type */
1353     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1354
1355     /* Get the increment value in bytes */
1356     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1357
1358     /* Check the location of the data */
1359     switch (ED_GetLoc (Expr)) {
1360
1361         case E_LOC_ABS:
1362             /* Absolute: numeric address or const */
1363             g_subeqstatic (Flags, Expr->IVal, 0, Val);
1364             break;
1365
1366         case E_LOC_GLOBAL:
1367             /* Global variable */
1368             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1369             break;
1370
1371         case E_LOC_STATIC:
1372         case E_LOC_LITERAL:
1373             /* Static variable or literal in the literal pool */
1374             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1375             break;
1376
1377         case E_LOC_REGISTER:
1378             /* Register variable */
1379             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1380             break;
1381
1382         case E_LOC_STACK:
1383             /* Value on the stack */
1384             g_subeqlocal (Flags, Expr->IVal, Val);
1385             break;
1386
1387         case E_LOC_PRIMARY:
1388             /* The primary register */
1389             g_inc (Flags, Val);
1390             break;
1391
1392         case E_LOC_EXPR:
1393             /* An expression in the primary register */
1394             g_subeqind (Flags, Expr->IVal, Val);
1395             break;
1396
1397         default:
1398             Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1399     }
1400
1401     /* Result is an expression, no reference */
1402     ED_MakeRValExpr (Expr);
1403 }
1404
1405
1406
1407 static void PostInc (ExprDesc* Expr)
1408 /* Handle the postincrement operator */
1409 {
1410     unsigned Flags;
1411
1412     NextToken ();
1413
1414     /* The expression to increment must be an lvalue */
1415     if (!ED_IsLVal (Expr)) {
1416         Error ("Invalid lvalue");
1417         return;
1418     }
1419
1420     /* We cannot modify const values */
1421     if (IsQualConst (Expr->Type)) {
1422         Error ("Increment of read-only variable");
1423     }
1424
1425     /* Get the data type */
1426     Flags = TypeOf (Expr->Type);
1427
1428     /* Push the address if needed */
1429     PushAddr (Expr);
1430
1431     /* Fetch the value and save it (since it's the result of the expression) */
1432     LoadExpr (CF_NONE, Expr);
1433     g_save (Flags | CF_FORCECHAR);
1434
1435     /* If we have a pointer expression, increment by the size of the type */
1436     if (IsTypePtr (Expr->Type)) {
1437         g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1438     } else {
1439         g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1440     }
1441
1442     /* Store the result back */
1443     Store (Expr, 0);
1444
1445     /* Restore the original value in the primary register */
1446     g_restore (Flags | CF_FORCECHAR);
1447
1448     /* The result is always an expression, no reference */
1449     ED_MakeRValExpr (Expr);
1450 }
1451
1452
1453
1454 static void PostDec (ExprDesc* Expr)
1455 /* Handle the postdecrement operator */
1456 {
1457     unsigned Flags;
1458
1459     NextToken ();
1460
1461     /* The expression to increment must be an lvalue */
1462     if (!ED_IsLVal (Expr)) {
1463         Error ("Invalid lvalue");
1464         return;
1465     }
1466
1467     /* We cannot modify const values */
1468     if (IsQualConst (Expr->Type)) {
1469         Error ("Decrement of read-only variable");
1470     }
1471
1472     /* Get the data type */
1473     Flags = TypeOf (Expr->Type);
1474
1475     /* Push the address if needed */
1476     PushAddr (Expr);
1477
1478     /* Fetch the value and save it (since it's the result of the expression) */
1479     LoadExpr (CF_NONE, Expr);
1480     g_save (Flags | CF_FORCECHAR);
1481
1482     /* If we have a pointer expression, increment by the size of the type */
1483     if (IsTypePtr (Expr->Type)) {
1484         g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1485     } else {
1486         g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1487     }
1488
1489     /* Store the result back */
1490     Store (Expr, 0);
1491
1492     /* Restore the original value in the primary register */
1493     g_restore (Flags | CF_FORCECHAR);
1494
1495     /* The result is always an expression, no reference */
1496     ED_MakeRValExpr (Expr);
1497 }
1498
1499
1500
1501 static void UnaryOp (ExprDesc* Expr)
1502 /* Handle unary -/+ and ~ */
1503 {
1504     unsigned Flags;
1505
1506     /* Remember the operator token and skip it */
1507     token_t Tok = CurTok.Tok;
1508     NextToken ();
1509
1510     /* Get the expression */
1511     hie10 (Expr);
1512
1513     /* We can only handle integer types */
1514     if (!IsClassInt (Expr->Type)) {
1515         Error ("Argument must have integer type");
1516         ED_MakeConstAbsInt (Expr, 1);
1517     }
1518
1519     /* Check for a constant expression */
1520     if (ED_IsConstAbs (Expr)) {
1521         /* Value is constant */
1522         switch (Tok) {
1523             case TOK_MINUS: Expr->IVal = -Expr->IVal;   break;
1524             case TOK_PLUS:                              break;
1525             case TOK_COMP:  Expr->IVal = ~Expr->IVal;   break;
1526             default:        Internal ("Unexpected token: %d", Tok);
1527         }
1528     } else {
1529         /* Value is not constant */
1530         LoadExpr (CF_NONE, Expr);
1531
1532         /* Get the type of the expression */
1533         Flags = TypeOf (Expr->Type);
1534
1535         /* Handle the operation */
1536         switch (Tok) {
1537             case TOK_MINUS: g_neg (Flags);  break;
1538             case TOK_PLUS:                  break;
1539             case TOK_COMP:  g_com (Flags);  break;
1540             default:        Internal ("Unexpected token: %d", Tok);
1541         }
1542
1543         /* The result is a rvalue in the primary */
1544         ED_MakeRValExpr (Expr);
1545     }
1546 }
1547
1548
1549
1550 void hie10 (ExprDesc* Expr)
1551 /* Handle ++, --, !, unary - etc. */
1552 {
1553     unsigned long Size;
1554
1555     switch (CurTok.Tok) {
1556
1557         case TOK_INC:
1558             PreInc (Expr);
1559             break;
1560
1561         case TOK_DEC:
1562             PreDec (Expr);
1563             break;
1564
1565         case TOK_PLUS:
1566         case TOK_MINUS:
1567         case TOK_COMP:
1568             UnaryOp (Expr);
1569             break;
1570
1571         case TOK_BOOL_NOT:
1572             NextToken ();
1573             if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1574                 /* Constant expression */
1575                 Expr->IVal = !Expr->IVal;
1576             } else {
1577                 g_bneg (TypeOf (Expr->Type));
1578                 ED_MakeRValExpr (Expr);
1579                 ED_TestDone (Expr);             /* bneg will set cc */
1580             }
1581             break;
1582
1583         case TOK_STAR:
1584             NextToken ();
1585             ExprWithCheck (hie10, Expr);
1586             if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1587                 /* Not a const, load it into the primary and make it a
1588                  * calculated value.
1589                  */
1590                 LoadExpr (CF_NONE, Expr);
1591                 ED_MakeRValExpr (Expr);
1592             }
1593             /* If the expression is already a pointer to function, the
1594              * additional dereferencing operator must be ignored.
1595              */
1596             if (IsTypeFuncPtr (Expr->Type)) {
1597                 /* Expression not storable */
1598                 ED_MakeRVal (Expr);
1599             } else {
1600                 if (IsClassPtr (Expr->Type)) {
1601                     Expr->Type = Indirect (Expr->Type);
1602                 } else {
1603                     Error ("Illegal indirection");
1604                 }
1605                 /* The * operator yields an lvalue */
1606                 ED_MakeLVal (Expr);
1607             }
1608             break;
1609
1610         case TOK_AND:
1611             NextToken ();
1612             ExprWithCheck (hie10, Expr);
1613             /* The & operator may be applied to any lvalue, and it may be
1614              * applied to functions, even if they're no lvalues.
1615              */
1616             if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1617                 Error ("Illegal address");
1618             } else {
1619                 if (ED_IsBitField (Expr)) {
1620                     Error ("Cannot take address of bit-field");
1621                     /* Do it anyway, just to avoid further warnings */
1622                     Expr->Flags &= ~E_BITFIELD;
1623                 }
1624                 Expr->Type = PointerTo (Expr->Type);
1625                 /* The & operator yields an rvalue */
1626                 ED_MakeRVal (Expr);
1627             }
1628             break;
1629
1630         case TOK_SIZEOF:
1631             NextToken ();
1632             if (TypeSpecAhead ()) {
1633                 Type T[MAXTYPELEN];
1634                 NextToken ();
1635                 Size = CheckedSizeOf (ParseType (T));
1636                 ConsumeRParen ();
1637             } else {
1638                 /* Remember the output queue pointer */
1639                 CodeMark Mark;
1640                 GetCodePos (&Mark);
1641                 hie10 (Expr);
1642                 Size = CheckedSizeOf (Expr->Type);
1643                 /* Remove any generated code */
1644                 RemoveCode (&Mark);
1645             }
1646             ED_MakeConstAbs (Expr, Size, type_size_t);
1647             ED_MarkAsUntested (Expr);
1648             break;
1649
1650         default:
1651             if (TypeSpecAhead ()) {
1652
1653                 /* A typecast */
1654                 TypeCast (Expr);
1655
1656             } else {
1657
1658                 /* An expression */
1659                 hie11 (Expr);
1660
1661                 /* Handle post increment */
1662                 switch (CurTok.Tok) {
1663                     case TOK_INC:   PostInc (Expr); break;
1664                     case TOK_DEC:   PostDec (Expr); break;
1665                     default:                        break;
1666                 }
1667
1668             }
1669             break;
1670     }
1671 }
1672
1673
1674
1675 static void hie_internal (const GenDesc* Ops,   /* List of generators */
1676                           ExprDesc* Expr,
1677                           void (*hienext) (ExprDesc*),
1678                           int* UsedGen)
1679 /* Helper function */
1680 {
1681     ExprDesc Expr2;
1682     CodeMark Mark1;
1683     CodeMark Mark2;
1684     const GenDesc* Gen;
1685     token_t Tok;                        /* The operator token */
1686     unsigned ltype, type;
1687     int rconst;                         /* Operand is a constant */
1688
1689
1690     hienext (Expr);
1691
1692     *UsedGen = 0;
1693     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1694
1695         /* Tell the caller that we handled it's ops */
1696         *UsedGen = 1;
1697
1698         /* All operators that call this function expect an int on the lhs */
1699         if (!IsClassInt (Expr->Type)) {
1700             Error ("Integer expression expected");
1701             /* To avoid further errors, make Expr a valid int expression */
1702             ED_MakeConstAbsInt (Expr, 1);
1703         }
1704
1705         /* Remember the operator token, then skip it */
1706         Tok = CurTok.Tok;
1707         NextToken ();
1708
1709         /* Get the lhs on stack */
1710         GetCodePos (&Mark1);
1711         ltype = TypeOf (Expr->Type);
1712         if (ED_IsConstAbs (Expr)) {
1713             /* Constant value */
1714             GetCodePos (&Mark2);
1715             g_push (ltype | CF_CONST, Expr->IVal);
1716         } else {
1717             /* Value not constant */
1718             LoadExpr (CF_NONE, Expr);
1719             GetCodePos (&Mark2);
1720             g_push (ltype, 0);
1721         }
1722
1723         /* Get the right hand side */
1724         rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1725
1726         /* Check the type of the rhs */
1727         if (!IsClassInt (Expr2.Type)) {
1728             Error ("Integer expression expected");
1729         }
1730
1731         /* Check for const operands */
1732         if (ED_IsConstAbs (Expr) && rconst) {
1733
1734             /* Both operands are constant, remove the generated code */
1735             RemoveCode (&Mark1);
1736
1737             /* Get the type of the result */
1738             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1739
1740             /* Handle the op differently for signed and unsigned types */
1741             if (IsSignSigned (Expr->Type)) {
1742
1743                 /* Evaluate the result for signed operands */
1744                 signed long Val1 = Expr->IVal;
1745                 signed long Val2 = Expr2.IVal;
1746                 switch (Tok) {
1747                     case TOK_OR:
1748                         Expr->IVal = (Val1 | Val2);
1749                         break;
1750                     case TOK_XOR:
1751                         Expr->IVal = (Val1 ^ Val2);
1752                         break;
1753                     case TOK_AND:
1754                         Expr->IVal = (Val1 & Val2);
1755                         break;
1756                     case TOK_STAR:
1757                         Expr->IVal = (Val1 * Val2);
1758                         break;
1759                     case TOK_DIV:
1760                         if (Val2 == 0) {
1761                             Error ("Division by zero");
1762                             Expr->IVal = 0x7FFFFFFF;
1763                         } else {
1764                             Expr->IVal = (Val1 / Val2);
1765                         }
1766                         break;
1767                     case TOK_MOD:
1768                         if (Val2 == 0) {
1769                             Error ("Modulo operation with zero");
1770                             Expr->IVal = 0;
1771                         } else {
1772                             Expr->IVal = (Val1 % Val2);
1773                         }
1774                         break;
1775                     default:
1776                         Internal ("hie_internal: got token 0x%X\n", Tok);
1777                 }
1778             } else {
1779
1780                 /* Evaluate the result for unsigned operands */
1781                 unsigned long Val1 = Expr->IVal;
1782                 unsigned long Val2 = Expr2.IVal;
1783                 switch (Tok) {
1784                     case TOK_OR:
1785                         Expr->IVal = (Val1 | Val2);
1786                         break;
1787                     case TOK_XOR:
1788                         Expr->IVal = (Val1 ^ Val2);
1789                         break;
1790                     case TOK_AND:
1791                         Expr->IVal = (Val1 & Val2);
1792                         break;
1793                     case TOK_STAR:
1794                         Expr->IVal = (Val1 * Val2);
1795                         break;
1796                     case TOK_DIV:
1797                         if (Val2 == 0) {
1798                             Error ("Division by zero");
1799                             Expr->IVal = 0xFFFFFFFF;
1800                         } else {
1801                             Expr->IVal = (Val1 / Val2);
1802                         }
1803                         break;
1804                     case TOK_MOD:
1805                         if (Val2 == 0) {
1806                             Error ("Modulo operation with zero");
1807                             Expr->IVal = 0;
1808                         } else {
1809                             Expr->IVal = (Val1 % Val2);
1810                         }
1811                         break;
1812                     default:
1813                         Internal ("hie_internal: got token 0x%X\n", Tok);
1814                 }
1815             }
1816
1817         } else {
1818
1819             /* If the right hand side is constant, and the generator function
1820              * expects the lhs in the primary, remove the push of the primary
1821              * now.
1822              */
1823             unsigned rtype = TypeOf (Expr2.Type);
1824             type = 0;
1825             if (rconst) {
1826                 /* Second value is constant - check for div */
1827                 type |= CF_CONST;
1828                 rtype |= CF_CONST;
1829                 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1830                     Error ("Division by zero");
1831                 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1832                     Error ("Modulo operation with zero");
1833                 }
1834                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1835                     RemoveCode (&Mark2);
1836                     ltype |= CF_REG;    /* Value is in register */
1837                 }
1838             }
1839
1840             /* Determine the type of the operation result. */
1841             type |= g_typeadjust (ltype, rtype);
1842             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1843
1844             /* Generate code */
1845             Gen->Func (type, Expr2.IVal);
1846
1847             /* We have a rvalue in the primary now */
1848             ED_MakeRValExpr (Expr);
1849         }
1850     }
1851 }
1852
1853
1854
1855 static void hie_compare (const GenDesc* Ops,    /* List of generators */
1856                          ExprDesc* Expr,
1857                          void (*hienext) (ExprDesc*))
1858 /* Helper function for the compare operators */
1859 {
1860     ExprDesc Expr2;
1861     CodeMark Mark1;
1862     CodeMark Mark2;
1863     const GenDesc* Gen;
1864     token_t Tok;                        /* The operator token */
1865     unsigned ltype;
1866     int rconst;                         /* Operand is a constant */
1867
1868
1869     hienext (Expr);
1870
1871     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1872
1873         /* Remember the operator token, then skip it */
1874         Tok = CurTok.Tok;
1875         NextToken ();
1876
1877         /* Get the lhs on stack */
1878         GetCodePos (&Mark1);
1879         ltype = TypeOf (Expr->Type);
1880         if (ED_IsConstAbs (Expr)) {
1881             /* Constant value */
1882             GetCodePos (&Mark2);
1883             g_push (ltype | CF_CONST, Expr->IVal);
1884         } else {
1885             /* Value not constant */
1886             LoadExpr (CF_NONE, Expr);
1887             GetCodePos (&Mark2);
1888             g_push (ltype, 0);
1889         }
1890
1891         /* Get the right hand side */
1892         rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1893
1894         /* Make sure, the types are compatible */
1895         if (IsClassInt (Expr->Type)) {
1896             if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1897                 Error ("Incompatible types");
1898             }
1899         } else if (IsClassPtr (Expr->Type)) {
1900             if (IsClassPtr (Expr2.Type)) {
1901                 /* Both pointers are allowed in comparison if they point to
1902                  * the same type, or if one of them is a void pointer.
1903                  */
1904                 Type* left  = Indirect (Expr->Type);
1905                 Type* right = Indirect (Expr2.Type);
1906                 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
1907                     /* Incomatible pointers */
1908                     Error ("Incompatible types");
1909                 }
1910             } else if (!ED_IsNullPtr (&Expr2)) {
1911                 Error ("Incompatible types");
1912             }
1913         }
1914
1915         /* Check for const operands */
1916         if (ED_IsConstAbs (Expr) && rconst) {
1917
1918             /* If the result is constant, this is suspicious when not in
1919              * preprocessor mode.
1920              */
1921             if (!Preprocessing) {
1922                 Warning ("Result of comparison is constant");
1923             }
1924
1925             /* Both operands are constant, remove the generated code */
1926             RemoveCode (&Mark1);
1927
1928             /* Determine if this is a signed or unsigned compare */
1929             if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
1930                 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
1931
1932                 /* Evaluate the result for signed operands */
1933                 signed long Val1 = Expr->IVal;
1934                 signed long Val2 = Expr2.IVal;
1935                 switch (Tok) {
1936                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
1937                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
1938                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
1939                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
1940                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
1941                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
1942                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
1943                 }
1944
1945             } else {
1946
1947                 /* Evaluate the result for unsigned operands */
1948                 unsigned long Val1 = Expr->IVal;
1949                 unsigned long Val2 = Expr2.IVal;
1950                 switch (Tok) {
1951                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
1952                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
1953                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
1954                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
1955                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
1956                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
1957                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
1958                 }
1959             }
1960
1961         } else {
1962
1963             /* If the right hand side is constant, and the generator function
1964              * expects the lhs in the primary, remove the push of the primary
1965              * now.
1966              */
1967             unsigned flags = 0;
1968             if (rconst) {
1969                 flags |= CF_CONST;
1970                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1971                     RemoveCode (&Mark2);
1972                     ltype |= CF_REG;    /* Value is in register */
1973                 }
1974             }
1975
1976             /* Determine the type of the operation result. If the left
1977              * operand is of type char and the right is a constant, or
1978              * if both operands are of type char, we will encode the
1979              * operation as char operation. Otherwise the default
1980              * promotions are used.
1981              */
1982             if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
1983                 flags |= CF_CHAR;
1984                 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
1985                     flags |= CF_UNSIGNED;
1986                 }
1987                 if (rconst) {
1988                     flags |= CF_FORCECHAR;
1989                 }
1990             } else {
1991                 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
1992                 flags |= g_typeadjust (ltype, rtype);
1993             }
1994
1995             /* Generate code */
1996             Gen->Func (flags, Expr2.IVal);
1997
1998             /* The result is an rvalue in the primary */
1999             ED_MakeRValExpr (Expr);
2000         }
2001
2002         /* Result type is always int */
2003         Expr->Type = type_int;
2004
2005         /* Condition codes are set */
2006         ED_TestDone (Expr);
2007     }
2008 }
2009
2010
2011
2012 static void hie9 (ExprDesc *Expr)
2013 /* Process * and / operators. */
2014 {
2015     static const GenDesc hie9_ops[] = {
2016         { TOK_STAR,     GEN_NOPUSH,     g_mul   },
2017         { TOK_DIV,      GEN_NOPUSH,     g_div   },
2018         { TOK_MOD,      GEN_NOPUSH,     g_mod   },
2019         { TOK_INVALID,  0,              0       }
2020     };
2021     int UsedGen;
2022
2023     hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2024 }
2025
2026
2027
2028 static void parseadd (ExprDesc* Expr)
2029 /* Parse an expression with the binary plus operator. Expr contains the
2030  * unprocessed left hand side of the expression and will contain the
2031  * result of the expression on return.
2032  */
2033 {
2034     ExprDesc Expr2;
2035     unsigned flags;             /* Operation flags */
2036     CodeMark Mark;              /* Remember code position */
2037     Type* lhst;                 /* Type of left hand side */
2038     Type* rhst;                 /* Type of right hand side */
2039
2040
2041     /* Skip the PLUS token */
2042     NextToken ();
2043
2044     /* Get the left hand side type, initialize operation flags */
2045     lhst = Expr->Type;
2046     flags = 0;
2047
2048     /* Check for constness on both sides */
2049     if (ED_IsConst (Expr)) {
2050
2051         /* The left hand side is a constant of some sort. Good. Get rhs */
2052         hie9 (&Expr2);
2053         if (ED_IsConstAbs (&Expr2)) {
2054
2055             /* Right hand side is a constant numeric value. Get the rhs type */
2056             rhst = Expr2.Type;
2057
2058             /* Both expressions are constants. Check for pointer arithmetic */
2059             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2060                 /* Left is pointer, right is int, must scale rhs */
2061                 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2062                 /* Result type is a pointer */
2063             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2064                 /* Left is int, right is pointer, must scale lhs */
2065                 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2066                 /* Result type is a pointer */
2067                 Expr->Type = Expr2.Type;
2068             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2069                 /* Integer addition */
2070                 Expr->IVal += Expr2.IVal;
2071                 typeadjust (Expr, &Expr2, 1);
2072             } else {
2073                 /* OOPS */
2074                 Error ("Invalid operands for binary operator `+'");
2075             }
2076
2077         } else {
2078
2079             /* lhs is a constant and rhs is not constant. Load rhs into
2080              * the primary.
2081              */
2082             LoadExpr (CF_NONE, &Expr2);
2083
2084             /* Beware: The check above (for lhs) lets not only pass numeric
2085              * constants, but also constant addresses (labels), maybe even
2086              * with an offset. We have to check for that here.
2087              */
2088
2089             /* First, get the rhs type. */
2090             rhst = Expr2.Type;
2091
2092             /* Setup flags */
2093             if (ED_IsLocAbs (Expr)) {
2094                 /* A numerical constant */
2095                 flags |= CF_CONST;
2096             } else {
2097                 /* Constant address label */
2098                 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2099             }
2100
2101             /* Check for pointer arithmetic */
2102             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2103                 /* Left is pointer, right is int, must scale rhs */
2104                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2105                 /* Operate on pointers, result type is a pointer */
2106                 flags |= CF_PTR;
2107                 /* Generate the code for the add */
2108                 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2109                     /* Numeric constant */
2110                     g_inc (flags, Expr->IVal);
2111                 } else {
2112                     /* Constant address */
2113                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2114                 }
2115             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2116
2117                 /* Left is int, right is pointer, must scale lhs. */
2118                 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2119
2120                 /* Operate on pointers, result type is a pointer */
2121                 flags |= CF_PTR;
2122                 Expr->Type = Expr2.Type;
2123
2124                 /* Since we do already have rhs in the primary, if lhs is
2125                  * not a numeric constant, and the scale factor is not one
2126                  * (no scaling), we must take the long way over the stack.
2127                  */
2128                 if (ED_IsLocAbs (Expr)) {
2129                     /* Numeric constant, scale lhs */
2130                     Expr->IVal *= ScaleFactor;
2131                     /* Generate the code for the add */
2132                     g_inc (flags, Expr->IVal);
2133                 } else if (ScaleFactor == 1) {
2134                     /* Constant address but no need to scale */
2135                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2136                 } else {
2137                     /* Constant address that must be scaled */
2138                     g_push (TypeOf (Expr2.Type), 0);    /* rhs --> stack */
2139                     g_getimmed (flags, Expr->Name, Expr->IVal);
2140                     g_scale (CF_PTR, ScaleFactor);
2141                     g_add (CF_PTR, 0);
2142                 }
2143             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2144                 /* Integer addition */
2145                 flags |= typeadjust (Expr, &Expr2, 1);
2146                 /* Generate the code for the add */
2147                 if (ED_IsLocAbs (Expr)) {
2148                     /* Numeric constant */
2149                     g_inc (flags, Expr->IVal);
2150                 } else {
2151                     /* Constant address */
2152                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2153                 }
2154             } else {
2155                 /* OOPS */
2156                 Error ("Invalid operands for binary operator `+'");
2157                 flags = CF_INT;
2158             }
2159
2160             /* Result is a rvalue in primary register */
2161             ED_MakeRValExpr (Expr);
2162         }
2163
2164     } else {
2165
2166         /* Left hand side is not constant. Get the value onto the stack. */
2167         LoadExpr (CF_NONE, Expr);              /* --> primary register */
2168         GetCodePos (&Mark);
2169         g_push (TypeOf (Expr->Type), 0);        /* --> stack */
2170
2171         /* Evaluate the rhs */
2172         if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2173
2174             /* Right hand side is a constant. Get the rhs type */
2175             rhst = Expr2.Type;
2176
2177             /* Remove pushed value from stack */
2178             RemoveCode (&Mark);
2179
2180             /* Check for pointer arithmetic */
2181             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2182                 /* Left is pointer, right is int, must scale rhs */
2183                 Expr2.IVal *= CheckedPSizeOf (lhst);
2184                 /* Operate on pointers, result type is a pointer */
2185                 flags = CF_PTR;
2186             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2187                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2188                 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2189                 /* Operate on pointers, result type is a pointer */
2190                 flags = CF_PTR;
2191                 Expr->Type = Expr2.Type;
2192             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2193                 /* Integer addition */
2194                 flags = typeadjust (Expr, &Expr2, 1);
2195             } else {
2196                 /* OOPS */
2197                 Error ("Invalid operands for binary operator `+'");
2198                 flags = CF_INT;
2199             }
2200
2201             /* Generate code for the add */
2202             g_inc (flags | CF_CONST, Expr2.IVal);
2203
2204         } else {
2205
2206             /* lhs and rhs are not constant. Get the rhs type. */
2207             rhst = Expr2.Type;
2208
2209             /* Check for pointer arithmetic */
2210             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2211                 /* Left is pointer, right is int, must scale rhs */
2212                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2213                 /* Operate on pointers, result type is a pointer */
2214                 flags = CF_PTR;
2215             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2216                 /* Left is int, right is pointer, must scale lhs */
2217                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2218                 g_swap (CF_INT);                /* Swap TOS and primary */
2219                 g_scale (CF_INT, CheckedPSizeOf (rhst));
2220                 /* Operate on pointers, result type is a pointer */
2221                 flags = CF_PTR;
2222                 Expr->Type = Expr2.Type;
2223             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2224                 /* Integer addition. Note: Result is never constant.
2225                  * Problem here is that typeadjust does not know if the
2226                  * variable is an rvalue or lvalue, so if both operands
2227                  * are dereferenced constant numeric addresses, typeadjust
2228                  * thinks the operation works on constants. Removing
2229                  * CF_CONST here means handling the symptoms, however, the
2230                  * whole parser is such a mess that I fear to break anything
2231                  * when trying to apply another solution.
2232                  */
2233                 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2234             } else {
2235                 /* OOPS */
2236                 Error ("Invalid operands for binary operator `+'");
2237                 flags = CF_INT;
2238             }
2239
2240             /* Generate code for the add */
2241             g_add (flags, 0);
2242
2243         }
2244
2245         /* Result is a rvalue in primary register */
2246         ED_MakeRValExpr (Expr);
2247     }
2248
2249     /* Condition codes not set */
2250     ED_MarkAsUntested (Expr);
2251
2252 }
2253
2254
2255
2256 static void parsesub (ExprDesc* Expr)
2257 /* Parse an expression with the binary minus operator. Expr contains the
2258  * unprocessed left hand side of the expression and will contain the
2259  * result of the expression on return.
2260  */
2261 {
2262     ExprDesc Expr2;
2263     unsigned flags;             /* Operation flags */
2264     Type* lhst;                 /* Type of left hand side */
2265     Type* rhst;                 /* Type of right hand side */
2266     CodeMark Mark1;             /* Save position of output queue */
2267     CodeMark Mark2;             /* Another position in the queue */
2268     int rscale;                 /* Scale factor for the result */
2269
2270
2271     /* Skip the MINUS token */
2272     NextToken ();
2273
2274     /* Get the left hand side type, initialize operation flags */
2275     lhst = Expr->Type;
2276     rscale = 1;                 /* Scale by 1, that is, don't scale */
2277
2278     /* Remember the output queue position, then bring the value onto the stack */
2279     GetCodePos (&Mark1);
2280     LoadExpr (CF_NONE, Expr);  /* --> primary register */
2281     GetCodePos (&Mark2);
2282     g_push (TypeOf (lhst), 0);  /* --> stack */
2283
2284     /* Parse the right hand side */
2285     if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2286
2287         /* The right hand side is constant. Get the rhs type. */
2288         rhst = Expr2.Type;
2289
2290         /* Check left hand side */
2291         if (ED_IsConstAbs (Expr)) {
2292
2293             /* Both sides are constant, remove generated code */
2294             RemoveCode (&Mark1);
2295
2296             /* Check for pointer arithmetic */
2297             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2298                 /* Left is pointer, right is int, must scale rhs */
2299                 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2300                 /* Operate on pointers, result type is a pointer */
2301             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2302                 /* Left is pointer, right is pointer, must scale result */
2303                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2304                     Error ("Incompatible pointer types");
2305                 } else {
2306                     Expr->IVal = (Expr->IVal - Expr2.IVal) /
2307                                       CheckedPSizeOf (lhst);
2308                 }
2309                 /* Operate on pointers, result type is an integer */
2310                 Expr->Type = type_int;
2311             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2312                 /* Integer subtraction */
2313                 typeadjust (Expr, &Expr2, 1);
2314                 Expr->IVal -= Expr2.IVal;
2315             } else {
2316                 /* OOPS */
2317                 Error ("Invalid operands for binary operator `-'");
2318             }
2319
2320             /* Result is constant, condition codes not set */
2321             ED_MarkAsUntested (Expr);
2322
2323         } else {
2324
2325             /* Left hand side is not constant, right hand side is.
2326              * Remove pushed value from stack.
2327              */
2328             RemoveCode (&Mark2);
2329
2330             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2331                 /* Left is pointer, right is int, must scale rhs */
2332                 Expr2.IVal *= CheckedPSizeOf (lhst);
2333                 /* Operate on pointers, result type is a pointer */
2334                 flags = CF_PTR;
2335             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2336                 /* Left is pointer, right is pointer, must scale result */
2337                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2338                     Error ("Incompatible pointer types");
2339                 } else {
2340                     rscale = CheckedPSizeOf (lhst);
2341                 }
2342                 /* Operate on pointers, result type is an integer */
2343                 flags = CF_PTR;
2344                 Expr->Type = type_int;
2345             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2346                 /* Integer subtraction */
2347                 flags = typeadjust (Expr, &Expr2, 1);
2348             } else {
2349                 /* OOPS */
2350                 Error ("Invalid operands for binary operator `-'");
2351                 flags = CF_INT;
2352             }
2353
2354             /* Do the subtraction */
2355             g_dec (flags | CF_CONST, Expr2.IVal);
2356
2357             /* If this was a pointer subtraction, we must scale the result */
2358             if (rscale != 1) {
2359                 g_scale (flags, -rscale);
2360             }
2361
2362             /* Result is a rvalue in the primary register */
2363             ED_MakeRValExpr (Expr);
2364             ED_MarkAsUntested (Expr);
2365
2366         }
2367
2368     } else {
2369
2370         /* Right hand side is not constant. Get the rhs type. */
2371         rhst = Expr2.Type;
2372
2373         /* Check for pointer arithmetic */
2374         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2375             /* Left is pointer, right is int, must scale rhs */
2376             g_scale (CF_INT, CheckedPSizeOf (lhst));
2377             /* Operate on pointers, result type is a pointer */
2378             flags = CF_PTR;
2379         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2380             /* Left is pointer, right is pointer, must scale result */
2381             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2382                 Error ("Incompatible pointer types");
2383             } else {
2384                 rscale = CheckedPSizeOf (lhst);
2385             }
2386             /* Operate on pointers, result type is an integer */
2387             flags = CF_PTR;
2388             Expr->Type = type_int;
2389         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2390             /* Integer subtraction. If the left hand side descriptor says that
2391              * the lhs is const, we have to remove this mark, since this is no
2392              * longer true, lhs is on stack instead.
2393              */
2394             if (ED_IsLocAbs (Expr)) {
2395                 ED_MakeRValExpr (Expr);
2396             }
2397             /* Adjust operand types */
2398             flags = typeadjust (Expr, &Expr2, 0);
2399         } else {
2400             /* OOPS */
2401             Error ("Invalid operands for binary operator `-'");
2402             flags = CF_INT;
2403         }
2404
2405         /* Generate code for the sub (the & is a hack here) */
2406         g_sub (flags & ~CF_CONST, 0);
2407
2408         /* If this was a pointer subtraction, we must scale the result */
2409         if (rscale != 1) {
2410             g_scale (flags, -rscale);
2411         }
2412
2413         /* Result is a rvalue in the primary register */
2414         ED_MakeRValExpr (Expr);
2415         ED_MarkAsUntested (Expr);
2416     }
2417 }
2418
2419
2420
2421 void hie8 (ExprDesc* Expr)
2422 /* Process + and - binary operators. */
2423 {
2424     hie9 (Expr);
2425     while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2426         if (CurTok.Tok == TOK_PLUS) {
2427             parseadd (Expr);
2428         } else {
2429             parsesub (Expr);
2430         }
2431     }
2432 }
2433
2434
2435
2436 static void hie6 (ExprDesc* Expr)
2437 /* Handle greater-than type comparators */
2438 {
2439     static const GenDesc hie6_ops [] = {
2440         { TOK_LT,       GEN_NOPUSH,     g_lt    },
2441         { TOK_LE,       GEN_NOPUSH,     g_le    },
2442         { TOK_GE,       GEN_NOPUSH,     g_ge    },
2443         { TOK_GT,       GEN_NOPUSH,     g_gt    },
2444         { TOK_INVALID,  0,              0       }
2445     };
2446     hie_compare (hie6_ops, Expr, ShiftExpr);
2447 }
2448
2449
2450
2451 static void hie5 (ExprDesc* Expr)
2452 /* Handle == and != */
2453 {
2454     static const GenDesc hie5_ops[] = {
2455         { TOK_EQ,       GEN_NOPUSH,     g_eq    },
2456         { TOK_NE,       GEN_NOPUSH,     g_ne    },
2457         { TOK_INVALID,  0,              0       }
2458     };
2459     hie_compare (hie5_ops, Expr, hie6);
2460 }
2461
2462
2463
2464 static void hie4 (ExprDesc* Expr)
2465 /* Handle & (bitwise and) */
2466 {
2467     static const GenDesc hie4_ops[] = {
2468         { TOK_AND,      GEN_NOPUSH,     g_and   },
2469         { TOK_INVALID,  0,              0       }
2470     };
2471     int UsedGen;
2472
2473     hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2474 }
2475
2476
2477
2478 static void hie3 (ExprDesc* Expr)
2479 /* Handle ^ (bitwise exclusive or) */
2480 {
2481     static const GenDesc hie3_ops[] = {
2482         { TOK_XOR,      GEN_NOPUSH,     g_xor   },
2483         { TOK_INVALID,  0,              0       }
2484     };
2485     int UsedGen;
2486
2487     hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2488 }
2489
2490
2491
2492 static void hie2 (ExprDesc* Expr)
2493 /* Handle | (bitwise or) */
2494 {
2495     static const GenDesc hie2_ops[] = {
2496         { TOK_OR,       GEN_NOPUSH,     g_or    },
2497         { TOK_INVALID,  0,              0       }
2498     };
2499     int UsedGen;
2500
2501     hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2502 }
2503
2504
2505
2506 static void hieAndPP (ExprDesc* Expr)
2507 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2508  * called recursively from the preprocessor.
2509  */
2510 {
2511     ExprDesc Expr2;
2512
2513     ConstAbsIntExpr (hie2, Expr);
2514     while (CurTok.Tok == TOK_BOOL_AND) {
2515
2516         /* Skip the && */
2517         NextToken ();
2518
2519         /* Get rhs */
2520         ConstAbsIntExpr (hie2, &Expr2);
2521
2522         /* Combine the two */
2523         Expr->IVal = (Expr->IVal && Expr2.IVal);
2524     }
2525 }
2526
2527
2528
2529 static void hieOrPP (ExprDesc *Expr)
2530 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2531  * called recursively from the preprocessor.
2532  */
2533 {
2534     ExprDesc Expr2;
2535
2536     ConstAbsIntExpr (hieAndPP, Expr);
2537     while (CurTok.Tok == TOK_BOOL_OR) {
2538
2539         /* Skip the && */
2540         NextToken ();
2541
2542         /* Get rhs */
2543         ConstAbsIntExpr (hieAndPP, &Expr2);
2544
2545         /* Combine the two */
2546         Expr->IVal = (Expr->IVal || Expr2.IVal);
2547     }
2548 }
2549
2550
2551
2552 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2553 /* Process "exp && exp" */
2554 {
2555     int FalseLab;
2556     ExprDesc Expr2;
2557
2558     hie2 (Expr);
2559     if (CurTok.Tok == TOK_BOOL_AND) {
2560
2561         /* Tell our caller that we're evaluating a boolean */
2562         *BoolOp = 1;
2563
2564         /* Get a label that we will use for false expressions */
2565         FalseLab = GetLocalLabel ();
2566
2567         /* If the expr hasn't set condition codes, set the force-test flag */
2568         if (!ED_IsTested (Expr)) {
2569             ED_MarkForTest (Expr);
2570         }
2571
2572         /* Load the value */
2573         LoadExpr (CF_FORCECHAR, Expr);
2574
2575         /* Generate the jump */
2576         g_falsejump (CF_NONE, FalseLab);
2577
2578         /* Parse more boolean and's */
2579         while (CurTok.Tok == TOK_BOOL_AND) {
2580
2581             /* Skip the && */
2582             NextToken ();
2583
2584             /* Get rhs */
2585             hie2 (&Expr2);
2586             if (!ED_IsTested (&Expr2)) {
2587                 ED_MarkForTest (&Expr2);
2588             }
2589             LoadExpr (CF_FORCECHAR, &Expr2);
2590
2591             /* Do short circuit evaluation */
2592             if (CurTok.Tok == TOK_BOOL_AND) {
2593                 g_falsejump (CF_NONE, FalseLab);
2594             } else {
2595                 /* Last expression - will evaluate to true */
2596                 g_truejump (CF_NONE, TrueLab);
2597             }
2598         }
2599
2600         /* Define the false jump label here */
2601         g_defcodelabel (FalseLab);
2602
2603         /* The result is an rvalue in primary */
2604         ED_MakeRValExpr (Expr);
2605         ED_TestDone (Expr);     /* Condition codes are set */
2606     }
2607 }
2608
2609
2610
2611 static void hieOr (ExprDesc *Expr)
2612 /* Process "exp || exp". */
2613 {
2614     ExprDesc Expr2;
2615     int BoolOp = 0;             /* Did we have a boolean op? */
2616     int AndOp;                  /* Did we have a && operation? */
2617     unsigned TrueLab;           /* Jump to this label if true */
2618     unsigned DoneLab;
2619
2620     /* Get a label */
2621     TrueLab = GetLocalLabel ();
2622
2623     /* Call the next level parser */
2624     hieAnd (Expr, TrueLab, &BoolOp);
2625
2626     /* Any boolean or's? */
2627     if (CurTok.Tok == TOK_BOOL_OR) {
2628
2629         /* If the expr hasn't set condition codes, set the force-test flag */
2630         if (!ED_IsTested (Expr)) {
2631             ED_MarkForTest (Expr);
2632         }
2633
2634         /* Get first expr */
2635         LoadExpr (CF_FORCECHAR, Expr);
2636
2637         /* For each expression jump to TrueLab if true. Beware: If we
2638          * had && operators, the jump is already in place!
2639          */
2640         if (!BoolOp) {
2641             g_truejump (CF_NONE, TrueLab);
2642         }
2643
2644         /* Remember that we had a boolean op */
2645         BoolOp = 1;
2646
2647         /* while there's more expr */
2648         while (CurTok.Tok == TOK_BOOL_OR) {
2649
2650             /* skip the || */
2651             NextToken ();
2652
2653             /* Get a subexpr */
2654             AndOp = 0;
2655             hieAnd (&Expr2, TrueLab, &AndOp);
2656             if (!ED_IsTested (&Expr2)) {
2657                 ED_MarkForTest (&Expr2);
2658             }
2659             LoadExpr (CF_FORCECHAR, &Expr2);
2660
2661             /* If there is more to come, add shortcut boolean eval. */
2662             g_truejump (CF_NONE, TrueLab);
2663
2664         }
2665
2666         /* The result is an rvalue in primary */
2667         ED_MakeRValExpr (Expr);
2668         ED_TestDone (Expr);                     /* Condition codes are set */
2669     }
2670
2671     /* If we really had boolean ops, generate the end sequence */
2672     if (BoolOp) {
2673         DoneLab = GetLocalLabel ();
2674         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2675         g_falsejump (CF_NONE, DoneLab);
2676         g_defcodelabel (TrueLab);
2677         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2678         g_defcodelabel (DoneLab);
2679     }
2680 }
2681
2682
2683
2684 static void hieQuest (ExprDesc* Expr)
2685 /* Parse the ternary operator */
2686 {
2687     int         FalseLab;
2688     int         TrueLab;
2689     CodeMark    TrueCodeEnd;
2690     ExprDesc    Expr2;          /* Expression 2 */
2691     ExprDesc    Expr3;          /* Expression 3 */
2692     int         Expr2IsNULL;    /* Expression 2 is a NULL pointer */
2693     int         Expr3IsNULL;    /* Expression 3 is a NULL pointer */
2694     Type*       ResultType;     /* Type of result */
2695
2696
2697     /* Call the lower level eval routine */
2698     if (Preprocessing) {
2699         hieOrPP (Expr);
2700     } else {
2701         hieOr (Expr);
2702     }
2703
2704     /* Check if it's a ternary expression */
2705     if (CurTok.Tok == TOK_QUEST) {
2706         NextToken ();
2707         if (!ED_IsTested (Expr)) {
2708             /* Condition codes not set, request a test */
2709             ED_MarkForTest (Expr);
2710         }
2711         LoadExpr (CF_NONE, Expr);
2712         FalseLab = GetLocalLabel ();
2713         g_falsejump (CF_NONE, FalseLab);
2714
2715         /* Parse second expression. Remember for later if it is a NULL pointer
2716          * expression, then load it into the primary.
2717          */
2718         ExprWithCheck (hie1, &Expr2);
2719         Expr2IsNULL = ED_IsNullPtr (&Expr2);
2720         if (!IsTypeVoid (Expr2.Type)) {
2721             /* Load it into the primary */
2722             LoadExpr (CF_NONE, &Expr2);
2723             ED_MakeRValExpr (&Expr2);
2724             Expr2.Type = PtrConversion (Expr2.Type);
2725         }
2726
2727         /* Remember the current code position */
2728         GetCodePos (&TrueCodeEnd);
2729
2730         /* Jump around the evaluation of the third expression */
2731         TrueLab = GetLocalLabel ();
2732         ConsumeColon ();
2733         g_jump (TrueLab);
2734
2735         /* Jump here if the first expression was false */
2736         g_defcodelabel (FalseLab);
2737
2738         /* Parse third expression. Remember for later if it is a NULL pointer
2739          * expression, then load it into the primary.
2740          */
2741         ExprWithCheck (hie1, &Expr3);
2742         Expr3IsNULL = ED_IsNullPtr (&Expr3);
2743         if (!IsTypeVoid (Expr3.Type)) {
2744             /* Load it into the primary */
2745             LoadExpr (CF_NONE, &Expr3);
2746             ED_MakeRValExpr (&Expr3);
2747             Expr3.Type = PtrConversion (Expr3.Type);
2748         }
2749
2750         /* Check if any conversions are needed, if so, do them.
2751          * Conversion rules for ?: expression are:
2752          *   - if both expressions are int expressions, default promotion
2753          *     rules for ints apply.
2754          *   - if both expressions are pointers of the same type, the
2755          *     result of the expression is of this type.
2756          *   - if one of the expressions is a pointer and the other is
2757          *     a zero constant, the resulting type is that of the pointer
2758          *     type.
2759          *   - if both expressions are void expressions, the result is of
2760          *     type void.
2761          *   - all other cases are flagged by an error.
2762          */
2763         if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2764
2765             CodeMark    CvtCodeStart;
2766             CodeMark    CvtCodeEnd;
2767
2768
2769             /* Get common type */
2770             ResultType = promoteint (Expr2.Type, Expr3.Type);
2771
2772             /* Convert the third expression to this type if needed */
2773             TypeConversion (&Expr3, ResultType);
2774
2775             /* Emit conversion code for the second expression, but remember
2776              * where it starts end ends.
2777              */
2778             GetCodePos (&CvtCodeStart);
2779             TypeConversion (&Expr2, ResultType);
2780             GetCodePos (&CvtCodeEnd);
2781
2782             /* If we had conversion code, move it to the right place */
2783             if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
2784                 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
2785             }
2786
2787         } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2788             /* Must point to same type */
2789             if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2790                 Error ("Incompatible pointer types");
2791             }
2792             /* Result has the common type */
2793             ResultType = Expr2.Type;
2794         } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2795             /* Result type is pointer, no cast needed */
2796             ResultType = Expr2.Type;
2797         } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2798             /* Result type is pointer, no cast needed */
2799             ResultType = Expr3.Type;
2800         } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2801             /* Result type is void */
2802             ResultType = Expr3.Type;
2803         } else {
2804             Error ("Incompatible types");
2805             ResultType = Expr2.Type;            /* Doesn't matter here */
2806         }
2807
2808         /* Define the final label */
2809         g_defcodelabel (TrueLab);
2810
2811         /* Setup the target expression */
2812         ED_MakeRValExpr (Expr);
2813         Expr->Type  = ResultType;
2814     }
2815 }
2816
2817
2818
2819 static void opeq (const GenDesc* Gen, ExprDesc* Expr)
2820 /* Process "op=" operators. */
2821 {
2822     ExprDesc Expr2;
2823     unsigned flags;
2824     CodeMark Mark;
2825     int MustScale;
2826
2827     /* op= can only be used with lvalues */
2828     if (!ED_IsLVal (Expr)) {
2829         Error ("Invalid lvalue in assignment");
2830         return;
2831     }
2832
2833     /* The left side must not be const qualified */
2834     if (IsQualConst (Expr->Type)) {
2835         Error ("Assignment to const");
2836     }
2837
2838     /* There must be an integer or pointer on the left side */
2839     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2840         Error ("Invalid left operand type");
2841         /* Continue. Wrong code will be generated, but the compiler won't
2842          * break, so this is the best error recovery.
2843          */
2844     }
2845
2846     /* Skip the operator token */
2847     NextToken ();
2848
2849     /* Determine the type of the lhs */
2850     flags = TypeOf (Expr->Type);
2851     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2852
2853     /* Get the lhs address on stack (if needed) */
2854     PushAddr (Expr);
2855
2856     /* Fetch the lhs into the primary register if needed */
2857     LoadExpr (CF_NONE, Expr);
2858
2859     /* Bring the lhs on stack */
2860     GetCodePos (&Mark);
2861     g_push (flags, 0);
2862
2863     /* Evaluate the rhs */
2864     if (evalexpr (CF_NONE, hie1, &Expr2) == 0) {
2865         /* The resulting value is a constant. If the generator has the NOPUSH
2866          * flag set, don't push the lhs.
2867          */
2868         if (Gen->Flags & GEN_NOPUSH) {
2869             RemoveCode (&Mark);
2870         }
2871         if (MustScale) {
2872             /* lhs is a pointer, scale rhs */
2873             Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2874         }
2875
2876         /* If the lhs is character sized, the operation may be later done
2877          * with characters.
2878          */
2879         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2880             flags |= CF_FORCECHAR;
2881         }
2882
2883         /* Special handling for add and sub - some sort of a hack, but short code */
2884         if (Gen->Func == g_add) {
2885             g_inc (flags | CF_CONST, Expr2.IVal);
2886         } else if (Gen->Func == g_sub) {
2887             g_dec (flags | CF_CONST, Expr2.IVal);
2888         } else {
2889             if (Expr2.IVal == 0) {
2890                 /* Check for div by zero/mod by zero */
2891                 if (Gen->Func == g_div) {
2892                     Error ("Division by zero");
2893                 } else if (Gen->Func == g_mod) {
2894                     Error ("Modulo operation with zero");
2895                 }
2896             }
2897             Gen->Func (flags | CF_CONST, Expr2.IVal);
2898         }
2899     } else {
2900         /* rhs is not constant and already in the primary register */
2901         if (MustScale) {
2902             /* lhs is a pointer, scale rhs */
2903             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2904         }
2905
2906         /* If the lhs is character sized, the operation may be later done
2907          * with characters.
2908          */
2909         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2910             flags |= CF_FORCECHAR;
2911         }
2912
2913         /* Adjust the types of the operands if needed */
2914         Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2915     }
2916     Store (Expr, 0);
2917     ED_MakeRValExpr (Expr);
2918 }
2919
2920
2921
2922 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr)
2923 /* Process the += and -= operators */
2924 {
2925     ExprDesc Expr2;
2926     unsigned lflags;
2927     unsigned rflags;
2928     int      MustScale;
2929
2930
2931     /* We're currently only able to handle some adressing modes */
2932     if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2933         /* Use generic routine */
2934         opeq (Gen, Expr);
2935         return;
2936     }
2937
2938     /* We must have an lvalue */
2939     if (ED_IsRVal (Expr)) {
2940         Error ("Invalid lvalue in assignment");
2941         return;
2942     }
2943
2944     /* The left side must not be const qualified */
2945     if (IsQualConst (Expr->Type)) {
2946         Error ("Assignment to const");
2947     }
2948
2949     /* There must be an integer or pointer on the left side */
2950     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2951         Error ("Invalid left operand type");
2952         /* Continue. Wrong code will be generated, but the compiler won't
2953          * break, so this is the best error recovery.
2954          */
2955     }
2956
2957     /* Skip the operator */
2958     NextToken ();
2959
2960     /* Check if we have a pointer expression and must scale rhs */
2961     MustScale = IsTypePtr (Expr->Type);
2962
2963     /* Initialize the code generator flags */
2964     lflags = 0;
2965     rflags = 0;
2966
2967     /* Evaluate the rhs */
2968     hie1 (&Expr2);
2969     if (ED_IsConstAbs (&Expr2)) {
2970         /* The resulting value is a constant. Scale it. */
2971         if (MustScale) {
2972             Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
2973         }
2974         rflags |= CF_CONST;
2975         lflags |= CF_CONST;
2976     } else {
2977         /* Not constant, load into the primary */
2978         LoadExpr (CF_NONE, &Expr2);
2979         if (MustScale) {
2980             /* lhs is a pointer, scale rhs */
2981             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
2982         }
2983     }
2984
2985     /* Setup the code generator flags */
2986     lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
2987     rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
2988
2989     /* Convert the type of the lhs to that of the rhs */
2990     g_typecast (lflags, rflags);
2991
2992     /* Output apropriate code depending on the location */
2993     switch (ED_GetLoc (Expr)) {
2994
2995         case E_LOC_ABS:
2996             /* Absolute: numeric address or const */
2997             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2998                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2999             } else {
3000                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3001             }
3002             break;
3003
3004         case E_LOC_GLOBAL:
3005             /* Global variable */
3006             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3007                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3008             } else {
3009                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3010             }
3011             break;
3012
3013         case E_LOC_STATIC:
3014         case E_LOC_LITERAL:
3015             /* Static variable or literal in the literal pool */
3016             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3017                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3018             } else {
3019                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3020             }
3021             break;
3022
3023         case E_LOC_REGISTER:
3024             /* Register variable */
3025             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3026                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3027             } else {
3028                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3029             }
3030             break;
3031
3032         case E_LOC_STACK:
3033             /* Value on the stack */
3034             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3035                 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3036             } else {
3037                 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3038             }
3039             break;
3040
3041         default:
3042             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3043     }
3044
3045     /* Expression is a rvalue in the primary now */
3046     ED_MakeRValExpr (Expr);
3047 }
3048
3049
3050
3051 void hie1 (ExprDesc* Expr)
3052 /* Parse first level of expression hierarchy. */
3053 {
3054     hieQuest (Expr);
3055     switch (CurTok.Tok) {
3056
3057         case TOK_ASSIGN:
3058             Assignment (Expr);
3059             break;
3060
3061         case TOK_PLUS_ASSIGN:
3062             addsubeq (&GenPASGN, Expr);
3063             break;
3064
3065         case TOK_MINUS_ASSIGN:
3066             addsubeq (&GenSASGN, Expr);
3067             break;
3068
3069         case TOK_MUL_ASSIGN:
3070             opeq (&GenMASGN, Expr);
3071             break;
3072
3073         case TOK_DIV_ASSIGN:
3074             opeq (&GenDASGN, Expr);
3075             break;
3076
3077         case TOK_MOD_ASSIGN:
3078             opeq (&GenMOASGN, Expr);
3079             break;
3080
3081         case TOK_SHL_ASSIGN:
3082             opeq (&GenSLASGN, Expr);
3083             break;
3084
3085         case TOK_SHR_ASSIGN:
3086             opeq (&GenSRASGN, Expr);
3087             break;
3088
3089         case TOK_AND_ASSIGN:
3090             opeq (&GenAASGN, Expr);
3091             break;
3092
3093         case TOK_XOR_ASSIGN:
3094             opeq (&GenXOASGN, Expr);
3095             break;
3096
3097         case TOK_OR_ASSIGN:
3098             opeq (&GenOASGN, Expr);
3099             break;
3100
3101         default:
3102             break;
3103     }
3104 }
3105
3106
3107
3108 void hie0 (ExprDesc *Expr)
3109 /* Parse comma operator. */
3110 {
3111     hie1 (Expr);
3112     while (CurTok.Tok == TOK_COMMA) {
3113         NextToken ();
3114         hie1 (Expr);
3115     }
3116 }
3117
3118
3119
3120 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3121 /* Will evaluate an expression via the given function. If the result is a
3122  * constant, 0 is returned and the value is put in the Expr struct. If the
3123  * result is not constant, LoadExpr is called to bring the value into the
3124  * primary register and 1 is returned.
3125  */
3126 {
3127     /* Evaluate */
3128     ExprWithCheck (Func, Expr);
3129
3130     /* Check for a constant expression */
3131     if (ED_IsConstAbs (Expr)) {
3132         /* Constant expression */
3133         return 0;
3134     } else {
3135         /* Not constant, load into the primary */
3136         LoadExpr (Flags, Expr);
3137         return 1;
3138     }
3139 }
3140
3141
3142
3143 void Expression0 (ExprDesc* Expr)
3144 /* Evaluate an expression via hie0 and put the result into the primary register */
3145 {
3146     ExprWithCheck (hie0, Expr);
3147     LoadExpr (CF_NONE, Expr);
3148 }
3149
3150
3151
3152 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3153 /* Will evaluate an expression via the given function. If the result is not
3154  * a constant of some sort, a diagnostic will be printed, and the value is
3155  * replaced by a constant one to make sure there are no internal errors that
3156  * result from this input error.
3157  */
3158 {
3159     ExprWithCheck (Func, Expr);
3160     if (!ED_IsConst (Expr)) {
3161         Error ("Constant expression expected");
3162         /* To avoid any compiler errors, make the expression a valid const */
3163         ED_MakeConstAbsInt (Expr, 1);
3164     }
3165 }
3166
3167
3168
3169 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3170 /* Will evaluate an expression via the given function. If the result is not
3171  * something that may be evaluated in a boolean context, a diagnostic will be
3172  * printed, and the value is replaced by a constant one to make sure there
3173  * are no internal errors that result from this input error.
3174  */
3175 {
3176     ExprWithCheck (Func, Expr);
3177     if (!ED_IsBool (Expr)) {
3178         Error ("Boolean expression expected");
3179         /* To avoid any compiler errors, make the expression a valid int */
3180         ED_MakeConstAbsInt (Expr, 1);
3181     }
3182 }
3183
3184
3185
3186 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3187 /* Will evaluate an expression via the given function. If the result is not
3188  * a constant numeric integer value, a diagnostic will be printed, and the
3189  * value is replaced by a constant one to make sure there are no internal
3190  * errors that result from this input error.
3191  */
3192 {
3193     ExprWithCheck (Func, Expr);
3194     if (!ED_IsConstAbsInt (Expr)) {
3195         Error ("Constant integer expression expected");
3196         /* To avoid any compiler errors, make the expression a valid const */
3197         ED_MakeConstAbsInt (Expr, 1);
3198     }
3199 }
3200
3201
3202