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