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