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