]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
Moved the fascall and near/far flags from the function desriptor into the
[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. */
767             Error ("Expression expected");
768             ED_MakeConstAbsInt (E, 1);
769             break;
770     }
771 }
772
773
774
775 static void ArrayRef (ExprDesc* Expr)
776 /* Handle an array reference. This function needs a rewrite. */
777 {
778     int         ConstBaseAddr;
779     ExprDesc    SubScript;
780     CodeMark    Mark1;
781     CodeMark    Mark2;
782     Type*       ElementType;
783     Type*       tptr1;
784
785
786     /* Skip the bracket */
787     NextToken ();
788
789     /* Get the type of left side */
790     tptr1 = Expr->Type;
791
792     /* We can apply a special treatment for arrays that have a const base
793      * address. This is true for most arrays and will produce a lot better
794      * code. Check if this is a const base address.
795      */
796     ConstBaseAddr = ED_IsRVal (Expr) &&
797                     (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
798
799     /* If we have a constant base, we delay the address fetch */
800     GetCodePos (&Mark1);
801     if (!ConstBaseAddr) {
802         /* Get a pointer to the array into the primary */
803         LoadExpr (CF_NONE, Expr);
804
805         /* Get the array pointer on stack. Do not push more than 16
806          * bit, even if this value is greater, since we cannot handle
807          * other than 16bit stuff when doing indexing.
808          */
809         GetCodePos (&Mark2);
810         g_push (CF_PTR, 0);
811     }
812
813     /* TOS now contains ptr to array elements. Get the subscript. */
814     ExprWithCheck (hie0, &SubScript);
815
816     /* Check the types of array and subscript. We can either have a
817      * pointer/array to the left, in which case the subscript must be of an
818      * integer type, or we have an integer to the left, in which case the
819      * subscript must be a pointer/array.
820      * Since we do the necessary checking here, we can rely later on the
821      * correct types.
822      */
823     if (IsClassPtr (Expr->Type)) {
824         if (!IsClassInt (SubScript.Type))  {
825             Error ("Array subscript is not an integer");
826             /* To avoid any compiler errors, make the expression a valid int */
827             ED_MakeConstAbsInt (&SubScript, 0);
828         }
829         ElementType = Indirect (Expr->Type);
830     } else if (IsClassInt (Expr->Type)) {
831         if (!IsClassPtr (SubScript.Type)) {
832             Error ("Subscripted value is neither array nor pointer");
833             /* To avoid compiler errors, make the subscript a char[] at
834              * address 0.
835              */
836             ED_MakeConstAbs (&SubScript, 0, GetCharArrayType (1));
837         }
838         ElementType = Indirect (SubScript.Type);
839     } else {
840         Error ("Cannot subscript");
841         /* To avoid compiler errors, fake both the array and the subscript, so
842          * we can just proceed.
843          */
844         ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
845         ED_MakeConstAbsInt (&SubScript, 0);
846         ElementType = Indirect (Expr->Type);
847     }
848
849     /* Check if the subscript is constant absolute value */
850     if (ED_IsConstAbs (&SubScript)) {
851
852         /* The array subscript is a numeric constant. If we had pushed the
853          * array base address onto the stack before, we can remove this value,
854          * since we can generate expression+offset.
855          */
856         if (!ConstBaseAddr) {
857             RemoveCode (&Mark2);
858         } else {
859             /* Get an array pointer into the primary */
860             LoadExpr (CF_NONE, Expr);
861         }
862
863         if (IsClassPtr (Expr->Type)) {
864
865             /* Lhs is pointer/array. Scale the subscript value according to
866              * the element size.
867              */
868             SubScript.IVal *= CheckedSizeOf (ElementType);
869
870             /* Remove the address load code */
871             RemoveCode (&Mark1);
872
873             /* In case of an array, we can adjust the offset of the expression
874              * already in Expr. If the base address was a constant, we can even
875              * remove the code that loaded the address into the primary.
876              */
877             if (IsTypeArray (Expr->Type)) {
878
879                 /* Adjust the offset */
880                 Expr->IVal += SubScript.IVal;
881
882             } else {
883
884                 /* It's a pointer, so we do have to load it into the primary
885                  * first (if it's not already there).
886                  */
887                 if (ConstBaseAddr || ED_IsLVal (Expr)) {
888                     LoadExpr (CF_NONE, Expr);
889                     ED_MakeRValExpr (Expr);
890                 }
891
892                 /* Use the offset */
893                 Expr->IVal = SubScript.IVal;
894             }
895
896         } else {
897
898             /* Scale the rhs value according to the element type */
899             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
900
901             /* Add the subscript. Since arrays are indexed by integers,
902              * we will ignore the true type of the subscript here and
903              * use always an int. #### Use offset but beware of LoadExpr!
904              */
905             g_inc (CF_INT | CF_CONST, SubScript.IVal);
906
907         }
908
909     } else {
910
911         /* Array subscript is not constant. Load it into the primary */
912         GetCodePos (&Mark2);
913         LoadExpr (CF_NONE, &SubScript);
914
915         /* Do scaling */
916         if (IsClassPtr (Expr->Type)) {
917
918             /* Indexing is based on unsigneds, so we will just use the integer
919              * portion of the index (which is in (e)ax, so there's no further
920              * action required).
921              */
922             g_scale (CF_INT, CheckedSizeOf (ElementType));
923
924         } else {
925
926             /* Get the int value on top. If we come here, we're sure, both
927              * values are 16 bit (the first one was truncated if necessary
928              * and the second one is a pointer). Note: If ConstBaseAddr is
929              * true, we don't have a value on stack, so to "swap" both, just
930              * push the subscript.
931              */
932             if (ConstBaseAddr) {
933                 g_push (CF_INT, 0);
934                 LoadExpr (CF_NONE, Expr);
935                 ConstBaseAddr = 0;
936             } else {
937                 g_swap (CF_INT);
938             }
939
940             /* Scale it */
941             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
942
943         }
944
945         /* The offset is now in the primary register. It we didn't have a
946          * constant base address for the lhs, the lhs address is already
947          * on stack, and we must add the offset. If the base address was
948          * constant, we call special functions to add the address to the
949          * offset value.
950          */
951         if (!ConstBaseAddr) {
952
953             /* The array base address is on stack and the subscript is in the
954              * primary. Add both.
955              */
956             g_add (CF_INT, 0);
957
958         } else {
959
960             /* The subscript is in the primary, and the array base address is
961              * in Expr. If the subscript has itself a constant address, it is
962              * often a better idea to reverse again the order of the
963              * evaluation. This will generate better code if the subscript is
964              * a byte sized variable. But beware: This is only possible if the
965              * subscript was not scaled, that is, if this was a byte array
966              * or pointer.
967              */
968             if ((ED_IsLocConst (&SubScript) || ED_IsLocStack (&SubScript)) &&
969                 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
970
971                 unsigned Flags;
972
973                 /* Reverse the order of evaluation */
974                 if (CheckedSizeOf (SubScript.Type) == SIZEOF_CHAR) {
975                     Flags = CF_CHAR;
976                 } else {
977                     Flags = CF_INT;
978                 }
979                 RemoveCode (&Mark2);
980
981                 /* Get a pointer to the array into the primary. */
982                 LoadExpr (CF_NONE, Expr);
983
984                 /* Add the variable */
985                 if (ED_IsLocStack (&SubScript)) {
986                     g_addlocal (Flags, SubScript.IVal);
987                 } else {
988                     Flags |= GlobalModeFlags (&SubScript);
989                     g_addstatic (Flags, SubScript.Name, SubScript.IVal);
990                 }
991             } else {
992
993                 if (ED_IsLocAbs (Expr)) {
994                     /* Constant numeric address. Just add it */
995                     g_inc (CF_INT, Expr->IVal);
996                 } else if (ED_IsLocStack (Expr)) {
997                     /* Base address is a local variable address */
998                     if (IsTypeArray (Expr->Type)) {
999                         g_addaddr_local (CF_INT, Expr->IVal);
1000                     } else {
1001                         g_addlocal (CF_PTR, Expr->IVal);
1002                     }
1003                 } else {
1004                     /* Base address is a static variable address */
1005                     unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1006                     if (ED_IsRVal (Expr)) {
1007                         /* Add the address of the location */
1008                         g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1009                     } else {
1010                         /* Add the contents of the location */
1011                         g_addstatic (Flags, Expr->Name, Expr->IVal);
1012                     }
1013                 }
1014             }
1015
1016
1017         }
1018
1019         /* The result is an expression in the primary */
1020         ED_MakeRValExpr (Expr);
1021
1022     }
1023
1024     /* Result is of element type */
1025     Expr->Type = ElementType;
1026
1027     /* An array element is actually a variable. So the rules for variables
1028      * with respect to the reference type apply: If it's an array, it is
1029      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1030      * but an array cannot contain functions).
1031      */
1032     if (IsTypeArray (Expr->Type)) {
1033         ED_MakeRVal (Expr);
1034     } else {
1035         ED_MakeLVal (Expr);
1036     }
1037
1038     /* Consume the closing bracket */
1039     ConsumeRBrack ();
1040 }
1041
1042
1043
1044 static void StructRef (ExprDesc* Expr)
1045 /* Process struct field after . or ->. */
1046 {
1047     ident Ident;
1048     SymEntry* Field;
1049
1050     /* Skip the token and check for an identifier */
1051     NextToken ();
1052     if (CurTok.Tok != TOK_IDENT) {
1053         Error ("Identifier expected");
1054         Expr->Type = type_int;
1055         return;
1056     }
1057
1058     /* Get the symbol table entry and check for a struct field */
1059     strcpy (Ident, CurTok.Ident);
1060     NextToken ();
1061     Field = FindStructField (Expr->Type, Ident);
1062     if (Field == 0) {
1063         Error ("Struct/union has no field named `%s'", Ident);
1064         Expr->Type = type_int;
1065         return;
1066     }
1067
1068     /* If we have a struct pointer that is an lvalue and not already in the
1069      * primary, load it now.
1070      */
1071     if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1072
1073         /* Load into the primary */
1074         LoadExpr (CF_NONE, Expr);
1075
1076         /* Make it an lvalue expression */
1077         ED_MakeLValExpr (Expr);
1078     }
1079
1080     /* Set the struct field offset */
1081     Expr->IVal += Field->V.Offs;
1082
1083     /* The type is now the type of the field */
1084     Expr->Type = Field->Type;
1085
1086     /* An struct member is actually a variable. So the rules for variables
1087      * with respect to the reference type apply: If it's an array, it is
1088      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1089      * but a struct field cannot be a function).
1090      */
1091     if (IsTypeArray (Expr->Type)) {
1092         ED_MakeRVal (Expr);
1093     } else {
1094         ED_MakeLVal (Expr);
1095     }
1096 }
1097
1098
1099
1100 static void hie11 (ExprDesc *Expr)
1101 /* Handle compound types (structs and arrays) */
1102 {
1103     /* Name value used in invalid function calls */
1104     static const char IllegalFunc[] = "illegal_function_call";
1105
1106     /* Evaluate the lhs */
1107     Primary (Expr);
1108
1109     /* Check for a rhs */
1110     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1111            CurTok.Tok == TOK_DOT    || CurTok.Tok == TOK_PTR_REF) {
1112
1113         switch (CurTok.Tok) {
1114
1115             case TOK_LBRACK:
1116                 /* Array reference */
1117                 ArrayRef (Expr);
1118                 break;
1119
1120             case TOK_LPAREN:
1121                 /* Function call. */
1122                 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1123                     /* Not a function */
1124                     Error ("Illegal function call");
1125                     /* Force the type to be a implicitly defined function, one
1126                      * returning an int and taking any number of arguments.
1127                      * Since we don't have a name, invent one.
1128                      */
1129                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1130                     Expr->Name = (long) IllegalFunc;
1131                 }
1132                 /* Call the function */
1133                 FunctionCall (Expr);
1134                 break;
1135
1136             case TOK_DOT:
1137                 if (!IsClassStruct (Expr->Type)) {
1138                     Error ("Struct expected");
1139                 }
1140                 StructRef (Expr);
1141                 break;
1142
1143             case TOK_PTR_REF:
1144                 /* If we have an array, convert it to pointer to first element */
1145                 if (IsTypeArray (Expr->Type)) {
1146                     Expr->Type = ArrayToPtr (Expr->Type);
1147                 }
1148                 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1149                     Error ("Struct pointer expected");
1150                 }
1151                 StructRef (Expr);
1152                 break;
1153
1154             default:
1155                 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1156
1157         }
1158     }
1159 }
1160
1161
1162
1163 void Store (ExprDesc* Expr, const Type* StoreType)
1164 /* Store the primary register into the location denoted by Expr. If StoreType
1165  * is given, use this type when storing instead of Expr->Type. If StoreType
1166  * is NULL, use Expr->Type instead.
1167  */
1168 {
1169     unsigned Flags;
1170
1171     /* If StoreType was not given, use Expr->Type instead */
1172     if (StoreType == 0) {
1173         StoreType = Expr->Type;
1174     }
1175
1176     /* Prepare the code generator flags */
1177     Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1178
1179     /* Do the store depending on the location */
1180     switch (ED_GetLoc (Expr)) {
1181
1182         case E_LOC_ABS:
1183             /* Absolute: numeric address or const */
1184             g_putstatic (Flags, Expr->IVal, 0);
1185             break;
1186
1187         case E_LOC_GLOBAL:
1188             /* Global variable */
1189             g_putstatic (Flags, Expr->Name, Expr->IVal);
1190             break;
1191
1192         case E_LOC_STATIC:
1193         case E_LOC_LITERAL:
1194             /* Static variable or literal in the literal pool */
1195             g_putstatic (Flags, Expr->Name, Expr->IVal);
1196             break;
1197
1198         case E_LOC_REGISTER:
1199             /* Register variable */
1200             g_putstatic (Flags, Expr->Name, Expr->IVal);
1201             break;
1202
1203         case E_LOC_STACK:
1204             /* Value on the stack */
1205             g_putlocal (Flags, Expr->IVal, 0);
1206             break;
1207
1208         case E_LOC_PRIMARY:
1209             /* The primary register (value is already there) */
1210             break;
1211
1212         case E_LOC_EXPR:
1213             /* An expression in the primary register */
1214             g_putind (Flags, Expr->IVal);
1215             break;
1216
1217         default:
1218             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1219     }
1220
1221     /* Assume that each one of the stores will invalidate CC */
1222     ED_MarkAsUntested (Expr);
1223 }
1224
1225
1226
1227 static void PreInc (ExprDesc* Expr)
1228 /* Handle the preincrement operators */
1229 {
1230     unsigned Flags;
1231     unsigned long Val;
1232
1233     /* Skip the operator token */
1234     NextToken ();
1235
1236     /* Evaluate the expression and check that it is an lvalue */
1237     hie10 (Expr);
1238     if (!ED_IsLVal (Expr)) {
1239         Error ("Invalid lvalue");
1240         return;
1241     }
1242
1243     /* We cannot modify const values */
1244     if (IsQualConst (Expr->Type)) {
1245         Error ("Increment of read-only variable");
1246     }
1247
1248     /* Get the data type */
1249     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1250
1251     /* Get the increment value in bytes */
1252     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1253
1254     /* Check the location of the data */
1255     switch (ED_GetLoc (Expr)) {
1256
1257         case E_LOC_ABS:
1258             /* Absolute: numeric address or const */
1259             g_addeqstatic (Flags, Expr->IVal, 0, Val);
1260             break;
1261
1262         case E_LOC_GLOBAL:
1263             /* Global variable */
1264             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1265             break;
1266
1267         case E_LOC_STATIC:
1268         case E_LOC_LITERAL:
1269             /* Static variable or literal in the literal pool */
1270             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1271             break;
1272
1273         case E_LOC_REGISTER:
1274             /* Register variable */
1275             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1276             break;
1277
1278         case E_LOC_STACK:
1279             /* Value on the stack */
1280             g_addeqlocal (Flags, Expr->IVal, Val);
1281             break;
1282
1283         case E_LOC_PRIMARY:
1284             /* The primary register */
1285             g_inc (Flags, Val);
1286             break;
1287
1288         case E_LOC_EXPR:
1289             /* An expression in the primary register */
1290             g_addeqind (Flags, Expr->IVal, Val);
1291             break;
1292
1293         default:
1294             Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1295     }
1296
1297     /* Result is an expression, no reference */
1298     ED_MakeRValExpr (Expr);
1299 }
1300
1301
1302
1303 static void PreDec (ExprDesc* Expr)
1304 /* Handle the predecrement operators */
1305 {
1306     unsigned Flags;
1307     unsigned long Val;
1308
1309     /* Skip the operator token */
1310     NextToken ();
1311
1312     /* Evaluate the expression and check that it is an lvalue */
1313     hie10 (Expr);
1314     if (!ED_IsLVal (Expr)) {
1315         Error ("Invalid lvalue");
1316         return;
1317     }
1318
1319     /* We cannot modify const values */
1320     if (IsQualConst (Expr->Type)) {
1321         Error ("Decrement of read-only variable");
1322     }
1323
1324     /* Get the data type */
1325     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1326
1327     /* Get the increment value in bytes */
1328     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1329
1330     /* Check the location of the data */
1331     switch (ED_GetLoc (Expr)) {
1332
1333         case E_LOC_ABS:
1334             /* Absolute: numeric address or const */
1335             g_subeqstatic (Flags, Expr->IVal, 0, Val);
1336             break;
1337
1338         case E_LOC_GLOBAL:
1339             /* Global variable */
1340             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1341             break;
1342
1343         case E_LOC_STATIC:
1344         case E_LOC_LITERAL:
1345             /* Static variable or literal in the literal pool */
1346             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1347             break;
1348
1349         case E_LOC_REGISTER:
1350             /* Register variable */
1351             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1352             break;
1353
1354         case E_LOC_STACK:
1355             /* Value on the stack */
1356             g_subeqlocal (Flags, Expr->IVal, Val);
1357             break;
1358
1359         case E_LOC_PRIMARY:
1360             /* The primary register */
1361             g_inc (Flags, Val);
1362             break;
1363
1364         case E_LOC_EXPR:
1365             /* An expression in the primary register */
1366             g_subeqind (Flags, Expr->IVal, Val);
1367             break;
1368
1369         default:
1370             Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1371     }
1372
1373     /* Result is an expression, no reference */
1374     ED_MakeRValExpr (Expr);
1375 }
1376
1377
1378
1379 static void PostInc (ExprDesc* Expr)
1380 /* Handle the postincrement operator */
1381 {
1382     unsigned Flags;
1383
1384     NextToken ();
1385
1386     /* The expression to increment must be an lvalue */
1387     if (!ED_IsLVal (Expr)) {
1388         Error ("Invalid lvalue");
1389         return;
1390     }
1391
1392     /* We cannot modify const values */
1393     if (IsQualConst (Expr->Type)) {
1394         Error ("Increment of read-only variable");
1395     }
1396
1397     /* Get the data type */
1398     Flags = TypeOf (Expr->Type);
1399
1400     /* Push the address if needed */
1401     PushAddr (Expr);
1402
1403     /* Fetch the value and save it (since it's the result of the expression) */
1404     LoadExpr (CF_NONE, Expr);
1405     g_save (Flags | CF_FORCECHAR);
1406
1407     /* If we have a pointer expression, increment by the size of the type */
1408     if (IsTypePtr (Expr->Type)) {
1409         g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1410     } else {
1411         g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1412     }
1413
1414     /* Store the result back */
1415     Store (Expr, 0);
1416
1417     /* Restore the original value in the primary register */
1418     g_restore (Flags | CF_FORCECHAR);
1419
1420     /* The result is always an expression, no reference */
1421     ED_MakeRValExpr (Expr);
1422 }
1423
1424
1425
1426 static void PostDec (ExprDesc* Expr)
1427 /* Handle the postdecrement operator */
1428 {
1429     unsigned Flags;
1430
1431     NextToken ();
1432
1433     /* The expression to increment must be an lvalue */
1434     if (!ED_IsLVal (Expr)) {
1435         Error ("Invalid lvalue");
1436         return;
1437     }
1438
1439     /* We cannot modify const values */
1440     if (IsQualConst (Expr->Type)) {
1441         Error ("Decrement of read-only variable");
1442     }
1443
1444     /* Get the data type */
1445     Flags = TypeOf (Expr->Type);
1446
1447     /* Push the address if needed */
1448     PushAddr (Expr);
1449
1450     /* Fetch the value and save it (since it's the result of the expression) */
1451     LoadExpr (CF_NONE, Expr);
1452     g_save (Flags | CF_FORCECHAR);
1453
1454     /* If we have a pointer expression, increment by the size of the type */
1455     if (IsTypePtr (Expr->Type)) {
1456         g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1457     } else {
1458         g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1459     }
1460
1461     /* Store the result back */
1462     Store (Expr, 0);
1463
1464     /* Restore the original value in the primary register */
1465     g_restore (Flags | CF_FORCECHAR);
1466
1467     /* The result is always an expression, no reference */
1468     ED_MakeRValExpr (Expr);
1469 }
1470
1471
1472
1473 static void UnaryOp (ExprDesc* Expr)
1474 /* Handle unary -/+ and ~ */
1475 {
1476     unsigned Flags;
1477
1478     /* Remember the operator token and skip it */
1479     token_t Tok = CurTok.Tok;
1480     NextToken ();
1481
1482     /* Get the expression */
1483     hie10 (Expr);
1484
1485     /* We can only handle integer types */
1486     if (!IsClassInt (Expr->Type)) {
1487         Error ("Argument must have integer type");
1488         ED_MakeConstAbsInt (Expr, 1);
1489     }
1490
1491     /* Check for a constant expression */
1492     if (ED_IsConstAbs (Expr)) {
1493         /* Value is constant */
1494         switch (Tok) {
1495             case TOK_MINUS: Expr->IVal = -Expr->IVal;   break;
1496             case TOK_PLUS:                              break;
1497             case TOK_COMP:  Expr->IVal = ~Expr->IVal;   break;
1498             default:        Internal ("Unexpected token: %d", Tok);
1499         }
1500     } else {
1501         /* Value is not constant */
1502         LoadExpr (CF_NONE, Expr);
1503
1504         /* Get the type of the expression */
1505         Flags = TypeOf (Expr->Type);
1506
1507         /* Handle the operation */
1508         switch (Tok) {
1509             case TOK_MINUS: g_neg (Flags);  break;
1510             case TOK_PLUS:                  break;
1511             case TOK_COMP:  g_com (Flags);  break;
1512             default:        Internal ("Unexpected token: %d", Tok);
1513         }
1514
1515         /* The result is a rvalue in the primary */
1516         ED_MakeRValExpr (Expr);
1517     }
1518 }
1519
1520
1521
1522 void hie10 (ExprDesc* Expr)
1523 /* Handle ++, --, !, unary - etc. */
1524 {
1525     unsigned long Size;
1526
1527     switch (CurTok.Tok) {
1528
1529         case TOK_INC:
1530             PreInc (Expr);
1531             break;
1532
1533         case TOK_DEC:
1534             PreDec (Expr);
1535             break;
1536
1537         case TOK_PLUS:
1538         case TOK_MINUS:
1539         case TOK_COMP:
1540             UnaryOp (Expr);
1541             break;
1542
1543         case TOK_BOOL_NOT:
1544             NextToken ();
1545             if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1546                 /* Constant expression */
1547                 Expr->IVal = !Expr->IVal;
1548             } else {
1549                 g_bneg (TypeOf (Expr->Type));
1550                 ED_MakeRValExpr (Expr);
1551                 ED_TestDone (Expr);             /* bneg will set cc */
1552             }
1553             break;
1554
1555         case TOK_STAR:
1556             NextToken ();
1557             ExprWithCheck (hie10, Expr);
1558             if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1559                 /* Not a const, load it into the primary and make it a
1560                  * calculated value.
1561                  */
1562                 LoadExpr (CF_NONE, Expr);
1563                 ED_MakeRValExpr (Expr);
1564             }
1565             /* If the expression is already a pointer to function, the
1566              * additional dereferencing operator must be ignored.
1567              */
1568             if (IsTypeFuncPtr (Expr->Type)) {
1569                 /* Expression not storable */
1570                 ED_MakeRVal (Expr);
1571             } else {
1572                 if (IsClassPtr (Expr->Type)) {
1573                     Expr->Type = Indirect (Expr->Type);
1574                 } else {
1575                     Error ("Illegal indirection");
1576                 }
1577                 /* The * operator yields an lvalue */
1578                 ED_MakeLVal (Expr);
1579             }
1580             break;
1581
1582         case TOK_AND:
1583             NextToken ();
1584             ExprWithCheck (hie10, Expr);
1585             /* The & operator may be applied to any lvalue, and it may be
1586              * applied to functions, even if they're no lvalues.
1587              */
1588             if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1589                 Error ("Illegal address");
1590             } else {
1591                 Expr->Type = PointerTo (Expr->Type);
1592                 /* The & operator yields an rvalue */
1593                 ED_MakeRVal (Expr);
1594             }
1595             break;
1596
1597         case TOK_SIZEOF:
1598             NextToken ();
1599             if (TypeSpecAhead ()) {
1600                 Type T[MAXTYPELEN];
1601                 NextToken ();
1602                 Size = CheckedSizeOf (ParseType (T));
1603                 ConsumeRParen ();
1604             } else {
1605                 /* Remember the output queue pointer */
1606                 CodeMark Mark;
1607                 GetCodePos (&Mark);
1608                 hie10 (Expr);
1609                 Size = CheckedSizeOf (Expr->Type);
1610                 /* Remove any generated code */
1611                 RemoveCode (&Mark);
1612             }
1613             ED_MakeConstAbs (Expr, Size, type_size_t);
1614             ED_MarkAsUntested (Expr);
1615             break;
1616
1617         default:
1618             if (TypeSpecAhead ()) {
1619
1620                 /* A typecast */
1621                 TypeCast (Expr);
1622
1623             } else {
1624
1625                 /* An expression */
1626                 hie11 (Expr);
1627
1628                 /* Handle post increment */
1629                 switch (CurTok.Tok) {
1630                     case TOK_INC:   PostInc (Expr); break;
1631                     case TOK_DEC:   PostDec (Expr); break;
1632                     default:                        break;
1633                 }
1634
1635             }
1636             break;
1637     }
1638 }
1639
1640
1641
1642 static void hie_internal (const GenDesc* Ops,   /* List of generators */
1643                           ExprDesc* Expr,
1644                           void (*hienext) (ExprDesc*),
1645                           int* UsedGen)
1646 /* Helper function */
1647 {
1648     ExprDesc Expr2;
1649     CodeMark Mark1;
1650     CodeMark Mark2;
1651     const GenDesc* Gen;
1652     token_t Tok;                        /* The operator token */
1653     unsigned ltype, type;
1654     int rconst;                         /* Operand is a constant */
1655
1656
1657     hienext (Expr);
1658
1659     *UsedGen = 0;
1660     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1661
1662         /* Tell the caller that we handled it's ops */
1663         *UsedGen = 1;
1664
1665         /* All operators that call this function expect an int on the lhs */
1666         if (!IsClassInt (Expr->Type)) {
1667             Error ("Integer expression expected");
1668             /* To avoid further errors, make Expr a valid int expression */
1669             ED_MakeConstAbsInt (Expr, 1);
1670         }
1671
1672         /* Remember the operator token, then skip it */
1673         Tok = CurTok.Tok;
1674         NextToken ();
1675
1676         /* Get the lhs on stack */
1677         GetCodePos (&Mark1);
1678         ltype = TypeOf (Expr->Type);
1679         if (ED_IsConstAbs (Expr)) {
1680             /* Constant value */
1681             GetCodePos (&Mark2);
1682             g_push (ltype | CF_CONST, Expr->IVal);
1683         } else {
1684             /* Value not constant */
1685             LoadExpr (CF_NONE, Expr);
1686             GetCodePos (&Mark2);
1687             g_push (ltype, 0);
1688         }
1689
1690         /* Get the right hand side */
1691         rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1692
1693         /* Check the type of the rhs */
1694         if (!IsClassInt (Expr2.Type)) {
1695             Error ("Integer expression expected");
1696         }
1697
1698         /* Check for const operands */
1699         if (ED_IsConstAbs (Expr) && rconst) {
1700
1701             /* Both operands are constant, remove the generated code */
1702             RemoveCode (&Mark1);
1703
1704             /* Get the type of the result */
1705             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1706
1707             /* Handle the op differently for signed and unsigned types */
1708             if (IsSignSigned (Expr->Type)) {
1709
1710                 /* Evaluate the result for signed operands */
1711                 signed long Val1 = Expr->IVal;
1712                 signed long Val2 = Expr2.IVal;
1713                 switch (Tok) {
1714                     case TOK_OR:
1715                         Expr->IVal = (Val1 | Val2);
1716                         break;
1717                     case TOK_XOR:
1718                         Expr->IVal = (Val1 ^ Val2);
1719                         break;
1720                     case TOK_AND:
1721                         Expr->IVal = (Val1 & Val2);
1722                         break;
1723                     case TOK_STAR:
1724                         Expr->IVal = (Val1 * Val2);
1725                         break;
1726                     case TOK_DIV:
1727                         if (Val2 == 0) {
1728                             Error ("Division by zero");
1729                             Expr->IVal = 0x7FFFFFFF;
1730                         } else {
1731                             Expr->IVal = (Val1 / Val2);
1732                         }
1733                         break;
1734                     case TOK_MOD:
1735                         if (Val2 == 0) {
1736                             Error ("Modulo operation with zero");
1737                             Expr->IVal = 0;
1738                         } else {
1739                             Expr->IVal = (Val1 % Val2);
1740                         }
1741                         break;
1742                     default:
1743                         Internal ("hie_internal: got token 0x%X\n", Tok);
1744                 }
1745             } else {
1746
1747                 /* Evaluate the result for unsigned operands */
1748                 unsigned long Val1 = Expr->IVal;
1749                 unsigned long Val2 = Expr2.IVal;
1750                 switch (Tok) {
1751                     case TOK_OR:
1752                         Expr->IVal = (Val1 | Val2);
1753                         break;
1754                     case TOK_XOR:
1755                         Expr->IVal = (Val1 ^ Val2);
1756                         break;
1757                     case TOK_AND:
1758                         Expr->IVal = (Val1 & Val2);
1759                         break;
1760                     case TOK_STAR:
1761                         Expr->IVal = (Val1 * Val2);
1762                         break;
1763                     case TOK_DIV:
1764                         if (Val2 == 0) {
1765                             Error ("Division by zero");
1766                             Expr->IVal = 0xFFFFFFFF;
1767                         } else {
1768                             Expr->IVal = (Val1 / Val2);
1769                         }
1770                         break;
1771                     case TOK_MOD:
1772                         if (Val2 == 0) {
1773                             Error ("Modulo operation with zero");
1774                             Expr->IVal = 0;
1775                         } else {
1776                             Expr->IVal = (Val1 % Val2);
1777                         }
1778                         break;
1779                     default:
1780                         Internal ("hie_internal: got token 0x%X\n", Tok);
1781                 }
1782             }
1783
1784         } else {
1785
1786             /* If the right hand side is constant, and the generator function
1787              * expects the lhs in the primary, remove the push of the primary
1788              * now.
1789              */
1790             unsigned rtype = TypeOf (Expr2.Type);
1791             type = 0;
1792             if (rconst) {
1793                 /* Second value is constant - check for div */
1794                 type |= CF_CONST;
1795                 rtype |= CF_CONST;
1796                 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1797                     Error ("Division by zero");
1798                 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1799                     Error ("Modulo operation with zero");
1800                 }
1801                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1802                     RemoveCode (&Mark2);
1803                     ltype |= CF_REG;    /* Value is in register */
1804                 }
1805             }
1806
1807             /* Determine the type of the operation result. */
1808             type |= g_typeadjust (ltype, rtype);
1809             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1810
1811             /* Generate code */
1812             Gen->Func (type, Expr2.IVal);
1813
1814             /* We have a rvalue in the primary now */
1815             ED_MakeRValExpr (Expr);
1816         }
1817     }
1818 }
1819
1820
1821
1822 static void hie_compare (const GenDesc* Ops,    /* List of generators */
1823                          ExprDesc* Expr,
1824                          void (*hienext) (ExprDesc*))
1825 /* Helper function for the compare operators */
1826 {
1827     ExprDesc Expr2;
1828     CodeMark Mark1;
1829     CodeMark Mark2;
1830     const GenDesc* Gen;
1831     token_t Tok;                        /* The operator token */
1832     unsigned ltype;
1833     int rconst;                         /* Operand is a constant */
1834
1835
1836     hienext (Expr);
1837
1838     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1839
1840         /* Remember the operator token, then skip it */
1841         Tok = CurTok.Tok;
1842         NextToken ();
1843
1844         /* Get the lhs on stack */
1845         GetCodePos (&Mark1);
1846         ltype = TypeOf (Expr->Type);
1847         if (ED_IsConstAbs (Expr)) {
1848             /* Constant value */
1849             GetCodePos (&Mark2);
1850             g_push (ltype | CF_CONST, Expr->IVal);
1851         } else {
1852             /* Value not constant */
1853             LoadExpr (CF_NONE, Expr);
1854             GetCodePos (&Mark2);
1855             g_push (ltype, 0);
1856         }
1857
1858         /* Get the right hand side */
1859         rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1860
1861         /* Make sure, the types are compatible */
1862         if (IsClassInt (Expr->Type)) {
1863             if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1864                 Error ("Incompatible types");
1865             }
1866         } else if (IsClassPtr (Expr->Type)) {
1867             if (IsClassPtr (Expr2.Type)) {
1868                 /* Both pointers are allowed in comparison if they point to
1869                  * the same type, or if one of them is a void pointer.
1870                  */
1871                 Type* left  = Indirect (Expr->Type);
1872                 Type* right = Indirect (Expr2.Type);
1873                 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
1874                     /* Incomatible pointers */
1875                     Error ("Incompatible types");
1876                 }
1877             } else if (!ED_IsNullPtr (&Expr2)) {
1878                 Error ("Incompatible types");
1879             }
1880         }
1881
1882         /* Check for const operands */
1883         if (ED_IsConstAbs (Expr) && rconst) {
1884
1885             /* Both operands are constant, remove the generated code */
1886             RemoveCode (&Mark1);
1887
1888             /* Determine if this is a signed or unsigned compare */
1889             if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
1890                 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
1891
1892                 /* Evaluate the result for signed operands */
1893                 signed long Val1 = Expr->IVal;
1894                 signed long Val2 = Expr2.IVal;
1895                 switch (Tok) {
1896                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
1897                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
1898                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
1899                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
1900                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
1901                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
1902                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
1903                 }
1904
1905             } else {
1906
1907                 /* Evaluate the result for unsigned operands */
1908                 unsigned long Val1 = Expr->IVal;
1909                 unsigned 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
1921         } else {
1922
1923             /* If the right hand side is constant, and the generator function
1924              * expects the lhs in the primary, remove the push of the primary
1925              * now.
1926              */
1927             unsigned flags = 0;
1928             if (rconst) {
1929                 flags |= CF_CONST;
1930                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1931                     RemoveCode (&Mark2);
1932                     ltype |= CF_REG;    /* Value is in register */
1933                 }
1934             }
1935
1936             /* Determine the type of the operation result. If the left
1937              * operand is of type char and the right is a constant, or
1938              * if both operands are of type char, we will encode the
1939              * operation as char operation. Otherwise the default
1940              * promotions are used.
1941              */
1942             if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
1943                 flags |= CF_CHAR;
1944                 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
1945                     flags |= CF_UNSIGNED;
1946                 }
1947                 if (rconst) {
1948                     flags |= CF_FORCECHAR;
1949                 }
1950             } else {
1951                 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
1952                 flags |= g_typeadjust (ltype, rtype);
1953             }
1954
1955             /* Generate code */
1956             Gen->Func (flags, Expr2.IVal);
1957
1958             /* The result is an rvalue in the primary */
1959             ED_MakeRValExpr (Expr);
1960         }
1961
1962         /* Result type is always int */
1963         Expr->Type = type_int;
1964
1965         /* Condition codes are set */
1966         ED_TestDone (Expr);
1967     }
1968 }
1969
1970
1971
1972 static void hie9 (ExprDesc *Expr)
1973 /* Process * and / operators. */
1974 {
1975     static const GenDesc hie9_ops[] = {
1976         { TOK_STAR,     GEN_NOPUSH,     g_mul   },
1977         { TOK_DIV,      GEN_NOPUSH,     g_div   },
1978         { TOK_MOD,      GEN_NOPUSH,     g_mod   },
1979         { TOK_INVALID,  0,              0       }
1980     };
1981     int UsedGen;
1982
1983     hie_internal (hie9_ops, Expr, hie10, &UsedGen);
1984 }
1985
1986
1987
1988 static void parseadd (ExprDesc* Expr)
1989 /* Parse an expression with the binary plus operator. Expr contains the
1990  * unprocessed left hand side of the expression and will contain the
1991  * result of the expression on return.
1992  */
1993 {
1994     ExprDesc Expr2;
1995     unsigned flags;             /* Operation flags */
1996     CodeMark Mark;              /* Remember code position */
1997     Type* lhst;                 /* Type of left hand side */
1998     Type* rhst;                 /* Type of right hand side */
1999
2000
2001     /* Skip the PLUS token */
2002     NextToken ();
2003
2004     /* Get the left hand side type, initialize operation flags */
2005     lhst = Expr->Type;
2006     flags = 0;
2007
2008     /* Check for constness on both sides */
2009     if (ED_IsConst (Expr)) {
2010
2011         /* The left hand side is a constant of some sort. Good. Get rhs */
2012         hie9 (&Expr2);
2013         if (ED_IsConstAbs (&Expr2)) {
2014
2015             /* Right hand side is a constant numeric value. Get the rhs type */
2016             rhst = Expr2.Type;
2017
2018             /* Both expressions are constants. Check for pointer arithmetic */
2019             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2020                 /* Left is pointer, right is int, must scale rhs */
2021                 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2022                 /* Result type is a pointer */
2023             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2024                 /* Left is int, right is pointer, must scale lhs */
2025                 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2026                 /* Result type is a pointer */
2027                 Expr->Type = Expr2.Type;
2028             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2029                 /* Integer addition */
2030                 Expr->IVal += Expr2.IVal;
2031                 typeadjust (Expr, &Expr2, 1);
2032             } else {
2033                 /* OOPS */
2034                 Error ("Invalid operands for binary operator `+'");
2035             }
2036
2037         } else {
2038
2039             /* lhs is a constant and rhs is not constant. Load rhs into
2040              * the primary.
2041              */
2042             LoadExpr (CF_NONE, &Expr2);
2043
2044             /* Beware: The check above (for lhs) lets not only pass numeric
2045              * constants, but also constant addresses (labels), maybe even
2046              * with an offset. We have to check for that here.
2047              */
2048
2049             /* First, get the rhs type. */
2050             rhst = Expr2.Type;
2051
2052             /* Setup flags */
2053             if (ED_IsLocAbs (Expr)) {
2054                 /* A numerical constant */
2055                 flags |= CF_CONST;
2056             } else {
2057                 /* Constant address label */
2058                 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2059             }
2060
2061             /* Check for pointer arithmetic */
2062             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2063                 /* Left is pointer, right is int, must scale rhs */
2064                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2065                 /* Operate on pointers, result type is a pointer */
2066                 flags |= CF_PTR;
2067                 /* Generate the code for the add */
2068                 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2069                     /* Numeric constant */
2070                     g_inc (flags, Expr->IVal);
2071                 } else {
2072                     /* Constant address */
2073                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2074                 }
2075             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2076
2077                 /* Left is int, right is pointer, must scale lhs. */
2078                 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2079
2080                 /* Operate on pointers, result type is a pointer */
2081                 flags |= CF_PTR;
2082                 Expr->Type = Expr2.Type;
2083
2084                 /* Since we do already have rhs in the primary, if lhs is
2085                  * not a numeric constant, and the scale factor is not one
2086                  * (no scaling), we must take the long way over the stack.
2087                  */
2088                 if (ED_IsLocAbs (Expr)) {
2089                     /* Numeric constant, scale lhs */
2090                     Expr->IVal *= ScaleFactor;
2091                     /* Generate the code for the add */
2092                     g_inc (flags, Expr->IVal);
2093                 } else if (ScaleFactor == 1) {
2094                     /* Constant address but no need to scale */
2095                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2096                 } else {
2097                     /* Constant address that must be scaled */
2098                     g_push (TypeOf (Expr2.Type), 0);    /* rhs --> stack */
2099                     g_getimmed (flags, Expr->Name, Expr->IVal);
2100                     g_scale (CF_PTR, ScaleFactor);
2101                     g_add (CF_PTR, 0);
2102                 }
2103             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2104                 /* Integer addition */
2105                 flags |= typeadjust (Expr, &Expr2, 1);
2106                 /* Generate the code for the add */
2107                 if (ED_IsLocAbs (Expr)) {
2108                     /* Numeric constant */
2109                     g_inc (flags, Expr->IVal);
2110                 } else {
2111                     /* Constant address */
2112                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2113                 }
2114             } else {
2115                 /* OOPS */
2116                 Error ("Invalid operands for binary operator `+'");
2117                 flags = CF_INT;
2118             }
2119
2120             /* Result is a rvalue in primary register */
2121             ED_MakeRValExpr (Expr);
2122         }
2123
2124     } else {
2125
2126         /* Left hand side is not constant. Get the value onto the stack. */
2127         LoadExpr (CF_NONE, Expr);              /* --> primary register */
2128         GetCodePos (&Mark);
2129         g_push (TypeOf (Expr->Type), 0);        /* --> stack */
2130
2131         /* Evaluate the rhs */
2132         if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2133
2134             /* Right hand side is a constant. Get the rhs type */
2135             rhst = Expr2.Type;
2136
2137             /* Remove pushed value from stack */
2138             RemoveCode (&Mark);
2139
2140             /* Check for pointer arithmetic */
2141             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2142                 /* Left is pointer, right is int, must scale rhs */
2143                 Expr2.IVal *= CheckedPSizeOf (lhst);
2144                 /* Operate on pointers, result type is a pointer */
2145                 flags = CF_PTR;
2146             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2147                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2148                 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2149                 /* Operate on pointers, result type is a pointer */
2150                 flags = CF_PTR;
2151                 Expr->Type = Expr2.Type;
2152             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2153                 /* Integer addition */
2154                 flags = typeadjust (Expr, &Expr2, 1);
2155             } else {
2156                 /* OOPS */
2157                 Error ("Invalid operands for binary operator `+'");
2158                 flags = CF_INT;
2159             }
2160
2161             /* Generate code for the add */
2162             g_inc (flags | CF_CONST, Expr2.IVal);
2163
2164         } else {
2165
2166             /* lhs and rhs are not constant. Get the rhs type. */
2167             rhst = Expr2.Type;
2168
2169             /* Check for pointer arithmetic */
2170             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2171                 /* Left is pointer, right is int, must scale rhs */
2172                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2173                 /* Operate on pointers, result type is a pointer */
2174                 flags = CF_PTR;
2175             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2176                 /* Left is int, right is pointer, must scale lhs */
2177                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2178                 g_swap (CF_INT);                /* Swap TOS and primary */
2179                 g_scale (CF_INT, CheckedPSizeOf (rhst));
2180                 /* Operate on pointers, result type is a pointer */
2181                 flags = CF_PTR;
2182                 Expr->Type = Expr2.Type;
2183             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2184                 /* Integer addition. Note: Result is never constant.
2185                  * Problem here is that typeadjust does not know if the
2186                  * variable is an rvalue or lvalue, so if both operands
2187                  * are dereferenced constant numeric addresses, typeadjust
2188                  * thinks the operation works on constants. Removing
2189                  * CF_CONST here means handling the symptoms, however, the
2190                  * whole parser is such a mess that I fear to break anything
2191                  * when trying to apply another solution.
2192                  */
2193                 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2194             } else {
2195                 /* OOPS */
2196                 Error ("Invalid operands for binary operator `+'");
2197                 flags = CF_INT;
2198             }
2199
2200             /* Generate code for the add */
2201             g_add (flags, 0);
2202
2203         }
2204
2205         /* Result is a rvalue in primary register */
2206         ED_MakeRValExpr (Expr);
2207     }
2208
2209     /* Condition codes not set */
2210     ED_MarkAsUntested (Expr);
2211
2212 }
2213
2214
2215
2216 static void parsesub (ExprDesc* Expr)
2217 /* Parse an expression with the binary minus operator. Expr contains the
2218  * unprocessed left hand side of the expression and will contain the
2219  * result of the expression on return.
2220  */
2221 {
2222     ExprDesc Expr2;
2223     unsigned flags;             /* Operation flags */
2224     Type* lhst;                 /* Type of left hand side */
2225     Type* rhst;                 /* Type of right hand side */
2226     CodeMark Mark1;             /* Save position of output queue */
2227     CodeMark Mark2;             /* Another position in the queue */
2228     int rscale;                 /* Scale factor for the result */
2229
2230
2231     /* Skip the MINUS token */
2232     NextToken ();
2233
2234     /* Get the left hand side type, initialize operation flags */
2235     lhst = Expr->Type;
2236     rscale = 1;                 /* Scale by 1, that is, don't scale */
2237
2238     /* Remember the output queue position, then bring the value onto the stack */
2239     GetCodePos (&Mark1);
2240     LoadExpr (CF_NONE, Expr);  /* --> primary register */
2241     GetCodePos (&Mark2);
2242     g_push (TypeOf (lhst), 0);  /* --> stack */
2243
2244     /* Parse the right hand side */
2245     if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2246
2247         /* The right hand side is constant. Get the rhs type. */
2248         rhst = Expr2.Type;
2249
2250         /* Check left hand side */
2251         if (ED_IsConstAbs (Expr)) {
2252
2253             /* Both sides are constant, remove generated code */
2254             RemoveCode (&Mark1);
2255
2256             /* Check for pointer arithmetic */
2257             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2258                 /* Left is pointer, right is int, must scale rhs */
2259                 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2260                 /* Operate on pointers, result type is a pointer */
2261             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2262                 /* Left is pointer, right is pointer, must scale result */
2263                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2264                     Error ("Incompatible pointer types");
2265                 } else {
2266                     Expr->IVal = (Expr->IVal - Expr2.IVal) /
2267                                       CheckedPSizeOf (lhst);
2268                 }
2269                 /* Operate on pointers, result type is an integer */
2270                 Expr->Type = type_int;
2271             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2272                 /* Integer subtraction */
2273                 typeadjust (Expr, &Expr2, 1);
2274                 Expr->IVal -= Expr2.IVal;
2275             } else {
2276                 /* OOPS */
2277                 Error ("Invalid operands for binary operator `-'");
2278             }
2279
2280             /* Result is constant, condition codes not set */
2281             ED_MarkAsUntested (Expr);
2282
2283         } else {
2284
2285             /* Left hand side is not constant, right hand side is.
2286              * Remove pushed value from stack.
2287              */
2288             RemoveCode (&Mark2);
2289
2290             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2291                 /* Left is pointer, right is int, must scale rhs */
2292                 Expr2.IVal *= CheckedPSizeOf (lhst);
2293                 /* Operate on pointers, result type is a pointer */
2294                 flags = CF_PTR;
2295             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2296                 /* Left is pointer, right is pointer, must scale result */
2297                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2298                     Error ("Incompatible pointer types");
2299                 } else {
2300                     rscale = CheckedPSizeOf (lhst);
2301                 }
2302                 /* Operate on pointers, result type is an integer */
2303                 flags = CF_PTR;
2304                 Expr->Type = type_int;
2305             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2306                 /* Integer subtraction */
2307                 flags = typeadjust (Expr, &Expr2, 1);
2308             } else {
2309                 /* OOPS */
2310                 Error ("Invalid operands for binary operator `-'");
2311                 flags = CF_INT;
2312             }
2313
2314             /* Do the subtraction */
2315             g_dec (flags | CF_CONST, Expr2.IVal);
2316
2317             /* If this was a pointer subtraction, we must scale the result */
2318             if (rscale != 1) {
2319                 g_scale (flags, -rscale);
2320             }
2321
2322             /* Result is a rvalue in the primary register */
2323             ED_MakeRValExpr (Expr);
2324             ED_MarkAsUntested (Expr);
2325
2326         }
2327
2328     } else {
2329
2330         /* Right hand side is not constant. Get the rhs type. */
2331         rhst = Expr2.Type;
2332
2333         /* Check for pointer arithmetic */
2334         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2335             /* Left is pointer, right is int, must scale rhs */
2336             g_scale (CF_INT, CheckedPSizeOf (lhst));
2337             /* Operate on pointers, result type is a pointer */
2338             flags = CF_PTR;
2339         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2340             /* Left is pointer, right is pointer, must scale result */
2341             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2342                 Error ("Incompatible pointer types");
2343             } else {
2344                 rscale = CheckedPSizeOf (lhst);
2345             }
2346             /* Operate on pointers, result type is an integer */
2347             flags = CF_PTR;
2348             Expr->Type = type_int;
2349         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2350             /* Integer subtraction. If the left hand side descriptor says that
2351              * the lhs is const, we have to remove this mark, since this is no
2352              * longer true, lhs is on stack instead.
2353              */
2354             if (ED_IsLocAbs (Expr)) {
2355                 ED_MakeRValExpr (Expr);
2356             }
2357             /* Adjust operand types */
2358             flags = typeadjust (Expr, &Expr2, 0);
2359         } else {
2360             /* OOPS */
2361             Error ("Invalid operands for binary operator `-'");
2362             flags = CF_INT;
2363         }
2364
2365         /* Generate code for the sub (the & is a hack here) */
2366         g_sub (flags & ~CF_CONST, 0);
2367
2368         /* If this was a pointer subtraction, we must scale the result */
2369         if (rscale != 1) {
2370             g_scale (flags, -rscale);
2371         }
2372
2373         /* Result is a rvalue in the primary register */
2374         ED_MakeRValExpr (Expr);
2375         ED_MarkAsUntested (Expr);
2376     }
2377 }
2378
2379
2380
2381 void hie8 (ExprDesc* Expr)
2382 /* Process + and - binary operators. */
2383 {
2384     hie9 (Expr);
2385     while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2386         if (CurTok.Tok == TOK_PLUS) {
2387             parseadd (Expr);
2388         } else {
2389             parsesub (Expr);
2390         }
2391     }
2392 }
2393
2394
2395
2396 static void hie6 (ExprDesc* Expr)
2397 /* Handle greater-than type comparators */
2398 {
2399     static const GenDesc hie6_ops [] = {
2400         { TOK_LT,       GEN_NOPUSH,     g_lt    },
2401         { TOK_LE,       GEN_NOPUSH,     g_le    },
2402         { TOK_GE,       GEN_NOPUSH,     g_ge    },
2403         { TOK_GT,       GEN_NOPUSH,     g_gt    },
2404         { TOK_INVALID,  0,              0       }
2405     };
2406     hie_compare (hie6_ops, Expr, ShiftExpr);
2407 }
2408
2409
2410
2411 static void hie5 (ExprDesc* Expr)
2412 /* Handle == and != */
2413 {
2414     static const GenDesc hie5_ops[] = {
2415         { TOK_EQ,       GEN_NOPUSH,     g_eq    },
2416         { TOK_NE,       GEN_NOPUSH,     g_ne    },
2417         { TOK_INVALID,  0,              0       }
2418     };
2419     hie_compare (hie5_ops, Expr, hie6);
2420 }
2421
2422
2423
2424 static void hie4 (ExprDesc* Expr)
2425 /* Handle & (bitwise and) */
2426 {
2427     static const GenDesc hie4_ops[] = {
2428         { TOK_AND,      GEN_NOPUSH,     g_and   },
2429         { TOK_INVALID,  0,              0       }
2430     };
2431     int UsedGen;
2432
2433     hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2434 }
2435
2436
2437
2438 static void hie3 (ExprDesc* Expr)
2439 /* Handle ^ (bitwise exclusive or) */
2440 {
2441     static const GenDesc hie3_ops[] = {
2442         { TOK_XOR,      GEN_NOPUSH,     g_xor   },
2443         { TOK_INVALID,  0,              0       }
2444     };
2445     int UsedGen;
2446
2447     hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2448 }
2449
2450
2451
2452 static void hie2 (ExprDesc* Expr)
2453 /* Handle | (bitwise or) */
2454 {
2455     static const GenDesc hie2_ops[] = {
2456         { TOK_OR,       GEN_NOPUSH,     g_or    },
2457         { TOK_INVALID,  0,              0       }
2458     };
2459     int UsedGen;
2460
2461     hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2462 }
2463
2464
2465
2466 static void hieAndPP (ExprDesc* Expr)
2467 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2468  * called recursively from the preprocessor.
2469  */
2470 {
2471     ExprDesc Expr2;
2472
2473     ConstAbsIntExpr (hie2, Expr);
2474     while (CurTok.Tok == TOK_BOOL_AND) {
2475
2476         /* Skip the && */
2477         NextToken ();
2478
2479         /* Get rhs */
2480         ConstAbsIntExpr (hie2, &Expr2);
2481
2482         /* Combine the two */
2483         Expr->IVal = (Expr->IVal && Expr2.IVal);
2484     }
2485 }
2486
2487
2488
2489 static void hieOrPP (ExprDesc *Expr)
2490 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2491  * called recursively from the preprocessor.
2492  */
2493 {
2494     ExprDesc Expr2;
2495
2496     ConstAbsIntExpr (hieAndPP, Expr);
2497     while (CurTok.Tok == TOK_BOOL_OR) {
2498
2499         /* Skip the && */
2500         NextToken ();
2501
2502         /* Get rhs */
2503         ConstAbsIntExpr (hieAndPP, &Expr2);
2504
2505         /* Combine the two */
2506         Expr->IVal = (Expr->IVal || Expr2.IVal);
2507     }
2508 }
2509
2510
2511
2512 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2513 /* Process "exp && exp" */
2514 {
2515     int lab;
2516     ExprDesc Expr2;
2517
2518     hie2 (Expr);
2519     if (CurTok.Tok == TOK_BOOL_AND) {
2520
2521         /* Tell our caller that we're evaluating a boolean */
2522         *BoolOp = 1;
2523
2524         /* Get a label that we will use for false expressions */
2525         lab = GetLocalLabel ();
2526
2527         /* If the expr hasn't set condition codes, set the force-test flag */
2528         if (!ED_IsTested (Expr)) {
2529             ED_MarkForTest (Expr);
2530         }
2531
2532         /* Load the value */
2533         LoadExpr (CF_FORCECHAR, Expr);
2534
2535         /* Generate the jump */
2536         g_falsejump (CF_NONE, lab);
2537
2538         /* Parse more boolean and's */
2539         while (CurTok.Tok == TOK_BOOL_AND) {
2540
2541             /* Skip the && */
2542             NextToken ();
2543
2544             /* Get rhs */
2545             hie2 (&Expr2);
2546             if (!ED_IsTested (&Expr2)) {
2547                 ED_MarkForTest (&Expr2);
2548             }
2549             LoadExpr (CF_FORCECHAR, &Expr2);
2550
2551             /* Do short circuit evaluation */
2552             if (CurTok.Tok == TOK_BOOL_AND) {
2553                 g_falsejump (CF_NONE, lab);
2554             } else {
2555                 /* Last expression - will evaluate to true */
2556                 g_truejump (CF_NONE, TrueLab);
2557             }
2558         }
2559
2560         /* Define the false jump label here */
2561         g_defcodelabel (lab);
2562
2563         /* The result is an rvalue in primary */
2564         ED_MakeRValExpr (Expr);
2565         ED_TestDone (Expr);     /* Condition codes are set */
2566     }
2567 }
2568
2569
2570
2571 static void hieOr (ExprDesc *Expr)
2572 /* Process "exp || exp". */
2573 {
2574     ExprDesc Expr2;
2575     int BoolOp = 0;             /* Did we have a boolean op? */
2576     int AndOp;                  /* Did we have a && operation? */
2577     unsigned TrueLab;           /* Jump to this label if true */
2578     unsigned DoneLab;
2579
2580     /* Get a label */
2581     TrueLab = GetLocalLabel ();
2582
2583     /* Call the next level parser */
2584     hieAnd (Expr, TrueLab, &BoolOp);
2585
2586     /* Any boolean or's? */
2587     if (CurTok.Tok == TOK_BOOL_OR) {
2588
2589         /* If the expr hasn't set condition codes, set the force-test flag */
2590         if (!ED_IsTested (Expr)) {
2591             ED_MarkForTest (Expr);
2592         }
2593
2594         /* Get first expr */
2595         LoadExpr (CF_FORCECHAR, Expr);
2596
2597         /* For each expression jump to TrueLab if true. Beware: If we
2598          * had && operators, the jump is already in place!
2599          */
2600         if (!BoolOp) {
2601             g_truejump (CF_NONE, TrueLab);
2602         }
2603
2604         /* Remember that we had a boolean op */
2605         BoolOp = 1;
2606
2607         /* while there's more expr */
2608         while (CurTok.Tok == TOK_BOOL_OR) {
2609
2610             /* skip the || */
2611             NextToken ();
2612
2613             /* Get a subexpr */
2614             AndOp = 0;
2615             hieAnd (&Expr2, TrueLab, &AndOp);
2616             if (!ED_IsTested (&Expr2)) {
2617                 ED_MarkForTest (&Expr2);
2618             }
2619             LoadExpr (CF_FORCECHAR, &Expr2);
2620
2621             /* If there is more to come, add shortcut boolean eval. */
2622             g_truejump (CF_NONE, TrueLab);
2623
2624         }
2625
2626         /* The result is an rvalue in primary */
2627         ED_MakeRValExpr (Expr);
2628         ED_TestDone (Expr);                     /* Condition codes are set */
2629     }
2630
2631     /* If we really had boolean ops, generate the end sequence */
2632     if (BoolOp) {
2633         DoneLab = GetLocalLabel ();
2634         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2635         g_falsejump (CF_NONE, DoneLab);
2636         g_defcodelabel (TrueLab);
2637         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2638         g_defcodelabel (DoneLab);
2639     }
2640 }
2641
2642
2643
2644 static void hieQuest (ExprDesc* Expr)
2645 /* Parse the ternary operator */
2646 {
2647     int         labf;
2648     int         labt;
2649     ExprDesc    Expr2;          /* Expression 2 */
2650     ExprDesc    Expr3;          /* Expression 3 */
2651     int         Expr2IsNULL;    /* Expression 2 is a NULL pointer */
2652     int         Expr3IsNULL;    /* Expression 3 is a NULL pointer */
2653     Type*       ResultType;     /* Type of result */
2654
2655
2656     /* Call the lower level eval routine */
2657     if (Preprocessing) {
2658         hieOrPP (Expr);
2659     } else {
2660         hieOr (Expr);
2661     }
2662
2663     /* Check if it's a ternary expression */
2664     if (CurTok.Tok == TOK_QUEST) {
2665         NextToken ();
2666         if (!ED_IsTested (Expr)) {
2667             /* Condition codes not set, request a test */
2668             ED_MarkForTest (Expr);
2669         }
2670         LoadExpr (CF_NONE, Expr);
2671         labf = GetLocalLabel ();
2672         g_falsejump (CF_NONE, labf);
2673
2674         /* Parse second expression. Remember for later if it is a NULL pointer
2675          * expression, then load it into the primary.
2676          */
2677         ExprWithCheck (hie1, &Expr2);
2678         Expr2IsNULL = ED_IsNullPtr (&Expr2);
2679         if (!IsTypeVoid (Expr2.Type)) {
2680             /* Load it into the primary */
2681             LoadExpr (CF_NONE, &Expr2);
2682             ED_MakeRValExpr (&Expr2);
2683         }
2684         labt = GetLocalLabel ();
2685         ConsumeColon ();
2686         g_jump (labt);
2687
2688         /* Jump here if the first expression was false */
2689         g_defcodelabel (labf);
2690
2691         /* Parse second expression. Remember for later if it is a NULL pointer
2692          * expression, then load it into the primary.
2693          */
2694         ExprWithCheck (hie1, &Expr3);
2695         Expr3IsNULL = ED_IsNullPtr (&Expr3);
2696         if (!IsTypeVoid (Expr3.Type)) {
2697             /* Load it into the primary */
2698             LoadExpr (CF_NONE, &Expr3);
2699             ED_MakeRValExpr (&Expr3);
2700         }
2701
2702         /* Check if any conversions are needed, if so, do them.
2703          * Conversion rules for ?: expression are:
2704          *   - if both expressions are int expressions, default promotion
2705          *     rules for ints apply.
2706          *   - if both expressions are pointers of the same type, the
2707          *     result of the expression is of this type.
2708          *   - if one of the expressions is a pointer and the other is
2709          *     a zero constant, the resulting type is that of the pointer
2710          *     type.
2711          *   - if both expressions are void expressions, the result is of
2712          *     type void.
2713          *   - all other cases are flagged by an error.
2714          */
2715         if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2716
2717             /* Get common type */
2718             ResultType = promoteint (Expr2.Type, Expr3.Type);
2719
2720             /* Convert the third expression to this type if needed */
2721             TypeConversion (&Expr3, ResultType);
2722
2723             /* Setup a new label so that the expr3 code will jump around
2724              * the type cast code for expr2.
2725              */
2726             labf = GetLocalLabel ();    /* Get new label */
2727             g_jump (labf);              /* Jump around code */
2728
2729             /* The jump for expr2 goes here */
2730             g_defcodelabel (labt);
2731
2732             /* Create the typecast code for expr2 */
2733             TypeConversion (&Expr2, ResultType);
2734
2735             /* Jump here around the typecase code. */
2736             g_defcodelabel (labf);
2737             labt = 0;           /* Mark other label as invalid */
2738
2739         } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2740             /* Must point to same type */
2741             if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2742                 Error ("Incompatible pointer types");
2743             }
2744             /* Result has the common type */
2745             ResultType = Expr2.Type;
2746         } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2747             /* Result type is pointer, no cast needed */
2748             ResultType = Expr2.Type;
2749         } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2750             /* Result type is pointer, no cast needed */
2751             ResultType = Expr3.Type;
2752         } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2753             /* Result type is void */
2754             ResultType = Expr3.Type;
2755         } else {
2756             Error ("Incompatible types");
2757             ResultType = Expr2.Type;            /* Doesn't matter here */
2758         }
2759
2760         /* If we don't have the label defined until now, do it */
2761         if (labt) {
2762             g_defcodelabel (labt);
2763         }
2764
2765         /* Setup the target expression */
2766         ED_MakeRValExpr (Expr);
2767         Expr->Type  = ResultType;
2768     }
2769 }
2770
2771
2772
2773 static void opeq (const GenDesc* Gen, ExprDesc* Expr)
2774 /* Process "op=" operators. */
2775 {
2776     ExprDesc Expr2;
2777     unsigned flags;
2778     CodeMark Mark;
2779     int MustScale;
2780
2781     /* op= can only be used with lvalues */
2782     if (!ED_IsLVal (Expr)) {
2783         Error ("Invalid lvalue in assignment");
2784         return;
2785     }
2786
2787     /* The left side must not be const qualified */
2788     if (IsQualConst (Expr->Type)) {
2789         Error ("Assignment to const");
2790     }
2791
2792     /* There must be an integer or pointer on the left side */
2793     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2794         Error ("Invalid left operand type");
2795         /* Continue. Wrong code will be generated, but the compiler won't
2796          * break, so this is the best error recovery.
2797          */
2798     }
2799
2800     /* Skip the operator token */
2801     NextToken ();
2802
2803     /* Determine the type of the lhs */
2804     flags = TypeOf (Expr->Type);
2805     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2806
2807     /* Get the lhs address on stack (if needed) */
2808     PushAddr (Expr);
2809
2810     /* Fetch the lhs into the primary register if needed */
2811     LoadExpr (CF_NONE, Expr);
2812
2813     /* Bring the lhs on stack */
2814     GetCodePos (&Mark);
2815     g_push (flags, 0);
2816
2817     /* Evaluate the rhs */
2818     if (evalexpr (CF_NONE, hie1, &Expr2) == 0) {
2819         /* The resulting value is a constant. If the generator has the NOPUSH
2820          * flag set, don't push the lhs.
2821          */
2822         if (Gen->Flags & GEN_NOPUSH) {
2823             RemoveCode (&Mark);
2824         }
2825         if (MustScale) {
2826             /* lhs is a pointer, scale rhs */
2827             Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2828         }
2829
2830         /* If the lhs is character sized, the operation may be later done
2831          * with characters.
2832          */
2833         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2834             flags |= CF_FORCECHAR;
2835         }
2836
2837         /* Special handling for add and sub - some sort of a hack, but short code */
2838         if (Gen->Func == g_add) {
2839             g_inc (flags | CF_CONST, Expr2.IVal);
2840         } else if (Gen->Func == g_sub) {
2841             g_dec (flags | CF_CONST, Expr2.IVal);
2842         } else {
2843             Gen->Func (flags | CF_CONST, Expr2.IVal);
2844         }
2845     } else {
2846         /* rhs is not constant and already in the primary register */
2847         if (MustScale) {
2848             /* lhs is a pointer, scale rhs */
2849             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2850         }
2851
2852         /* If the lhs is character sized, the operation may be later done
2853          * with characters.
2854          */
2855         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2856             flags |= CF_FORCECHAR;
2857         }
2858
2859         /* Adjust the types of the operands if needed */
2860         Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2861     }
2862     Store (Expr, 0);
2863     ED_MakeRValExpr (Expr);
2864 }
2865
2866
2867
2868 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr)
2869 /* Process the += and -= operators */
2870 {
2871     ExprDesc Expr2;
2872     unsigned lflags;
2873     unsigned rflags;
2874     int      MustScale;
2875
2876
2877     /* We're currently only able to handle some adressing modes */
2878     if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2879         /* Use generic routine */
2880         opeq (Gen, Expr);
2881         return;
2882     }
2883
2884     /* We must have an lvalue */
2885     if (ED_IsRVal (Expr)) {
2886         Error ("Invalid lvalue in assignment");
2887         return;
2888     }
2889
2890     /* The left side must not be const qualified */
2891     if (IsQualConst (Expr->Type)) {
2892         Error ("Assignment to const");
2893     }
2894
2895     /* There must be an integer or pointer on the left side */
2896     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2897         Error ("Invalid left operand type");
2898         /* Continue. Wrong code will be generated, but the compiler won't
2899          * break, so this is the best error recovery.
2900          */
2901     }
2902
2903     /* Skip the operator */
2904     NextToken ();
2905
2906     /* Check if we have a pointer expression and must scale rhs */
2907     MustScale = IsTypePtr (Expr->Type);
2908
2909     /* Initialize the code generator flags */
2910     lflags = 0;
2911     rflags = 0;
2912
2913     /* Evaluate the rhs */
2914     hie1 (&Expr2);
2915     if (ED_IsConstAbs (&Expr2)) {
2916         /* The resulting value is a constant. Scale it. */
2917         if (MustScale) {
2918             Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
2919         }
2920         rflags |= CF_CONST;
2921         lflags |= CF_CONST;
2922     } else {
2923         /* Not constant, load into the primary */
2924         LoadExpr (CF_NONE, &Expr2);
2925         if (MustScale) {
2926             /* lhs is a pointer, scale rhs */
2927             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
2928         }
2929     }
2930
2931     /* Setup the code generator flags */
2932     lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
2933     rflags |= TypeOf (Expr2.Type);
2934
2935     /* Convert the type of the lhs to that of the rhs */
2936     g_typecast (lflags, rflags);
2937
2938     /* Output apropriate code depending on the location */
2939     switch (ED_GetLoc (Expr)) {
2940
2941         case E_LOC_ABS:
2942             /* Absolute: numeric address or const */
2943             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2944                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2945             } else {
2946                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2947             }
2948             break;
2949
2950         case E_LOC_GLOBAL:
2951             /* Global variable */
2952             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2953                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2954             } else {
2955                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2956             }
2957             break;
2958
2959         case E_LOC_STATIC:
2960         case E_LOC_LITERAL:
2961             /* Static variable or literal in the literal pool */
2962             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2963                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2964             } else {
2965                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2966             }
2967             break;
2968
2969         case E_LOC_REGISTER:
2970             /* Register variable */
2971             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2972                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2973             } else {
2974                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2975             }
2976             break;
2977
2978         case E_LOC_STACK:
2979             /* Value on the stack */
2980             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2981                 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
2982             } else {
2983                 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
2984             }
2985             break;
2986
2987         default:
2988             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
2989     }
2990
2991     /* Expression is a rvalue in the primary now */
2992     ED_MakeRValExpr (Expr);
2993 }
2994
2995
2996
2997 void hie1 (ExprDesc* Expr)
2998 /* Parse first level of expression hierarchy. */
2999 {
3000     hieQuest (Expr);
3001     switch (CurTok.Tok) {
3002
3003         case TOK_ASSIGN:
3004             Assignment (Expr);
3005             break;
3006
3007         case TOK_PLUS_ASSIGN:
3008             addsubeq (&GenPASGN, Expr);
3009             break;
3010
3011         case TOK_MINUS_ASSIGN:
3012             addsubeq (&GenSASGN, Expr);
3013             break;
3014
3015         case TOK_MUL_ASSIGN:
3016             opeq (&GenMASGN, Expr);
3017             break;
3018
3019         case TOK_DIV_ASSIGN:
3020             opeq (&GenDASGN, Expr);
3021             break;
3022
3023         case TOK_MOD_ASSIGN:
3024             opeq (&GenMOASGN, Expr);
3025             break;
3026
3027         case TOK_SHL_ASSIGN:
3028             opeq (&GenSLASGN, Expr);
3029             break;
3030
3031         case TOK_SHR_ASSIGN:
3032             opeq (&GenSRASGN, Expr);
3033             break;
3034
3035         case TOK_AND_ASSIGN:
3036             opeq (&GenAASGN, Expr);
3037             break;
3038
3039         case TOK_XOR_ASSIGN:
3040             opeq (&GenXOASGN, Expr);
3041             break;
3042
3043         case TOK_OR_ASSIGN:
3044             opeq (&GenOASGN, Expr);
3045             break;
3046
3047         default:
3048             break;
3049     }
3050 }
3051
3052
3053
3054 void hie0 (ExprDesc *Expr)
3055 /* Parse comma operator. */
3056 {
3057     hie1 (Expr);
3058     while (CurTok.Tok == TOK_COMMA) {
3059         NextToken ();
3060         hie1 (Expr);
3061     }
3062 }
3063
3064
3065
3066 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3067 /* Will evaluate an expression via the given function. If the result is a
3068  * constant, 0 is returned and the value is put in the Expr struct. If the
3069  * result is not constant, LoadExpr is called to bring the value into the
3070  * primary register and 1 is returned.
3071  */
3072 {
3073     /* Evaluate */
3074     ExprWithCheck (Func, Expr);
3075
3076     /* Check for a constant expression */
3077     if (ED_IsConstAbs (Expr)) {
3078         /* Constant expression */
3079         return 0;
3080     } else {
3081         /* Not constant, load into the primary */
3082         LoadExpr (Flags, Expr);
3083         return 1;
3084     }
3085 }
3086
3087
3088
3089 void Expression0 (ExprDesc* Expr)
3090 /* Evaluate an expression via hie0 and put the result into the primary register */
3091 {
3092     ExprWithCheck (hie0, Expr);
3093     LoadExpr (CF_NONE, Expr);
3094 }
3095
3096
3097
3098 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3099 /* Will evaluate an expression via the given function. If the result is not
3100  * a constant of some sort, a diagnostic will be printed, and the value is
3101  * replaced by a constant one to make sure there are no internal errors that
3102  * result from this input error.
3103  */
3104 {
3105     ExprWithCheck (Func, Expr);
3106     if (!ED_IsConst (Expr)) {
3107         Error ("Constant expression expected");
3108         /* To avoid any compiler errors, make the expression a valid const */
3109         ED_MakeConstAbsInt (Expr, 1);
3110     }
3111 }
3112
3113
3114
3115 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3116 /* Will evaluate an expression via the given function. If the result is not
3117  * something that may be evaluated in a boolean context, a diagnostic will be
3118  * printed, and the value is replaced by a constant one to make sure there
3119  * are no internal errors that result from this input error.
3120  */
3121 {
3122     ExprWithCheck (Func, Expr);
3123     if (!ED_IsBool (Expr)) {
3124         Error ("Boolean expression expected");
3125         /* To avoid any compiler errors, make the expression a valid int */
3126         ED_MakeConstAbsInt (Expr, 1);
3127     }
3128 }
3129
3130
3131
3132 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3133 /* Will evaluate an expression via the given function. If the result is not
3134  * a constant numeric integer value, a diagnostic will be printed, and the
3135  * value is replaced by a constant one to make sure there are no internal
3136  * errors that result from this input error.
3137  */
3138 {
3139     ExprWithCheck (Func, Expr);
3140     if (!ED_IsConstAbsInt (Expr)) {
3141         Error ("Constant integer expression expected");
3142         /* To avoid any compiler errors, make the expression a valid const */
3143         ED_MakeConstAbsInt (Expr, 1);
3144     }
3145 }
3146
3147
3148