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