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