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