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