3 * Ullrich von Bassewitz, 21.06.1998
13 #include "debugflag.h"
20 #include "assignment.h"
32 #include "shiftexpr.h"
43 /*****************************************************************************/
45 /*****************************************************************************/
49 /* Generator attributes */
50 #define GEN_NOPUSH 0x01 /* Don't push lhs */
52 /* Map a generator function and its attributes to a token */
54 token_t Tok; /* Token to map to */
55 unsigned Flags; /* Flags for generator function */
56 void (*Func) (unsigned, unsigned long); /* Generator func */
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 };
73 /*****************************************************************************/
74 /* Helper functions */
75 /*****************************************************************************/
79 static unsigned GlobalModeFlags (const ExprDesc* Expr)
80 /* Return the addressing mode flags for the given expression */
82 switch (ED_GetLoc (Expr)) {
83 case E_LOC_ABS: return CF_ABSOLUTE;
84 case E_LOC_GLOBAL: return CF_EXTERNAL;
85 case E_LOC_STATIC: return CF_STATIC;
86 case E_LOC_REGISTER: return CF_REGVAR;
87 case E_LOC_STACK: return CF_NONE;
88 case E_LOC_PRIMARY: return CF_NONE;
89 case E_LOC_EXPR: return CF_NONE;
90 case E_LOC_LITERAL: return CF_STATIC; /* Same as static */
92 Internal ("GlobalModeFlags: Invalid location flags value: 0x%04X", Expr->Flags);
100 void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
101 /* Call an expression function with checks. */
103 /* Remember the stack pointer */
104 int OldSP = StackPtr;
106 /* Call the expression function */
109 /* Do some checks if code generation is still constistent */
110 if (StackPtr != OldSP) {
113 "Code generation messed up!\n"
114 "StackPtr is %d, should be %d",
117 Internal ("StackPtr is %d, should be %d\n", StackPtr, OldSP);
124 void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
125 /* Call an expression function with checks and record start and end of the
131 ExprWithCheck (Func, Expr);
133 ED_SetCodeRange (Expr, &Start, &End);
138 static Type* promoteint (Type* lhst, Type* rhst)
139 /* In an expression with two ints, return the type of the result */
141 /* Rules for integer types:
142 * - If one of the values is a long, the result is long.
143 * - If one of the values is unsigned, the result is also unsigned.
144 * - Otherwise the result is an int.
146 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
147 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
153 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
163 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
164 /* Adjust the two values for a binary operation. lhs is expected on stack or
165 * to be constant, rhs is expected to be in the primary register or constant.
166 * The function will put the type of the result into lhs and return the
167 * code generator flags for the operation.
168 * If NoPush is given, it is assumed that the operation does not expect the lhs
169 * to be on stack, and that lhs is in a register instead.
170 * Beware: The function does only accept int types.
173 unsigned ltype, rtype;
176 /* Get the type strings */
177 Type* lhst = lhs->Type;
178 Type* rhst = rhs->Type;
180 /* Generate type adjustment code if needed */
181 ltype = TypeOf (lhst);
182 if (ED_IsLocAbs (lhs)) {
186 /* Value is in primary register*/
189 rtype = TypeOf (rhst);
190 if (ED_IsLocAbs (rhs)) {
193 flags = g_typeadjust (ltype, rtype);
195 /* Set the type of the result */
196 lhs->Type = promoteint (lhst, rhst);
198 /* Return the code generator flags */
204 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
205 /* Find a token in a generator table */
207 while (Table->Tok != TOK_INVALID) {
208 if (Table->Tok == Tok) {
218 static int TypeSpecAhead (void)
219 /* Return true if some sort of type is waiting (helper for cast and sizeof()
225 /* There's a type waiting if:
227 * We have an opening paren, and
228 * a. the next token is a type, or
229 * b. the next token is a type qualifier, or
230 * c. the next token is a typedef'd type
232 return CurTok.Tok == TOK_LPAREN && (
233 TokIsType (&NextTok) ||
234 TokIsTypeQual (&NextTok) ||
235 (NextTok.Tok == TOK_IDENT &&
236 (Entry = FindSym (NextTok.Ident)) != 0 &&
237 SymIsTypeDef (Entry)));
242 void PushAddr (const ExprDesc* Expr)
243 /* If the expression contains an address that was somehow evaluated,
244 * push this address on the stack. This is a helper function for all
245 * sorts of implicit or explicit assignment functions where the lvalue
246 * must be saved if it's not constant, before evaluating the rhs.
249 /* Get the address on stack if needed */
250 if (ED_IsLocExpr (Expr)) {
251 /* Push the address (always a pointer) */
258 /*****************************************************************************/
260 /*****************************************************************************/
264 static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall)
265 /* Parse a function parameter list and pass the parameters to the called
266 * function. Depending on several criteria this may be done by just pushing
267 * each parameter separately, or creating the parameter frame once and then
268 * storing into this frame.
269 * The function returns the size of the parameters pushed.
274 /* Initialize variables */
275 SymEntry* Param = 0; /* Keep gcc silent */
276 unsigned ParamSize = 0; /* Size of parameters pushed */
277 unsigned ParamCount = 0; /* Number of parameters pushed */
278 unsigned FrameSize = 0; /* Size of parameter frame */
279 unsigned FrameParams = 0; /* Number of params in frame */
280 int FrameOffs = 0; /* Offset into parameter frame */
281 int Ellipsis = 0; /* Function is variadic */
283 /* As an optimization, we may allocate the complete parameter frame at
284 * once instead of pushing each parameter as it comes. We may do that,
287 * - optimizations that increase code size are enabled (allocating the
288 * stack frame at once gives usually larger code).
289 * - we have more than one parameter to push (don't count the last param
290 * for __fastcall__ functions).
292 * The FrameSize variable will contain a value > 0 if storing into a frame
293 * (instead of pushing) is enabled.
296 if (IS_Get (&CodeSizeFactor) >= 200) {
298 /* Calculate the number and size of the parameters */
299 FrameParams = Func->ParamCount;
300 FrameSize = Func->ParamSize;
301 if (FrameParams > 0 && IsFastcall) {
302 /* Last parameter is not pushed */
303 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
307 /* Do we have more than one parameter in the frame? */
308 if (FrameParams > 1) {
309 /* Okeydokey, setup the frame */
310 FrameOffs = StackPtr;
312 StackPtr -= FrameSize;
314 /* Don't use a preallocated frame */
319 /* Parse the actual parameter list */
320 while (CurTok.Tok != TOK_RPAREN) {
324 /* Count arguments */
327 /* Fetch the pointer to the next argument, check for too many args */
328 if (ParamCount <= Func->ParamCount) {
329 /* Beware: If there are parameters with identical names, they
330 * cannot go into the same symbol table, which means that in this
331 * case of errorneous input, the number of nodes in the symbol
332 * table and ParamCount are NOT equal. We have to handle this case
333 * below to avoid segmentation violations. Since we know that this
334 * problem can only occur if there is more than one parameter,
335 * we will just use the last one.
337 if (ParamCount == 1) {
339 Param = Func->SymTab->SymHead;
340 } else if (Param->NextSym != 0) {
342 Param = Param->NextSym;
343 CHECK ((Param->Flags & SC_PARAM) != 0);
345 } else if (!Ellipsis) {
346 /* Too many arguments. Do we have an open param list? */
347 if ((Func->Flags & FD_VARIADIC) == 0) {
348 /* End of param list reached, no ellipsis */
349 Error ("Too many arguments in function call");
351 /* Assume an ellipsis even in case of errors to avoid an error
352 * message for each other argument.
357 /* Evaluate the parameter expression */
360 /* If we don't have an argument spec, accept anything, otherwise
361 * convert the actual argument to the type needed.
366 /* Convert the argument to the parameter type if needed */
367 TypeConversion (&Expr, Param->Type);
369 /* If we have a prototype, chars may be pushed as chars */
370 Flags |= CF_FORCECHAR;
374 /* No prototype available. Convert array to "pointer to first
375 * element", and function to "pointer to function".
377 Expr.Type = PtrConversion (Expr.Type);
381 /* Load the value into the primary if it is not already there */
382 LoadExpr (Flags, &Expr);
384 /* Use the type of the argument for the push */
385 Flags |= TypeOf (Expr.Type);
387 /* If this is a fastcall function, don't push the last argument */
388 if (ParamCount != Func->ParamCount || !IsFastcall) {
389 unsigned ArgSize = sizeofarg (Flags);
391 /* We have the space already allocated, store in the frame.
392 * Because of invalid type conversions (that have produced an
393 * error before), we can end up here with a non aligned stack
394 * frame. Since no output will be generated anyway, handle
395 * these cases gracefully instead of doing a CHECK.
397 if (FrameSize >= ArgSize) {
398 FrameSize -= ArgSize;
402 FrameOffs -= ArgSize;
404 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
406 /* Push the argument */
407 g_push (Flags, Expr.IVal);
410 /* Calculate total parameter size */
411 ParamSize += ArgSize;
414 /* Check for end of argument list */
415 if (CurTok.Tok != TOK_COMMA) {
421 /* Check if we had enough parameters */
422 if (ParamCount < Func->ParamCount) {
423 Error ("Too few arguments in function call");
426 /* The function returns the size of all parameters pushed onto the stack.
427 * However, if there are parameters missing (which is an error and was
428 * flagged by the compiler) AND a stack frame was preallocated above,
429 * we would loose track of the stackpointer and generate an internal error
430 * later. So we correct the value by the parameters that should have been
431 * pushed to avoid an internal compiler error. Since an error was
432 * generated before, no code will be output anyway.
434 return ParamSize + FrameSize;
439 static void FunctionCall (ExprDesc* Expr)
440 /* Perform a function call. */
442 FuncDesc* Func; /* Function descriptor */
443 int IsFuncPtr; /* Flag */
444 unsigned ParamSize; /* Number of parameter bytes */
446 int PtrOffs = 0; /* Offset of function pointer on stack */
447 int IsFastcall = 0; /* True if it's a fast call function */
448 int PtrOnStack = 0; /* True if a pointer copy is on stack */
450 /* Skip the left paren */
453 /* Get a pointer to the function descriptor from the type string */
454 Func = GetFuncDesc (Expr->Type);
456 /* Handle function pointers transparently */
457 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
460 /* Check wether it's a fastcall function that has parameters */
461 IsFastcall = IsQualFastcall (Expr->Type + 1) && (Func->ParamCount > 0);
463 /* Things may be difficult, depending on where the function pointer
464 * resides. If the function pointer is an expression of some sort
465 * (not a local or global variable), we have to evaluate this
466 * expression now and save the result for later. Since calls to
467 * function pointers may be nested, we must save it onto the stack.
468 * For fastcall functions we do also need to place a copy of the
469 * pointer on stack, since we cannot use a/x.
471 PtrOnStack = IsFastcall || !ED_IsConst (Expr);
474 /* Not a global or local variable, or a fastcall function. Load
475 * the pointer into the primary and mark it as an expression.
477 LoadExpr (CF_NONE, Expr);
478 ED_MakeRValExpr (Expr);
480 /* Remember the code position */
483 /* Push the pointer onto the stack and remember the offset */
489 /* Check for known standard functions and inline them */
490 if (Expr->Name != 0) {
491 int StdFunc = FindStdFunc ((const char*) Expr->Name);
493 /* Inline this function */
494 HandleStdFunc (StdFunc, Func, Expr);
499 /* If we didn't inline the function, get fastcall info */
500 IsFastcall = IsQualFastcall (Expr->Type);
503 /* Parse the parameter list */
504 ParamSize = FunctionParamList (Func, IsFastcall);
506 /* We need the closing paren here */
509 /* Special handling for function pointers */
512 /* If the function is not a fastcall function, load the pointer to
513 * the function into the primary.
517 /* Not a fastcall function - we may use the primary */
519 /* If we have no parameters, the pointer is still in the
520 * primary. Remove the code to push it and correct the
523 if (ParamSize == 0) {
527 /* Load from the saved copy */
528 g_getlocal (CF_PTR, PtrOffs);
531 /* Load from original location */
532 LoadExpr (CF_NONE, Expr);
535 /* Call the function */
536 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
540 /* Fastcall function. We cannot use the primary for the function
541 * pointer and must therefore use an offset to the stack location.
542 * Since fastcall functions may never be variadic, we can use the
543 * index register for this purpose.
545 g_callind (CF_LOCAL, ParamSize, PtrOffs);
548 /* If we have a pointer on stack, remove it */
550 g_space (- (int) sizeofarg (CF_PTR));
559 /* Normal function */
560 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
564 /* The function result is an rvalue in the primary register */
565 ED_MakeRValExpr (Expr);
566 Expr->Type = GetFuncReturn (Expr->Type);
571 static void Primary (ExprDesc* E)
572 /* This is the lowest level of the expression parser. */
576 /* Initialize fields in the expression stucture */
579 /* Character and integer constants. */
580 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
581 E->IVal = CurTok.IVal;
582 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
583 E->Type = CurTok.Type;
588 /* Floating point constant */
589 if (CurTok.Tok == TOK_FCONST) {
590 E->FVal = CurTok.FVal;
591 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
592 E->Type = CurTok.Type;
597 /* Process parenthesized subexpression by calling the whole parser
600 if (CurTok.Tok == TOK_LPAREN) {
607 /* If we run into an identifier in preprocessing mode, we assume that this
608 * is an undefined macro and replace it by a constant value of zero.
610 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
612 ED_MakeConstAbsInt (E, 0);
616 /* All others may only be used if the expression evaluation is not called
617 * recursively by the preprocessor.
620 /* Illegal expression in PP mode */
621 Error ("Preprocessor expression expected");
622 ED_MakeConstAbsInt (E, 1);
626 switch (CurTok.Tok) {
629 /* Identifier. Get a pointer to the symbol table entry */
630 Sym = E->Sym = FindSym (CurTok.Ident);
632 /* Is the symbol known? */
635 /* We found the symbol - skip the name token */
638 /* Check for illegal symbol types */
639 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
640 if (Sym->Flags & SC_TYPE) {
641 /* Cannot use type symbols */
642 Error ("Variable identifier expected");
643 /* Assume an int type to make E valid */
644 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
649 /* Mark the symbol as referenced */
650 Sym->Flags |= SC_REF;
652 /* The expression type is the symbol type */
655 /* Check for legal symbol types */
656 if ((Sym->Flags & SC_CONST) == SC_CONST) {
657 /* Enum or some other numeric constant */
658 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
659 E->IVal = Sym->V.ConstVal;
660 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
662 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
663 E->Name = (unsigned long) Sym->Name;
664 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
665 /* Local variable. If this is a parameter for a variadic
666 * function, we have to add some address calculations, and the
667 * address is not const.
669 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
670 /* Variadic parameter */
671 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
672 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
674 /* Normal parameter */
675 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
676 E->IVal = Sym->V.Offs;
678 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
679 /* Register variable, zero page based */
680 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
681 E->Name = Sym->V.R.RegOffs;
682 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
683 /* Static variable */
684 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
685 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
686 E->Name = (unsigned long) Sym->Name;
688 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
689 E->Name = Sym->V.Label;
692 /* Local static variable */
693 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
694 E->Name = Sym->V.Offs;
697 /* We've made all variables lvalues above. However, this is
698 * not always correct: An array is actually the address of its
699 * first element, which is a rvalue, and a function is a
700 * rvalue, too, because we cannot store anything in a function.
701 * So fix the flags depending on the type.
703 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
709 /* We did not find the symbol. Remember the name, then skip it */
711 strcpy (Ident, CurTok.Ident);
714 /* IDENT is either an auto-declared function or an undefined variable. */
715 if (CurTok.Tok == TOK_LPAREN) {
716 /* C99 doesn't allow calls to undefined functions, so
717 * generate an error and otherwise a warning. Declare a
718 * function returning int. For that purpose, prepare a
719 * function signature for a function having an empty param
720 * list and returning int.
722 if (IS_Get (&Standard) >= STD_C99) {
723 Error ("Call to undefined function `%s'", Ident);
725 Warning ("Call to undefined function `%s'", Ident);
727 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
729 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
730 E->Name = (unsigned long) Sym->Name;
732 /* Undeclared Variable */
733 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
734 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
736 Error ("Undefined symbol: `%s'", Ident);
745 E->Type = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
746 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
747 E->IVal = CurTok.IVal;
748 E->Name = LiteralPoolLabel;
755 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
760 /* Register pseudo variable */
761 E->Type = type_uchar;
762 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
767 /* Register pseudo variable */
769 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
774 /* Register pseudo variable */
775 E->Type = type_ulong;
776 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
781 /* Illegal primary. Be sure to skip the token to avoid endless
784 Error ("Expression expected");
786 ED_MakeConstAbsInt (E, 1);
793 static void ArrayRef (ExprDesc* Expr)
794 /* Handle an array reference. This function needs a rewrite. */
804 /* Skip the bracket */
807 /* Get the type of left side */
810 /* We can apply a special treatment for arrays that have a const base
811 * address. This is true for most arrays and will produce a lot better
812 * code. Check if this is a const base address.
814 ConstBaseAddr = ED_IsRVal (Expr) &&
815 (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
817 /* If we have a constant base, we delay the address fetch */
819 if (!ConstBaseAddr) {
820 /* Get a pointer to the array into the primary */
821 LoadExpr (CF_NONE, Expr);
823 /* Get the array pointer on stack. Do not push more than 16
824 * bit, even if this value is greater, since we cannot handle
825 * other than 16bit stuff when doing indexing.
831 /* TOS now contains ptr to array elements. Get the subscript. */
832 MarkedExprWithCheck (hie0, &Subscript);
834 /* Check the types of array and subscript. We can either have a
835 * pointer/array to the left, in which case the subscript must be of an
836 * integer type, or we have an integer to the left, in which case the
837 * subscript must be a pointer/array.
838 * Since we do the necessary checking here, we can rely later on the
841 if (IsClassPtr (Expr->Type)) {
842 if (!IsClassInt (Subscript.Type)) {
843 Error ("Array subscript is not an integer");
844 /* To avoid any compiler errors, make the expression a valid int */
845 ED_MakeConstAbsInt (&Subscript, 0);
847 ElementType = Indirect (Expr->Type);
848 } else if (IsClassInt (Expr->Type)) {
849 if (!IsClassPtr (Subscript.Type)) {
850 Error ("Subscripted value is neither array nor pointer");
851 /* To avoid compiler errors, make the subscript a char[] at
854 ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
856 ElementType = Indirect (Subscript.Type);
858 Error ("Cannot subscript");
859 /* To avoid compiler errors, fake both the array and the subscript, so
860 * we can just proceed.
862 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
863 ED_MakeConstAbsInt (&Subscript, 0);
864 ElementType = Indirect (Expr->Type);
867 /* If the subscript is a bit-field, load it and make it an rvalue */
868 if (ED_IsBitField (&Subscript)) {
869 LoadExpr (CF_NONE, &Subscript);
870 ED_MakeRValExpr (&Subscript);
873 /* Check if the subscript is constant absolute value */
874 if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) {
876 /* The array subscript is a numeric constant. If we had pushed the
877 * array base address onto the stack before, we can remove this value,
878 * since we can generate expression+offset.
880 if (!ConstBaseAddr) {
883 /* Get an array pointer into the primary */
884 LoadExpr (CF_NONE, Expr);
887 if (IsClassPtr (Expr->Type)) {
889 /* Lhs is pointer/array. Scale the subscript value according to
892 Subscript.IVal *= CheckedSizeOf (ElementType);
894 /* Remove the address load code */
897 /* In case of an array, we can adjust the offset of the expression
898 * already in Expr. If the base address was a constant, we can even
899 * remove the code that loaded the address into the primary.
901 if (IsTypeArray (Expr->Type)) {
903 /* Adjust the offset */
904 Expr->IVal += Subscript.IVal;
908 /* It's a pointer, so we do have to load it into the primary
909 * first (if it's not already there).
911 if (ConstBaseAddr || ED_IsLVal (Expr)) {
912 LoadExpr (CF_NONE, Expr);
913 ED_MakeRValExpr (Expr);
917 Expr->IVal = Subscript.IVal;
922 /* Scale the rhs value according to the element type */
923 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
925 /* Add the subscript. Since arrays are indexed by integers,
926 * we will ignore the true type of the subscript here and
927 * use always an int. #### Use offset but beware of LoadExpr!
929 g_inc (CF_INT | CF_CONST, Subscript.IVal);
935 /* Array subscript is not constant. Load it into the primary */
937 LoadExpr (CF_NONE, &Subscript);
940 if (IsClassPtr (Expr->Type)) {
942 /* Indexing is based on unsigneds, so we will just use the integer
943 * portion of the index (which is in (e)ax, so there's no further
946 g_scale (CF_INT, CheckedSizeOf (ElementType));
950 /* Get the int value on top. If we come here, we're sure, both
951 * values are 16 bit (the first one was truncated if necessary
952 * and the second one is a pointer). Note: If ConstBaseAddr is
953 * true, we don't have a value on stack, so to "swap" both, just
954 * push the subscript.
958 LoadExpr (CF_NONE, Expr);
965 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
969 /* The offset is now in the primary register. It we didn't have a
970 * constant base address for the lhs, the lhs address is already
971 * on stack, and we must add the offset. If the base address was
972 * constant, we call special functions to add the address to the
975 if (!ConstBaseAddr) {
977 /* The array base address is on stack and the subscript is in the
984 /* The subscript is in the primary, and the array base address is
985 * in Expr. If the subscript has itself a constant address, it is
986 * often a better idea to reverse again the order of the
987 * evaluation. This will generate better code if the subscript is
988 * a byte sized variable. But beware: This is only possible if the
989 * subscript was not scaled, that is, if this was a byte array
992 if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
993 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
997 /* Reverse the order of evaluation */
998 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
1003 RemoveCode (&Mark2);
1005 /* Get a pointer to the array into the primary. */
1006 LoadExpr (CF_NONE, Expr);
1008 /* Add the variable */
1009 if (ED_IsLocStack (&Subscript)) {
1010 g_addlocal (Flags, Subscript.IVal);
1012 Flags |= GlobalModeFlags (&Subscript);
1013 g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1017 if (ED_IsLocAbs (Expr)) {
1018 /* Constant numeric address. Just add it */
1019 g_inc (CF_INT, Expr->IVal);
1020 } else if (ED_IsLocStack (Expr)) {
1021 /* Base address is a local variable address */
1022 if (IsTypeArray (Expr->Type)) {
1023 g_addaddr_local (CF_INT, Expr->IVal);
1025 g_addlocal (CF_PTR, Expr->IVal);
1028 /* Base address is a static variable address */
1029 unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1030 if (ED_IsRVal (Expr)) {
1031 /* Add the address of the location */
1032 g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1034 /* Add the contents of the location */
1035 g_addstatic (Flags, Expr->Name, Expr->IVal);
1043 /* The result is an expression in the primary */
1044 ED_MakeRValExpr (Expr);
1048 /* Result is of element type */
1049 Expr->Type = ElementType;
1051 /* An array element is actually a variable. So the rules for variables
1052 * with respect to the reference type apply: If it's an array, it is
1053 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1054 * but an array cannot contain functions).
1056 if (IsTypeArray (Expr->Type)) {
1062 /* Consume the closing bracket */
1068 static void StructRef (ExprDesc* Expr)
1069 /* Process struct field after . or ->. */
1075 /* Skip the token and check for an identifier */
1077 if (CurTok.Tok != TOK_IDENT) {
1078 Error ("Identifier expected");
1079 Expr->Type = type_int;
1083 /* Get the symbol table entry and check for a struct field */
1084 strcpy (Ident, CurTok.Ident);
1086 Field = FindStructField (Expr->Type, Ident);
1088 Error ("Struct/union has no field named `%s'", Ident);
1089 Expr->Type = type_int;
1093 /* If we have a struct pointer that is an lvalue and not already in the
1094 * primary, load it now.
1096 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1098 /* Load into the primary */
1099 LoadExpr (CF_NONE, Expr);
1101 /* Make it an lvalue expression */
1102 ED_MakeLValExpr (Expr);
1105 /* Set the struct field offset */
1106 Expr->IVal += Field->V.Offs;
1108 /* The type is the type of the field plus any qualifiers from the struct */
1109 Q = GetQualifier (Expr->Type);
1110 if (Q == T_QUAL_NONE) {
1111 Expr->Type = Field->Type;
1113 Expr->Type = TypeDup (Field->Type);
1117 /* An struct member is actually a variable. So the rules for variables
1118 * with respect to the reference type apply: If it's an array, it is
1119 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1120 * but a struct field cannot be a function).
1122 if (IsTypeArray (Expr->Type)) {
1128 /* Make the expression a bit field if necessary */
1129 if (SymIsBitField (Field)) {
1130 ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1136 static void hie11 (ExprDesc *Expr)
1137 /* Handle compound types (structs and arrays) */
1139 /* Name value used in invalid function calls */
1140 static const char IllegalFunc[] = "illegal_function_call";
1142 /* Evaluate the lhs */
1145 /* Check for a rhs */
1146 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1147 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1149 switch (CurTok.Tok) {
1152 /* Array reference */
1157 /* Function call. */
1158 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1159 /* Not a function */
1160 Error ("Illegal function call");
1161 /* Force the type to be a implicitly defined function, one
1162 * returning an int and taking any number of arguments.
1163 * Since we don't have a name, invent one.
1165 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1166 Expr->Name = (long) IllegalFunc;
1168 /* Call the function */
1169 FunctionCall (Expr);
1173 if (!IsClassStruct (Expr->Type)) {
1174 Error ("Struct expected");
1180 /* If we have an array, convert it to pointer to first element */
1181 if (IsTypeArray (Expr->Type)) {
1182 Expr->Type = ArrayToPtr (Expr->Type);
1184 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1185 Error ("Struct pointer expected");
1191 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1199 void Store (ExprDesc* Expr, const Type* StoreType)
1200 /* Store the primary register into the location denoted by Expr. If StoreType
1201 * is given, use this type when storing instead of Expr->Type. If StoreType
1202 * is NULL, use Expr->Type instead.
1207 /* If StoreType was not given, use Expr->Type instead */
1208 if (StoreType == 0) {
1209 StoreType = Expr->Type;
1212 /* Prepare the code generator flags */
1213 Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1215 /* Do the store depending on the location */
1216 switch (ED_GetLoc (Expr)) {
1219 /* Absolute: numeric address or const */
1220 g_putstatic (Flags, Expr->IVal, 0);
1224 /* Global variable */
1225 g_putstatic (Flags, Expr->Name, Expr->IVal);
1230 /* Static variable or literal in the literal pool */
1231 g_putstatic (Flags, Expr->Name, Expr->IVal);
1234 case E_LOC_REGISTER:
1235 /* Register variable */
1236 g_putstatic (Flags, Expr->Name, Expr->IVal);
1240 /* Value on the stack */
1241 g_putlocal (Flags, Expr->IVal, 0);
1245 /* The primary register (value is already there) */
1249 /* An expression in the primary register */
1250 g_putind (Flags, Expr->IVal);
1254 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1257 /* Assume that each one of the stores will invalidate CC */
1258 ED_MarkAsUntested (Expr);
1263 static void PreInc (ExprDesc* Expr)
1264 /* Handle the preincrement operators */
1269 /* Skip the operator token */
1272 /* Evaluate the expression and check that it is an lvalue */
1274 if (!ED_IsLVal (Expr)) {
1275 Error ("Invalid lvalue");
1279 /* We cannot modify const values */
1280 if (IsQualConst (Expr->Type)) {
1281 Error ("Increment of read-only variable");
1284 /* Get the data type */
1285 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1287 /* Get the increment value in bytes */
1288 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1290 /* Check the location of the data */
1291 switch (ED_GetLoc (Expr)) {
1294 /* Absolute: numeric address or const */
1295 g_addeqstatic (Flags, Expr->IVal, 0, Val);
1299 /* Global variable */
1300 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1305 /* Static variable or literal in the literal pool */
1306 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1309 case E_LOC_REGISTER:
1310 /* Register variable */
1311 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1315 /* Value on the stack */
1316 g_addeqlocal (Flags, Expr->IVal, Val);
1320 /* The primary register */
1325 /* An expression in the primary register */
1326 g_addeqind (Flags, Expr->IVal, Val);
1330 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1333 /* Result is an expression, no reference */
1334 ED_MakeRValExpr (Expr);
1339 static void PreDec (ExprDesc* Expr)
1340 /* Handle the predecrement operators */
1345 /* Skip the operator token */
1348 /* Evaluate the expression and check that it is an lvalue */
1350 if (!ED_IsLVal (Expr)) {
1351 Error ("Invalid lvalue");
1355 /* We cannot modify const values */
1356 if (IsQualConst (Expr->Type)) {
1357 Error ("Decrement of read-only variable");
1360 /* Get the data type */
1361 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1363 /* Get the increment value in bytes */
1364 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1366 /* Check the location of the data */
1367 switch (ED_GetLoc (Expr)) {
1370 /* Absolute: numeric address or const */
1371 g_subeqstatic (Flags, Expr->IVal, 0, Val);
1375 /* Global variable */
1376 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1381 /* Static variable or literal in the literal pool */
1382 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1385 case E_LOC_REGISTER:
1386 /* Register variable */
1387 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1391 /* Value on the stack */
1392 g_subeqlocal (Flags, Expr->IVal, Val);
1396 /* The primary register */
1401 /* An expression in the primary register */
1402 g_subeqind (Flags, Expr->IVal, Val);
1406 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1409 /* Result is an expression, no reference */
1410 ED_MakeRValExpr (Expr);
1415 static void PostInc (ExprDesc* Expr)
1416 /* Handle the postincrement operator */
1422 /* The expression to increment must be an lvalue */
1423 if (!ED_IsLVal (Expr)) {
1424 Error ("Invalid lvalue");
1428 /* We cannot modify const values */
1429 if (IsQualConst (Expr->Type)) {
1430 Error ("Increment of read-only variable");
1433 /* Get the data type */
1434 Flags = TypeOf (Expr->Type);
1436 /* Push the address if needed */
1439 /* Fetch the value and save it (since it's the result of the expression) */
1440 LoadExpr (CF_NONE, Expr);
1441 g_save (Flags | CF_FORCECHAR);
1443 /* If we have a pointer expression, increment by the size of the type */
1444 if (IsTypePtr (Expr->Type)) {
1445 g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1447 g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1450 /* Store the result back */
1453 /* Restore the original value in the primary register */
1454 g_restore (Flags | CF_FORCECHAR);
1456 /* The result is always an expression, no reference */
1457 ED_MakeRValExpr (Expr);
1462 static void PostDec (ExprDesc* Expr)
1463 /* Handle the postdecrement operator */
1469 /* The expression to increment must be an lvalue */
1470 if (!ED_IsLVal (Expr)) {
1471 Error ("Invalid lvalue");
1475 /* We cannot modify const values */
1476 if (IsQualConst (Expr->Type)) {
1477 Error ("Decrement of read-only variable");
1480 /* Get the data type */
1481 Flags = TypeOf (Expr->Type);
1483 /* Push the address if needed */
1486 /* Fetch the value and save it (since it's the result of the expression) */
1487 LoadExpr (CF_NONE, Expr);
1488 g_save (Flags | CF_FORCECHAR);
1490 /* If we have a pointer expression, increment by the size of the type */
1491 if (IsTypePtr (Expr->Type)) {
1492 g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1494 g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1497 /* Store the result back */
1500 /* Restore the original value in the primary register */
1501 g_restore (Flags | CF_FORCECHAR);
1503 /* The result is always an expression, no reference */
1504 ED_MakeRValExpr (Expr);
1509 static void UnaryOp (ExprDesc* Expr)
1510 /* Handle unary -/+ and ~ */
1514 /* Remember the operator token and skip it */
1515 token_t Tok = CurTok.Tok;
1518 /* Get the expression */
1521 /* We can only handle integer types */
1522 if (!IsClassInt (Expr->Type)) {
1523 Error ("Argument must have integer type");
1524 ED_MakeConstAbsInt (Expr, 1);
1527 /* Check for a constant expression */
1528 if (ED_IsConstAbs (Expr)) {
1529 /* Value is constant */
1531 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1532 case TOK_PLUS: break;
1533 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1534 default: Internal ("Unexpected token: %d", Tok);
1537 /* Value is not constant */
1538 LoadExpr (CF_NONE, Expr);
1540 /* Get the type of the expression */
1541 Flags = TypeOf (Expr->Type);
1543 /* Handle the operation */
1545 case TOK_MINUS: g_neg (Flags); break;
1546 case TOK_PLUS: break;
1547 case TOK_COMP: g_com (Flags); break;
1548 default: Internal ("Unexpected token: %d", Tok);
1551 /* The result is a rvalue in the primary */
1552 ED_MakeRValExpr (Expr);
1558 void hie10 (ExprDesc* Expr)
1559 /* Handle ++, --, !, unary - etc. */
1563 switch (CurTok.Tok) {
1581 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1582 /* Constant expression */
1583 Expr->IVal = !Expr->IVal;
1585 g_bneg (TypeOf (Expr->Type));
1586 ED_MakeRValExpr (Expr);
1587 ED_TestDone (Expr); /* bneg will set cc */
1593 ExprWithCheck (hie10, Expr);
1594 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1595 /* Not a const, load it into the primary and make it a
1598 LoadExpr (CF_NONE, Expr);
1599 ED_MakeRValExpr (Expr);
1601 /* If the expression is already a pointer to function, the
1602 * additional dereferencing operator must be ignored.
1604 if (IsTypeFuncPtr (Expr->Type)) {
1605 /* Expression not storable */
1608 if (IsClassPtr (Expr->Type)) {
1609 Expr->Type = Indirect (Expr->Type);
1611 Error ("Illegal indirection");
1613 /* The * operator yields an lvalue */
1620 ExprWithCheck (hie10, Expr);
1621 /* The & operator may be applied to any lvalue, and it may be
1622 * applied to functions, even if they're no lvalues.
1624 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1625 Error ("Illegal address");
1627 if (ED_IsBitField (Expr)) {
1628 Error ("Cannot take address of bit-field");
1629 /* Do it anyway, just to avoid further warnings */
1630 Expr->Flags &= ~E_BITFIELD;
1632 Expr->Type = PointerTo (Expr->Type);
1633 /* The & operator yields an rvalue */
1640 if (TypeSpecAhead ()) {
1643 Size = CheckedSizeOf (ParseType (T));
1646 /* Remember the output queue pointer */
1650 Size = CheckedSizeOf (Expr->Type);
1651 /* Remove any generated code */
1654 ED_MakeConstAbs (Expr, Size, type_size_t);
1655 ED_MarkAsUntested (Expr);
1659 if (TypeSpecAhead ()) {
1669 /* Handle post increment */
1670 switch (CurTok.Tok) {
1671 case TOK_INC: PostInc (Expr); break;
1672 case TOK_DEC: PostDec (Expr); break;
1683 static void hie_internal (const GenDesc* Ops, /* List of generators */
1685 void (*hienext) (ExprDesc*),
1687 /* Helper function */
1693 token_t Tok; /* The operator token */
1694 unsigned ltype, type;
1695 int rconst; /* Operand is a constant */
1701 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1703 /* Tell the caller that we handled it's ops */
1706 /* All operators that call this function expect an int on the lhs */
1707 if (!IsClassInt (Expr->Type)) {
1708 Error ("Integer expression expected");
1709 /* To avoid further errors, make Expr a valid int expression */
1710 ED_MakeConstAbsInt (Expr, 1);
1713 /* Remember the operator token, then skip it */
1717 /* Get the lhs on stack */
1718 GetCodePos (&Mark1);
1719 ltype = TypeOf (Expr->Type);
1720 if (ED_IsConstAbs (Expr)) {
1721 /* Constant value */
1722 GetCodePos (&Mark2);
1723 g_push (ltype | CF_CONST, Expr->IVal);
1725 /* Value not constant */
1726 LoadExpr (CF_NONE, Expr);
1727 GetCodePos (&Mark2);
1731 /* Get the right hand side */
1732 MarkedExprWithCheck (hienext, &Expr2);
1734 /* Check for a constant expression */
1735 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1737 /* Not constant, load into the primary */
1738 LoadExpr (CF_NONE, &Expr2);
1741 /* Check the type of the rhs */
1742 if (!IsClassInt (Expr2.Type)) {
1743 Error ("Integer expression expected");
1746 /* Check for const operands */
1747 if (ED_IsConstAbs (Expr) && rconst) {
1749 /* Both operands are constant, remove the generated code */
1750 RemoveCode (&Mark1);
1752 /* Get the type of the result */
1753 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1755 /* Handle the op differently for signed and unsigned types */
1756 if (IsSignSigned (Expr->Type)) {
1758 /* Evaluate the result for signed operands */
1759 signed long Val1 = Expr->IVal;
1760 signed long Val2 = Expr2.IVal;
1763 Expr->IVal = (Val1 | Val2);
1766 Expr->IVal = (Val1 ^ Val2);
1769 Expr->IVal = (Val1 & Val2);
1772 Expr->IVal = (Val1 * Val2);
1776 Error ("Division by zero");
1777 Expr->IVal = 0x7FFFFFFF;
1779 Expr->IVal = (Val1 / Val2);
1784 Error ("Modulo operation with zero");
1787 Expr->IVal = (Val1 % Val2);
1791 Internal ("hie_internal: got token 0x%X\n", Tok);
1795 /* Evaluate the result for unsigned operands */
1796 unsigned long Val1 = Expr->IVal;
1797 unsigned long Val2 = Expr2.IVal;
1800 Expr->IVal = (Val1 | Val2);
1803 Expr->IVal = (Val1 ^ Val2);
1806 Expr->IVal = (Val1 & Val2);
1809 Expr->IVal = (Val1 * Val2);
1813 Error ("Division by zero");
1814 Expr->IVal = 0xFFFFFFFF;
1816 Expr->IVal = (Val1 / Val2);
1821 Error ("Modulo operation with zero");
1824 Expr->IVal = (Val1 % Val2);
1828 Internal ("hie_internal: got token 0x%X\n", Tok);
1834 /* If the right hand side is constant, and the generator function
1835 * expects the lhs in the primary, remove the push of the primary
1838 unsigned rtype = TypeOf (Expr2.Type);
1841 /* Second value is constant - check for div */
1844 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1845 Error ("Division by zero");
1846 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1847 Error ("Modulo operation with zero");
1849 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1850 RemoveCode (&Mark2);
1851 ltype |= CF_REG; /* Value is in register */
1855 /* Determine the type of the operation result. */
1856 type |= g_typeadjust (ltype, rtype);
1857 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1860 Gen->Func (type, Expr2.IVal);
1862 /* We have a rvalue in the primary now */
1863 ED_MakeRValExpr (Expr);
1870 static void hie_compare (const GenDesc* Ops, /* List of generators */
1872 void (*hienext) (ExprDesc*))
1873 /* Helper function for the compare operators */
1879 token_t Tok; /* The operator token */
1881 int rconst; /* Operand is a constant */
1886 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1888 /* Remember the operator token, then skip it */
1892 /* Get the lhs on stack */
1893 GetCodePos (&Mark1);
1894 ltype = TypeOf (Expr->Type);
1895 if (ED_IsConstAbs (Expr)) {
1896 /* Constant value */
1897 GetCodePos (&Mark2);
1898 g_push (ltype | CF_CONST, Expr->IVal);
1900 /* Value not constant */
1901 LoadExpr (CF_NONE, Expr);
1902 GetCodePos (&Mark2);
1906 /* Get the right hand side */
1907 MarkedExprWithCheck (hienext, &Expr2);
1909 /* Check for a constant expression */
1910 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1912 /* Not constant, load into the primary */
1913 LoadExpr (CF_NONE, &Expr2);
1916 /* Make sure, the types are compatible */
1917 if (IsClassInt (Expr->Type)) {
1918 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1919 Error ("Incompatible types");
1921 } else if (IsClassPtr (Expr->Type)) {
1922 if (IsClassPtr (Expr2.Type)) {
1923 /* Both pointers are allowed in comparison if they point to
1924 * the same type, or if one of them is a void pointer.
1926 Type* left = Indirect (Expr->Type);
1927 Type* right = Indirect (Expr2.Type);
1928 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
1929 /* Incomatible pointers */
1930 Error ("Incompatible types");
1932 } else if (!ED_IsNullPtr (&Expr2)) {
1933 Error ("Incompatible types");
1937 /* Check for const operands */
1938 if (ED_IsConstAbs (Expr) && rconst) {
1940 /* If the result is constant, this is suspicious when not in
1941 * preprocessor mode.
1943 if (!Preprocessing) {
1944 Warning ("Result of comparison is constant");
1947 /* Both operands are constant, remove the generated code */
1948 RemoveCode (&Mark1);
1950 /* Determine if this is a signed or unsigned compare */
1951 if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
1952 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
1954 /* Evaluate the result for signed operands */
1955 signed long Val1 = Expr->IVal;
1956 signed long Val2 = Expr2.IVal;
1958 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
1959 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
1960 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
1961 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
1962 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
1963 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
1964 default: Internal ("hie_compare: got token 0x%X\n", Tok);
1969 /* Evaluate the result for unsigned operands */
1970 unsigned long Val1 = Expr->IVal;
1971 unsigned long Val2 = Expr2.IVal;
1973 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
1974 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
1975 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
1976 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
1977 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
1978 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
1979 default: Internal ("hie_compare: got token 0x%X\n", Tok);
1985 /* If the right hand side is constant, and the generator function
1986 * expects the lhs in the primary, remove the push of the primary
1992 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1993 RemoveCode (&Mark2);
1994 ltype |= CF_REG; /* Value is in register */
1998 /* Determine the type of the operation result. If the left
1999 * operand is of type char and the right is a constant, or
2000 * if both operands are of type char, we will encode the
2001 * operation as char operation. Otherwise the default
2002 * promotions are used.
2004 if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
2006 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
2007 flags |= CF_UNSIGNED;
2010 flags |= CF_FORCECHAR;
2013 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2014 flags |= g_typeadjust (ltype, rtype);
2018 Gen->Func (flags, Expr2.IVal);
2020 /* The result is an rvalue in the primary */
2021 ED_MakeRValExpr (Expr);
2024 /* Result type is always int */
2025 Expr->Type = type_int;
2027 /* Condition codes are set */
2034 static void hie9 (ExprDesc *Expr)
2035 /* Process * and / operators. */
2037 static const GenDesc hie9_ops[] = {
2038 { TOK_STAR, GEN_NOPUSH, g_mul },
2039 { TOK_DIV, GEN_NOPUSH, g_div },
2040 { TOK_MOD, GEN_NOPUSH, g_mod },
2041 { TOK_INVALID, 0, 0 }
2045 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2050 static void parseadd (ExprDesc* Expr)
2051 /* Parse an expression with the binary plus operator. Expr contains the
2052 * unprocessed left hand side of the expression and will contain the
2053 * result of the expression on return.
2057 unsigned flags; /* Operation flags */
2058 CodeMark Mark; /* Remember code position */
2059 Type* lhst; /* Type of left hand side */
2060 Type* rhst; /* Type of right hand side */
2063 /* Skip the PLUS token */
2066 /* Get the left hand side type, initialize operation flags */
2070 /* Check for constness on both sides */
2071 if (ED_IsConst (Expr)) {
2073 /* The left hand side is a constant of some sort. Good. Get rhs */
2075 if (ED_IsConstAbs (&Expr2)) {
2077 /* Right hand side is a constant numeric value. Get the rhs type */
2080 /* Both expressions are constants. Check for pointer arithmetic */
2081 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2082 /* Left is pointer, right is int, must scale rhs */
2083 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2084 /* Result type is a pointer */
2085 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2086 /* Left is int, right is pointer, must scale lhs */
2087 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2088 /* Result type is a pointer */
2089 Expr->Type = Expr2.Type;
2090 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2091 /* Integer addition */
2092 Expr->IVal += Expr2.IVal;
2093 typeadjust (Expr, &Expr2, 1);
2096 Error ("Invalid operands for binary operator `+'");
2101 /* lhs is a constant and rhs is not constant. Load rhs into
2104 LoadExpr (CF_NONE, &Expr2);
2106 /* Beware: The check above (for lhs) lets not only pass numeric
2107 * constants, but also constant addresses (labels), maybe even
2108 * with an offset. We have to check for that here.
2111 /* First, get the rhs type. */
2115 if (ED_IsLocAbs (Expr)) {
2116 /* A numerical constant */
2119 /* Constant address label */
2120 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2123 /* Check for pointer arithmetic */
2124 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2125 /* Left is pointer, right is int, must scale rhs */
2126 g_scale (CF_INT, CheckedPSizeOf (lhst));
2127 /* Operate on pointers, result type is a pointer */
2129 /* Generate the code for the add */
2130 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2131 /* Numeric constant */
2132 g_inc (flags, Expr->IVal);
2134 /* Constant address */
2135 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2137 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2139 /* Left is int, right is pointer, must scale lhs. */
2140 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2142 /* Operate on pointers, result type is a pointer */
2144 Expr->Type = Expr2.Type;
2146 /* Since we do already have rhs in the primary, if lhs is
2147 * not a numeric constant, and the scale factor is not one
2148 * (no scaling), we must take the long way over the stack.
2150 if (ED_IsLocAbs (Expr)) {
2151 /* Numeric constant, scale lhs */
2152 Expr->IVal *= ScaleFactor;
2153 /* Generate the code for the add */
2154 g_inc (flags, Expr->IVal);
2155 } else if (ScaleFactor == 1) {
2156 /* Constant address but no need to scale */
2157 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2159 /* Constant address that must be scaled */
2160 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2161 g_getimmed (flags, Expr->Name, Expr->IVal);
2162 g_scale (CF_PTR, ScaleFactor);
2165 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2166 /* Integer addition */
2167 flags |= typeadjust (Expr, &Expr2, 1);
2168 /* Generate the code for the add */
2169 if (ED_IsLocAbs (Expr)) {
2170 /* Numeric constant */
2171 g_inc (flags, Expr->IVal);
2173 /* Constant address */
2174 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2178 Error ("Invalid operands for binary operator `+'");
2182 /* Result is a rvalue in primary register */
2183 ED_MakeRValExpr (Expr);
2188 /* Left hand side is not constant. Get the value onto the stack. */
2189 LoadExpr (CF_NONE, Expr); /* --> primary register */
2191 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2193 /* Evaluate the rhs */
2194 MarkedExprWithCheck (hie9, &Expr2);
2196 /* Check for a constant rhs expression */
2197 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2199 /* Right hand side is a constant. Get the rhs type */
2202 /* Remove pushed value from stack */
2205 /* Check for pointer arithmetic */
2206 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2207 /* Left is pointer, right is int, must scale rhs */
2208 Expr2.IVal *= CheckedPSizeOf (lhst);
2209 /* Operate on pointers, result type is a pointer */
2211 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2212 /* Left is int, right is pointer, must scale lhs (ptr only) */
2213 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2214 /* Operate on pointers, result type is a pointer */
2216 Expr->Type = Expr2.Type;
2217 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2218 /* Integer addition */
2219 flags = typeadjust (Expr, &Expr2, 1);
2222 Error ("Invalid operands for binary operator `+'");
2226 /* Generate code for the add */
2227 g_inc (flags | CF_CONST, Expr2.IVal);
2231 /* Not constant, load into the primary */
2232 LoadExpr (CF_NONE, &Expr2);
2234 /* lhs and rhs are not constant. Get the rhs type. */
2237 /* Check for pointer arithmetic */
2238 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2239 /* Left is pointer, right is int, must scale rhs */
2240 g_scale (CF_INT, CheckedPSizeOf (lhst));
2241 /* Operate on pointers, result type is a pointer */
2243 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2244 /* Left is int, right is pointer, must scale lhs */
2245 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2246 g_swap (CF_INT); /* Swap TOS and primary */
2247 g_scale (CF_INT, CheckedPSizeOf (rhst));
2248 /* Operate on pointers, result type is a pointer */
2250 Expr->Type = Expr2.Type;
2251 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2252 /* Integer addition. Note: Result is never constant.
2253 * Problem here is that typeadjust does not know if the
2254 * variable is an rvalue or lvalue, so if both operands
2255 * are dereferenced constant numeric addresses, typeadjust
2256 * thinks the operation works on constants. Removing
2257 * CF_CONST here means handling the symptoms, however, the
2258 * whole parser is such a mess that I fear to break anything
2259 * when trying to apply another solution.
2261 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2264 Error ("Invalid operands for binary operator `+'");
2268 /* Generate code for the add */
2273 /* Result is a rvalue in primary register */
2274 ED_MakeRValExpr (Expr);
2277 /* Condition codes not set */
2278 ED_MarkAsUntested (Expr);
2284 static void parsesub (ExprDesc* Expr)
2285 /* Parse an expression with the binary minus operator. Expr contains the
2286 * unprocessed left hand side of the expression and will contain the
2287 * result of the expression on return.
2291 unsigned flags; /* Operation flags */
2292 Type* lhst; /* Type of left hand side */
2293 Type* rhst; /* Type of right hand side */
2294 CodeMark Mark1; /* Save position of output queue */
2295 CodeMark Mark2; /* Another position in the queue */
2296 int rscale; /* Scale factor for the result */
2299 /* Skip the MINUS token */
2302 /* Get the left hand side type, initialize operation flags */
2304 rscale = 1; /* Scale by 1, that is, don't scale */
2306 /* Remember the output queue position, then bring the value onto the stack */
2307 GetCodePos (&Mark1);
2308 LoadExpr (CF_NONE, Expr); /* --> primary register */
2309 GetCodePos (&Mark2);
2310 g_push (TypeOf (lhst), 0); /* --> stack */
2312 /* Parse the right hand side */
2313 MarkedExprWithCheck (hie9, &Expr2);
2315 /* Check for a constant rhs expression */
2316 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2318 /* The right hand side is constant. Get the rhs type. */
2321 /* Check left hand side */
2322 if (ED_IsConstAbs (Expr)) {
2324 /* Both sides are constant, remove generated code */
2325 RemoveCode (&Mark1);
2327 /* Check for pointer arithmetic */
2328 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2329 /* Left is pointer, right is int, must scale rhs */
2330 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2331 /* Operate on pointers, result type is a pointer */
2332 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2333 /* Left is pointer, right is pointer, must scale result */
2334 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2335 Error ("Incompatible pointer types");
2337 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2338 CheckedPSizeOf (lhst);
2340 /* Operate on pointers, result type is an integer */
2341 Expr->Type = type_int;
2342 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2343 /* Integer subtraction */
2344 typeadjust (Expr, &Expr2, 1);
2345 Expr->IVal -= Expr2.IVal;
2348 Error ("Invalid operands for binary operator `-'");
2351 /* Result is constant, condition codes not set */
2352 ED_MarkAsUntested (Expr);
2356 /* Left hand side is not constant, right hand side is.
2357 * Remove pushed value from stack.
2359 RemoveCode (&Mark2);
2361 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2362 /* Left is pointer, right is int, must scale rhs */
2363 Expr2.IVal *= CheckedPSizeOf (lhst);
2364 /* Operate on pointers, result type is a pointer */
2366 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2367 /* Left is pointer, right is pointer, must scale result */
2368 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2369 Error ("Incompatible pointer types");
2371 rscale = CheckedPSizeOf (lhst);
2373 /* Operate on pointers, result type is an integer */
2375 Expr->Type = type_int;
2376 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2377 /* Integer subtraction */
2378 flags = typeadjust (Expr, &Expr2, 1);
2381 Error ("Invalid operands for binary operator `-'");
2385 /* Do the subtraction */
2386 g_dec (flags | CF_CONST, Expr2.IVal);
2388 /* If this was a pointer subtraction, we must scale the result */
2390 g_scale (flags, -rscale);
2393 /* Result is a rvalue in the primary register */
2394 ED_MakeRValExpr (Expr);
2395 ED_MarkAsUntested (Expr);
2401 /* Not constant, load into the primary */
2402 LoadExpr (CF_NONE, &Expr2);
2404 /* Right hand side is not constant. Get the rhs type. */
2407 /* Check for pointer arithmetic */
2408 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2409 /* Left is pointer, right is int, must scale rhs */
2410 g_scale (CF_INT, CheckedPSizeOf (lhst));
2411 /* Operate on pointers, result type is a pointer */
2413 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2414 /* Left is pointer, right is pointer, must scale result */
2415 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2416 Error ("Incompatible pointer types");
2418 rscale = CheckedPSizeOf (lhst);
2420 /* Operate on pointers, result type is an integer */
2422 Expr->Type = type_int;
2423 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2424 /* Integer subtraction. If the left hand side descriptor says that
2425 * the lhs is const, we have to remove this mark, since this is no
2426 * longer true, lhs is on stack instead.
2428 if (ED_IsLocAbs (Expr)) {
2429 ED_MakeRValExpr (Expr);
2431 /* Adjust operand types */
2432 flags = typeadjust (Expr, &Expr2, 0);
2435 Error ("Invalid operands for binary operator `-'");
2439 /* Generate code for the sub (the & is a hack here) */
2440 g_sub (flags & ~CF_CONST, 0);
2442 /* If this was a pointer subtraction, we must scale the result */
2444 g_scale (flags, -rscale);
2447 /* Result is a rvalue in the primary register */
2448 ED_MakeRValExpr (Expr);
2449 ED_MarkAsUntested (Expr);
2455 void hie8 (ExprDesc* Expr)
2456 /* Process + and - binary operators. */
2459 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2460 if (CurTok.Tok == TOK_PLUS) {
2470 static void hie6 (ExprDesc* Expr)
2471 /* Handle greater-than type comparators */
2473 static const GenDesc hie6_ops [] = {
2474 { TOK_LT, GEN_NOPUSH, g_lt },
2475 { TOK_LE, GEN_NOPUSH, g_le },
2476 { TOK_GE, GEN_NOPUSH, g_ge },
2477 { TOK_GT, GEN_NOPUSH, g_gt },
2478 { TOK_INVALID, 0, 0 }
2480 hie_compare (hie6_ops, Expr, ShiftExpr);
2485 static void hie5 (ExprDesc* Expr)
2486 /* Handle == and != */
2488 static const GenDesc hie5_ops[] = {
2489 { TOK_EQ, GEN_NOPUSH, g_eq },
2490 { TOK_NE, GEN_NOPUSH, g_ne },
2491 { TOK_INVALID, 0, 0 }
2493 hie_compare (hie5_ops, Expr, hie6);
2498 static void hie4 (ExprDesc* Expr)
2499 /* Handle & (bitwise and) */
2501 static const GenDesc hie4_ops[] = {
2502 { TOK_AND, GEN_NOPUSH, g_and },
2503 { TOK_INVALID, 0, 0 }
2507 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2512 static void hie3 (ExprDesc* Expr)
2513 /* Handle ^ (bitwise exclusive or) */
2515 static const GenDesc hie3_ops[] = {
2516 { TOK_XOR, GEN_NOPUSH, g_xor },
2517 { TOK_INVALID, 0, 0 }
2521 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2526 static void hie2 (ExprDesc* Expr)
2527 /* Handle | (bitwise or) */
2529 static const GenDesc hie2_ops[] = {
2530 { TOK_OR, GEN_NOPUSH, g_or },
2531 { TOK_INVALID, 0, 0 }
2535 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2540 static void hieAndPP (ExprDesc* Expr)
2541 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2542 * called recursively from the preprocessor.
2547 ConstAbsIntExpr (hie2, Expr);
2548 while (CurTok.Tok == TOK_BOOL_AND) {
2554 ConstAbsIntExpr (hie2, &Expr2);
2556 /* Combine the two */
2557 Expr->IVal = (Expr->IVal && Expr2.IVal);
2563 static void hieOrPP (ExprDesc *Expr)
2564 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2565 * called recursively from the preprocessor.
2570 ConstAbsIntExpr (hieAndPP, Expr);
2571 while (CurTok.Tok == TOK_BOOL_OR) {
2577 ConstAbsIntExpr (hieAndPP, &Expr2);
2579 /* Combine the two */
2580 Expr->IVal = (Expr->IVal || Expr2.IVal);
2586 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2587 /* Process "exp && exp" */
2593 if (CurTok.Tok == TOK_BOOL_AND) {
2595 /* Tell our caller that we're evaluating a boolean */
2598 /* Get a label that we will use for false expressions */
2599 FalseLab = GetLocalLabel ();
2601 /* If the expr hasn't set condition codes, set the force-test flag */
2602 if (!ED_IsTested (Expr)) {
2603 ED_MarkForTest (Expr);
2606 /* Load the value */
2607 LoadExpr (CF_FORCECHAR, Expr);
2609 /* Generate the jump */
2610 g_falsejump (CF_NONE, FalseLab);
2612 /* Parse more boolean and's */
2613 while (CurTok.Tok == TOK_BOOL_AND) {
2620 if (!ED_IsTested (&Expr2)) {
2621 ED_MarkForTest (&Expr2);
2623 LoadExpr (CF_FORCECHAR, &Expr2);
2625 /* Do short circuit evaluation */
2626 if (CurTok.Tok == TOK_BOOL_AND) {
2627 g_falsejump (CF_NONE, FalseLab);
2629 /* Last expression - will evaluate to true */
2630 g_truejump (CF_NONE, TrueLab);
2634 /* Define the false jump label here */
2635 g_defcodelabel (FalseLab);
2637 /* The result is an rvalue in primary */
2638 ED_MakeRValExpr (Expr);
2639 ED_TestDone (Expr); /* Condition codes are set */
2645 static void hieOr (ExprDesc *Expr)
2646 /* Process "exp || exp". */
2649 int BoolOp = 0; /* Did we have a boolean op? */
2650 int AndOp; /* Did we have a && operation? */
2651 unsigned TrueLab; /* Jump to this label if true */
2655 TrueLab = GetLocalLabel ();
2657 /* Call the next level parser */
2658 hieAnd (Expr, TrueLab, &BoolOp);
2660 /* Any boolean or's? */
2661 if (CurTok.Tok == TOK_BOOL_OR) {
2663 /* If the expr hasn't set condition codes, set the force-test flag */
2664 if (!ED_IsTested (Expr)) {
2665 ED_MarkForTest (Expr);
2668 /* Get first expr */
2669 LoadExpr (CF_FORCECHAR, Expr);
2671 /* For each expression jump to TrueLab if true. Beware: If we
2672 * had && operators, the jump is already in place!
2675 g_truejump (CF_NONE, TrueLab);
2678 /* Remember that we had a boolean op */
2681 /* while there's more expr */
2682 while (CurTok.Tok == TOK_BOOL_OR) {
2689 hieAnd (&Expr2, TrueLab, &AndOp);
2690 if (!ED_IsTested (&Expr2)) {
2691 ED_MarkForTest (&Expr2);
2693 LoadExpr (CF_FORCECHAR, &Expr2);
2695 /* If there is more to come, add shortcut boolean eval. */
2696 g_truejump (CF_NONE, TrueLab);
2700 /* The result is an rvalue in primary */
2701 ED_MakeRValExpr (Expr);
2702 ED_TestDone (Expr); /* Condition codes are set */
2705 /* If we really had boolean ops, generate the end sequence */
2707 DoneLab = GetLocalLabel ();
2708 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2709 g_falsejump (CF_NONE, DoneLab);
2710 g_defcodelabel (TrueLab);
2711 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2712 g_defcodelabel (DoneLab);
2718 static void hieQuest (ExprDesc* Expr)
2719 /* Parse the ternary operator */
2723 CodeMark TrueCodeEnd;
2724 ExprDesc Expr2; /* Expression 2 */
2725 ExprDesc Expr3; /* Expression 3 */
2726 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
2727 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
2728 Type* ResultType; /* Type of result */
2731 /* Call the lower level eval routine */
2732 if (Preprocessing) {
2738 /* Check if it's a ternary expression */
2739 if (CurTok.Tok == TOK_QUEST) {
2741 if (!ED_IsTested (Expr)) {
2742 /* Condition codes not set, request a test */
2743 ED_MarkForTest (Expr);
2745 LoadExpr (CF_NONE, Expr);
2746 FalseLab = GetLocalLabel ();
2747 g_falsejump (CF_NONE, FalseLab);
2749 /* Parse second expression. Remember for later if it is a NULL pointer
2750 * expression, then load it into the primary.
2752 ExprWithCheck (hie1, &Expr2);
2753 Expr2IsNULL = ED_IsNullPtr (&Expr2);
2754 if (!IsTypeVoid (Expr2.Type)) {
2755 /* Load it into the primary */
2756 LoadExpr (CF_NONE, &Expr2);
2757 ED_MakeRValExpr (&Expr2);
2758 Expr2.Type = PtrConversion (Expr2.Type);
2761 /* Remember the current code position */
2762 GetCodePos (&TrueCodeEnd);
2764 /* Jump around the evaluation of the third expression */
2765 TrueLab = GetLocalLabel ();
2769 /* Jump here if the first expression was false */
2770 g_defcodelabel (FalseLab);
2772 /* Parse third expression. Remember for later if it is a NULL pointer
2773 * expression, then load it into the primary.
2775 ExprWithCheck (hie1, &Expr3);
2776 Expr3IsNULL = ED_IsNullPtr (&Expr3);
2777 if (!IsTypeVoid (Expr3.Type)) {
2778 /* Load it into the primary */
2779 LoadExpr (CF_NONE, &Expr3);
2780 ED_MakeRValExpr (&Expr3);
2781 Expr3.Type = PtrConversion (Expr3.Type);
2784 /* Check if any conversions are needed, if so, do them.
2785 * Conversion rules for ?: expression are:
2786 * - if both expressions are int expressions, default promotion
2787 * rules for ints apply.
2788 * - if both expressions are pointers of the same type, the
2789 * result of the expression is of this type.
2790 * - if one of the expressions is a pointer and the other is
2791 * a zero constant, the resulting type is that of the pointer
2793 * - if both expressions are void expressions, the result is of
2795 * - all other cases are flagged by an error.
2797 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2799 CodeMark CvtCodeStart;
2800 CodeMark CvtCodeEnd;
2803 /* Get common type */
2804 ResultType = promoteint (Expr2.Type, Expr3.Type);
2806 /* Convert the third expression to this type if needed */
2807 TypeConversion (&Expr3, ResultType);
2809 /* Emit conversion code for the second expression, but remember
2810 * where it starts end ends.
2812 GetCodePos (&CvtCodeStart);
2813 TypeConversion (&Expr2, ResultType);
2814 GetCodePos (&CvtCodeEnd);
2816 /* If we had conversion code, move it to the right place */
2817 if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
2818 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
2821 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2822 /* Must point to same type */
2823 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2824 Error ("Incompatible pointer types");
2826 /* Result has the common type */
2827 ResultType = Expr2.Type;
2828 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2829 /* Result type is pointer, no cast needed */
2830 ResultType = Expr2.Type;
2831 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2832 /* Result type is pointer, no cast needed */
2833 ResultType = Expr3.Type;
2834 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2835 /* Result type is void */
2836 ResultType = Expr3.Type;
2838 Error ("Incompatible types");
2839 ResultType = Expr2.Type; /* Doesn't matter here */
2842 /* Define the final label */
2843 g_defcodelabel (TrueLab);
2845 /* Setup the target expression */
2846 ED_MakeRValExpr (Expr);
2847 Expr->Type = ResultType;
2853 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
2854 /* Process "op=" operators. */
2861 /* op= can only be used with lvalues */
2862 if (!ED_IsLVal (Expr)) {
2863 Error ("Invalid lvalue in assignment");
2867 /* The left side must not be const qualified */
2868 if (IsQualConst (Expr->Type)) {
2869 Error ("Assignment to const");
2872 /* There must be an integer or pointer on the left side */
2873 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2874 Error ("Invalid left operand type");
2875 /* Continue. Wrong code will be generated, but the compiler won't
2876 * break, so this is the best error recovery.
2880 /* Skip the operator token */
2883 /* Determine the type of the lhs */
2884 flags = TypeOf (Expr->Type);
2885 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2887 /* Get the lhs address on stack (if needed) */
2890 /* Fetch the lhs into the primary register if needed */
2891 LoadExpr (CF_NONE, Expr);
2893 /* Bring the lhs on stack */
2897 /* Evaluate the rhs */
2898 MarkedExprWithCheck (hie1, &Expr2);
2900 /* The rhs must be an integer (or a float, but we don't support that yet */
2901 if (!IsClassInt (Expr2.Type)) {
2902 Error ("Invalid right operand for binary operator `%s'", Op);
2903 /* Continue. Wrong code will be generated, but the compiler won't
2904 * break, so this is the best error recovery.
2908 /* Check for a constant expression */
2909 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2910 /* The resulting value is a constant. If the generator has the NOPUSH
2911 * flag set, don't push the lhs.
2913 if (Gen->Flags & GEN_NOPUSH) {
2917 /* lhs is a pointer, scale rhs */
2918 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2921 /* If the lhs is character sized, the operation may be later done
2924 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2925 flags |= CF_FORCECHAR;
2928 /* Special handling for add and sub - some sort of a hack, but short code */
2929 if (Gen->Func == g_add) {
2930 g_inc (flags | CF_CONST, Expr2.IVal);
2931 } else if (Gen->Func == g_sub) {
2932 g_dec (flags | CF_CONST, Expr2.IVal);
2934 if (Expr2.IVal == 0) {
2935 /* Check for div by zero/mod by zero */
2936 if (Gen->Func == g_div) {
2937 Error ("Division by zero");
2938 } else if (Gen->Func == g_mod) {
2939 Error ("Modulo operation with zero");
2942 Gen->Func (flags | CF_CONST, Expr2.IVal);
2946 /* rhs is not constant. Load into the primary */
2947 LoadExpr (CF_NONE, &Expr2);
2949 /* lhs is a pointer, scale rhs */
2950 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2953 /* If the lhs is character sized, the operation may be later done
2956 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2957 flags |= CF_FORCECHAR;
2960 /* Adjust the types of the operands if needed */
2961 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2964 ED_MakeRValExpr (Expr);
2969 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
2970 /* Process the += and -= operators */
2978 /* We're currently only able to handle some adressing modes */
2979 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2980 /* Use generic routine */
2981 opeq (Gen, Expr, Op);
2985 /* We must have an lvalue */
2986 if (ED_IsRVal (Expr)) {
2987 Error ("Invalid lvalue in assignment");
2991 /* The left side must not be const qualified */
2992 if (IsQualConst (Expr->Type)) {
2993 Error ("Assignment to const");
2996 /* There must be an integer or pointer on the left side */
2997 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2998 Error ("Invalid left operand type");
2999 /* Continue. Wrong code will be generated, but the compiler won't
3000 * break, so this is the best error recovery.
3004 /* Skip the operator */
3007 /* Check if we have a pointer expression and must scale rhs */
3008 MustScale = IsTypePtr (Expr->Type);
3010 /* Initialize the code generator flags */
3014 /* Evaluate the rhs. We expect an integer here, since float is not
3018 if (!IsClassInt (Expr2.Type)) {
3019 Error ("Invalid right operand for binary operator `%s'", Op);
3020 /* Continue. Wrong code will be generated, but the compiler won't
3021 * break, so this is the best error recovery.
3024 if (ED_IsConstAbs (&Expr2)) {
3025 /* The resulting value is a constant. Scale it. */
3027 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3032 /* Not constant, load into the primary */
3033 LoadExpr (CF_NONE, &Expr2);
3035 /* lhs is a pointer, scale rhs */
3036 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3040 /* Setup the code generator flags */
3041 lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3042 rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3044 /* Convert the type of the lhs to that of the rhs */
3045 g_typecast (lflags, rflags);
3047 /* Output apropriate code depending on the location */
3048 switch (ED_GetLoc (Expr)) {
3051 /* Absolute: numeric address or const */
3052 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3053 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3055 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3060 /* Global variable */
3061 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3062 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3064 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3070 /* Static variable or literal in the literal pool */
3071 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3072 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3074 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3078 case E_LOC_REGISTER:
3079 /* Register variable */
3080 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3081 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3083 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3088 /* Value on the stack */
3089 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3090 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3092 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3097 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3100 /* Expression is a rvalue in the primary now */
3101 ED_MakeRValExpr (Expr);
3106 void hie1 (ExprDesc* Expr)
3107 /* Parse first level of expression hierarchy. */
3110 switch (CurTok.Tok) {
3116 case TOK_PLUS_ASSIGN:
3117 addsubeq (&GenPASGN, Expr, "+=");
3120 case TOK_MINUS_ASSIGN:
3121 addsubeq (&GenSASGN, Expr, "-=");
3124 case TOK_MUL_ASSIGN:
3125 opeq (&GenMASGN, Expr, "*=");
3128 case TOK_DIV_ASSIGN:
3129 opeq (&GenDASGN, Expr, "/=");
3132 case TOK_MOD_ASSIGN:
3133 opeq (&GenMOASGN, Expr, "%=");
3136 case TOK_SHL_ASSIGN:
3137 opeq (&GenSLASGN, Expr, "<<=");
3140 case TOK_SHR_ASSIGN:
3141 opeq (&GenSRASGN, Expr, ">>=");
3144 case TOK_AND_ASSIGN:
3145 opeq (&GenAASGN, Expr, "&=");
3148 case TOK_XOR_ASSIGN:
3149 opeq (&GenXOASGN, Expr, "^=");
3153 opeq (&GenOASGN, Expr, "|=");
3163 void hie0 (ExprDesc *Expr)
3164 /* Parse comma operator. */
3167 while (CurTok.Tok == TOK_COMMA) {
3175 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3176 /* Will evaluate an expression via the given function. If the result is a
3177 * constant, 0 is returned and the value is put in the Expr struct. If the
3178 * result is not constant, LoadExpr is called to bring the value into the
3179 * primary register and 1 is returned.
3183 ExprWithCheck (Func, Expr);
3185 /* Check for a constant expression */
3186 if (ED_IsConstAbs (Expr)) {
3187 /* Constant expression */
3190 /* Not constant, load into the primary */
3191 LoadExpr (Flags, Expr);
3198 void Expression0 (ExprDesc* Expr)
3199 /* Evaluate an expression via hie0 and put the result into the primary register */
3201 ExprWithCheck (hie0, Expr);
3202 LoadExpr (CF_NONE, Expr);
3207 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3208 /* Will evaluate an expression via the given function. If the result is not
3209 * a constant of some sort, a diagnostic will be printed, and the value is
3210 * replaced by a constant one to make sure there are no internal errors that
3211 * result from this input error.
3214 ExprWithCheck (Func, Expr);
3215 if (!ED_IsConst (Expr)) {
3216 Error ("Constant expression expected");
3217 /* To avoid any compiler errors, make the expression a valid const */
3218 ED_MakeConstAbsInt (Expr, 1);
3224 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3225 /* Will evaluate an expression via the given function. If the result is not
3226 * something that may be evaluated in a boolean context, a diagnostic will be
3227 * printed, and the value is replaced by a constant one to make sure there
3228 * are no internal errors that result from this input error.
3231 ExprWithCheck (Func, Expr);
3232 if (!ED_IsBool (Expr)) {
3233 Error ("Boolean expression expected");
3234 /* To avoid any compiler errors, make the expression a valid int */
3235 ED_MakeConstAbsInt (Expr, 1);
3241 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3242 /* Will evaluate an expression via the given function. If the result is not
3243 * a constant numeric integer value, a diagnostic will be printed, and the
3244 * value is replaced by a constant one to make sure there are no internal
3245 * errors that result from this input error.
3248 ExprWithCheck (Func, Expr);
3249 if (!ED_IsConstAbsInt (Expr)) {
3250 Error ("Constant integer expression expected");
3251 /* To avoid any compiler errors, make the expression a valid const */
3252 ED_MakeConstAbsInt (Expr, 1);