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) {
112 Error ("Code generation messed up: "
113 "StackPtr is %d, should be %d",
116 Internal ("Code generation messed up: "
117 "StackPtr is %d, should be %d",
125 void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
126 /* Call an expression function with checks and record start and end of the
132 ExprWithCheck (Func, Expr);
134 ED_SetCodeRange (Expr, &Start, &End);
139 static Type* promoteint (Type* lhst, Type* rhst)
140 /* In an expression with two ints, return the type of the result */
142 /* Rules for integer types:
143 * - If one of the values is a long, the result is long.
144 * - If one of the values is unsigned, the result is also unsigned.
145 * - Otherwise the result is an int.
147 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
148 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
154 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
164 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
165 /* Adjust the two values for a binary operation. lhs is expected on stack or
166 * to be constant, rhs is expected to be in the primary register or constant.
167 * The function will put the type of the result into lhs and return the
168 * code generator flags for the operation.
169 * If NoPush is given, it is assumed that the operation does not expect the lhs
170 * to be on stack, and that lhs is in a register instead.
171 * Beware: The function does only accept int types.
174 unsigned ltype, rtype;
177 /* Get the type strings */
178 Type* lhst = lhs->Type;
179 Type* rhst = rhs->Type;
181 /* Generate type adjustment code if needed */
182 ltype = TypeOf (lhst);
183 if (ED_IsLocAbs (lhs)) {
187 /* Value is in primary register*/
190 rtype = TypeOf (rhst);
191 if (ED_IsLocAbs (rhs)) {
194 flags = g_typeadjust (ltype, rtype);
196 /* Set the type of the result */
197 lhs->Type = promoteint (lhst, rhst);
199 /* Return the code generator flags */
205 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
206 /* Find a token in a generator table */
208 while (Table->Tok != TOK_INVALID) {
209 if (Table->Tok == Tok) {
219 static int TypeSpecAhead (void)
220 /* Return true if some sort of type is waiting (helper for cast and sizeof()
226 /* There's a type waiting if:
228 * We have an opening paren, and
229 * a. the next token is a type, or
230 * b. the next token is a type qualifier, or
231 * c. the next token is a typedef'd type
233 return CurTok.Tok == TOK_LPAREN && (
234 TokIsType (&NextTok) ||
235 TokIsTypeQual (&NextTok) ||
236 (NextTok.Tok == TOK_IDENT &&
237 (Entry = FindSym (NextTok.Ident)) != 0 &&
238 SymIsTypeDef (Entry)));
243 void PushAddr (const ExprDesc* Expr)
244 /* If the expression contains an address that was somehow evaluated,
245 * push this address on the stack. This is a helper function for all
246 * sorts of implicit or explicit assignment functions where the lvalue
247 * must be saved if it's not constant, before evaluating the rhs.
250 /* Get the address on stack if needed */
251 if (ED_IsLocExpr (Expr)) {
252 /* Push the address (always a pointer) */
259 static void WarnConstCompareResult (void)
260 /* If the result of a comparison is constant, this is suspicious when not in
264 if (!Preprocessing && IS_Get (&WarnConstComparison) != 0) {
265 Warning ("Result of comparison is constant");
271 /*****************************************************************************/
273 /*****************************************************************************/
277 static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall)
278 /* Parse a function parameter list and pass the parameters to the called
279 * function. Depending on several criteria this may be done by just pushing
280 * each parameter separately, or creating the parameter frame once and then
281 * storing into this frame.
282 * The function returns the size of the parameters pushed.
287 /* Initialize variables */
288 SymEntry* Param = 0; /* Keep gcc silent */
289 unsigned ParamSize = 0; /* Size of parameters pushed */
290 unsigned ParamCount = 0; /* Number of parameters pushed */
291 unsigned FrameSize = 0; /* Size of parameter frame */
292 unsigned FrameParams = 0; /* Number of params in frame */
293 int FrameOffs = 0; /* Offset into parameter frame */
294 int Ellipsis = 0; /* Function is variadic */
296 /* As an optimization, we may allocate the complete parameter frame at
297 * once instead of pushing each parameter as it comes. We may do that,
300 * - optimizations that increase code size are enabled (allocating the
301 * stack frame at once gives usually larger code).
302 * - we have more than one parameter to push (don't count the last param
303 * for __fastcall__ functions).
305 * The FrameSize variable will contain a value > 0 if storing into a frame
306 * (instead of pushing) is enabled.
309 if (IS_Get (&CodeSizeFactor) >= 200) {
311 /* Calculate the number and size of the parameters */
312 FrameParams = Func->ParamCount;
313 FrameSize = Func->ParamSize;
314 if (FrameParams > 0 && IsFastcall) {
315 /* Last parameter is not pushed */
316 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
320 /* Do we have more than one parameter in the frame? */
321 if (FrameParams > 1) {
322 /* Okeydokey, setup the frame */
323 FrameOffs = StackPtr;
325 StackPtr -= FrameSize;
327 /* Don't use a preallocated frame */
332 /* Parse the actual parameter list */
333 while (CurTok.Tok != TOK_RPAREN) {
337 /* Count arguments */
340 /* Fetch the pointer to the next argument, check for too many args */
341 if (ParamCount <= Func->ParamCount) {
342 /* Beware: If there are parameters with identical names, they
343 * cannot go into the same symbol table, which means that in this
344 * case of errorneous input, the number of nodes in the symbol
345 * table and ParamCount are NOT equal. We have to handle this case
346 * below to avoid segmentation violations. Since we know that this
347 * problem can only occur if there is more than one parameter,
348 * we will just use the last one.
350 if (ParamCount == 1) {
352 Param = Func->SymTab->SymHead;
353 } else if (Param->NextSym != 0) {
355 Param = Param->NextSym;
356 CHECK ((Param->Flags & SC_PARAM) != 0);
358 } else if (!Ellipsis) {
359 /* Too many arguments. Do we have an open param list? */
360 if ((Func->Flags & FD_VARIADIC) == 0) {
361 /* End of param list reached, no ellipsis */
362 Error ("Too many arguments in function call");
364 /* Assume an ellipsis even in case of errors to avoid an error
365 * message for each other argument.
370 /* Evaluate the parameter expression */
373 /* If we don't have an argument spec, accept anything, otherwise
374 * convert the actual argument to the type needed.
379 /* Convert the argument to the parameter type if needed */
380 TypeConversion (&Expr, Param->Type);
382 /* If we have a prototype, chars may be pushed as chars */
383 Flags |= CF_FORCECHAR;
387 /* No prototype available. Convert array to "pointer to first
388 * element", and function to "pointer to function".
390 Expr.Type = PtrConversion (Expr.Type);
394 /* Load the value into the primary if it is not already there */
395 LoadExpr (Flags, &Expr);
397 /* Use the type of the argument for the push */
398 Flags |= TypeOf (Expr.Type);
400 /* If this is a fastcall function, don't push the last argument */
401 if (ParamCount != Func->ParamCount || !IsFastcall) {
402 unsigned ArgSize = sizeofarg (Flags);
404 /* We have the space already allocated, store in the frame.
405 * Because of invalid type conversions (that have produced an
406 * error before), we can end up here with a non aligned stack
407 * frame. Since no output will be generated anyway, handle
408 * these cases gracefully instead of doing a CHECK.
410 if (FrameSize >= ArgSize) {
411 FrameSize -= ArgSize;
415 FrameOffs -= ArgSize;
417 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
419 /* Push the argument */
420 g_push (Flags, Expr.IVal);
423 /* Calculate total parameter size */
424 ParamSize += ArgSize;
427 /* Check for end of argument list */
428 if (CurTok.Tok != TOK_COMMA) {
434 /* Check if we had enough parameters */
435 if (ParamCount < Func->ParamCount) {
436 Error ("Too few arguments in function call");
439 /* The function returns the size of all parameters pushed onto the stack.
440 * However, if there are parameters missing (which is an error and was
441 * flagged by the compiler) AND a stack frame was preallocated above,
442 * we would loose track of the stackpointer and generate an internal error
443 * later. So we correct the value by the parameters that should have been
444 * pushed to avoid an internal compiler error. Since an error was
445 * generated before, no code will be output anyway.
447 return ParamSize + FrameSize;
452 static void FunctionCall (ExprDesc* Expr)
453 /* Perform a function call. */
455 FuncDesc* Func; /* Function descriptor */
456 int IsFuncPtr; /* Flag */
457 unsigned ParamSize; /* Number of parameter bytes */
459 int PtrOffs = 0; /* Offset of function pointer on stack */
460 int IsFastcall = 0; /* True if it's a fast call function */
461 int PtrOnStack = 0; /* True if a pointer copy is on stack */
463 /* Skip the left paren */
466 /* Get a pointer to the function descriptor from the type string */
467 Func = GetFuncDesc (Expr->Type);
469 /* Handle function pointers transparently */
470 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
473 /* Check wether it's a fastcall function that has parameters */
474 IsFastcall = IsQualFastcall (Expr->Type + 1) && (Func->ParamCount > 0);
476 /* Things may be difficult, depending on where the function pointer
477 * resides. If the function pointer is an expression of some sort
478 * (not a local or global variable), we have to evaluate this
479 * expression now and save the result for later. Since calls to
480 * function pointers may be nested, we must save it onto the stack.
481 * For fastcall functions we do also need to place a copy of the
482 * pointer on stack, since we cannot use a/x.
484 PtrOnStack = IsFastcall || !ED_IsConst (Expr);
487 /* Not a global or local variable, or a fastcall function. Load
488 * the pointer into the primary and mark it as an expression.
490 LoadExpr (CF_NONE, Expr);
491 ED_MakeRValExpr (Expr);
493 /* Remember the code position */
496 /* Push the pointer onto the stack and remember the offset */
502 /* Check function attributes */
503 if (Expr->Sym && SymHasAttr (Expr->Sym, atNoReturn)) {
504 /* For now, handle as if a return statement was encountered */
505 F_ReturnFound (CurrentFunc);
508 /* Check for known standard functions and inline them */
509 if (Expr->Name != 0) {
510 int StdFunc = FindStdFunc ((const char*) Expr->Name);
512 /* Inline this function */
513 HandleStdFunc (StdFunc, Func, Expr);
518 /* If we didn't inline the function, get fastcall info */
519 IsFastcall = IsQualFastcall (Expr->Type);
522 /* Parse the parameter list */
523 ParamSize = FunctionParamList (Func, IsFastcall);
525 /* We need the closing paren here */
528 /* Special handling for function pointers */
531 /* If the function is not a fastcall function, load the pointer to
532 * the function into the primary.
536 /* Not a fastcall function - we may use the primary */
538 /* If we have no parameters, the pointer is still in the
539 * primary. Remove the code to push it and correct the
542 if (ParamSize == 0) {
546 /* Load from the saved copy */
547 g_getlocal (CF_PTR, PtrOffs);
550 /* Load from original location */
551 LoadExpr (CF_NONE, Expr);
554 /* Call the function */
555 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
559 /* Fastcall function. We cannot use the primary for the function
560 * pointer and must therefore use an offset to the stack location.
561 * Since fastcall functions may never be variadic, we can use the
562 * index register for this purpose.
564 g_callind (CF_LOCAL, ParamSize, PtrOffs);
567 /* If we have a pointer on stack, remove it */
578 /* Normal function */
579 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
583 /* The function result is an rvalue in the primary register */
584 ED_MakeRValExpr (Expr);
585 Expr->Type = GetFuncReturn (Expr->Type);
590 static void Primary (ExprDesc* E)
591 /* This is the lowest level of the expression parser. */
595 /* Initialize fields in the expression stucture */
598 /* Character and integer constants. */
599 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
600 E->IVal = CurTok.IVal;
601 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
602 E->Type = CurTok.Type;
607 /* Floating point constant */
608 if (CurTok.Tok == TOK_FCONST) {
609 E->FVal = CurTok.FVal;
610 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
611 E->Type = CurTok.Type;
616 /* Process parenthesized subexpression by calling the whole parser
619 if (CurTok.Tok == TOK_LPAREN) {
626 /* If we run into an identifier in preprocessing mode, we assume that this
627 * is an undefined macro and replace it by a constant value of zero.
629 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
631 ED_MakeConstAbsInt (E, 0);
635 /* All others may only be used if the expression evaluation is not called
636 * recursively by the preprocessor.
639 /* Illegal expression in PP mode */
640 Error ("Preprocessor expression expected");
641 ED_MakeConstAbsInt (E, 1);
645 switch (CurTok.Tok) {
648 /* Identifier. Get a pointer to the symbol table entry */
649 Sym = E->Sym = FindSym (CurTok.Ident);
651 /* Is the symbol known? */
654 /* We found the symbol - skip the name token */
657 /* Check for illegal symbol types */
658 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
659 if (Sym->Flags & SC_TYPE) {
660 /* Cannot use type symbols */
661 Error ("Variable identifier expected");
662 /* Assume an int type to make E valid */
663 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
668 /* Mark the symbol as referenced */
669 Sym->Flags |= SC_REF;
671 /* The expression type is the symbol type */
674 /* Check for legal symbol types */
675 if ((Sym->Flags & SC_CONST) == SC_CONST) {
676 /* Enum or some other numeric constant */
677 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
678 E->IVal = Sym->V.ConstVal;
679 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
681 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
682 E->Name = (unsigned long) Sym->Name;
683 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
684 /* Local variable. If this is a parameter for a variadic
685 * function, we have to add some address calculations, and the
686 * address is not const.
688 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
689 /* Variadic parameter */
690 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
691 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
693 /* Normal parameter */
694 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
695 E->IVal = Sym->V.Offs;
697 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
698 /* Register variable, zero page based */
699 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
700 E->Name = Sym->V.R.RegOffs;
701 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
702 /* Static variable */
703 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
704 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
705 E->Name = (unsigned long) Sym->Name;
707 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
708 E->Name = Sym->V.Label;
711 /* Local static variable */
712 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
713 E->Name = Sym->V.Offs;
716 /* We've made all variables lvalues above. However, this is
717 * not always correct: An array is actually the address of its
718 * first element, which is a rvalue, and a function is a
719 * rvalue, too, because we cannot store anything in a function.
720 * So fix the flags depending on the type.
722 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
728 /* We did not find the symbol. Remember the name, then skip it */
730 strcpy (Ident, CurTok.Ident);
733 /* IDENT is either an auto-declared function or an undefined variable. */
734 if (CurTok.Tok == TOK_LPAREN) {
735 /* C99 doesn't allow calls to undefined functions, so
736 * generate an error and otherwise a warning. Declare a
737 * function returning int. For that purpose, prepare a
738 * function signature for a function having an empty param
739 * list and returning int.
741 if (IS_Get (&Standard) >= STD_C99) {
742 Error ("Call to undefined function `%s'", Ident);
744 Warning ("Call to undefined function `%s'", Ident);
746 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
748 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
749 E->Name = (unsigned long) Sym->Name;
751 /* Undeclared Variable */
752 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
753 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
755 Error ("Undefined symbol: `%s'", Ident);
764 E->LVal = UseLiteral (CurTok.SVal);
765 E->Type = GetCharArrayType (GetLiteralSize (CurTok.SVal));
766 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
768 E->Name = GetLiteralLabel (CurTok.SVal);
775 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
780 /* Register pseudo variable */
781 E->Type = type_uchar;
782 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
787 /* Register pseudo variable */
789 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
794 /* Register pseudo variable */
795 E->Type = type_ulong;
796 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
801 /* Illegal primary. Be sure to skip the token to avoid endless
804 Error ("Expression expected");
806 ED_MakeConstAbsInt (E, 1);
813 static void ArrayRef (ExprDesc* Expr)
814 /* Handle an array reference. This function needs a rewrite. */
825 /* Skip the bracket */
828 /* Get the type of left side */
831 /* We can apply a special treatment for arrays that have a const base
832 * address. This is true for most arrays and will produce a lot better
833 * code. Check if this is a const base address.
835 ConstBaseAddr = ED_IsRVal (Expr) &&
836 (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
838 /* If we have a constant base, we delay the address fetch */
840 if (!ConstBaseAddr) {
841 /* Get a pointer to the array into the primary */
842 LoadExpr (CF_NONE, Expr);
844 /* Get the array pointer on stack. Do not push more than 16
845 * bit, even if this value is greater, since we cannot handle
846 * other than 16bit stuff when doing indexing.
852 /* TOS now contains ptr to array elements. Get the subscript. */
853 MarkedExprWithCheck (hie0, &Subscript);
855 /* Check the types of array and subscript. We can either have a
856 * pointer/array to the left, in which case the subscript must be of an
857 * integer type, or we have an integer to the left, in which case the
858 * subscript must be a pointer/array.
859 * Since we do the necessary checking here, we can rely later on the
862 Qualifiers = T_QUAL_NONE;
863 if (IsClassPtr (Expr->Type)) {
864 if (!IsClassInt (Subscript.Type)) {
865 Error ("Array subscript is not an integer");
866 /* To avoid any compiler errors, make the expression a valid int */
867 ED_MakeConstAbsInt (&Subscript, 0);
869 if (IsTypeArray (Expr->Type)) {
870 Qualifiers = GetQualifier (Expr->Type);
872 ElementType = Indirect (Expr->Type);
873 } else if (IsClassInt (Expr->Type)) {
874 if (!IsClassPtr (Subscript.Type)) {
875 Error ("Subscripted value is neither array nor pointer");
876 /* To avoid compiler errors, make the subscript a char[] at
879 ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
880 } else if (IsTypeArray (Subscript.Type)) {
881 Qualifiers = GetQualifier (Subscript.Type);
883 ElementType = Indirect (Subscript.Type);
885 Error ("Cannot subscript");
886 /* To avoid compiler errors, fake both the array and the subscript, so
887 * we can just proceed.
889 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
890 ED_MakeConstAbsInt (&Subscript, 0);
891 ElementType = Indirect (Expr->Type);
894 /* The element type has the combined qualifiers from itself and the array,
895 * it is a member of (if any).
897 if (GetQualifier (ElementType) != (GetQualifier (ElementType) | Qualifiers)) {
898 ElementType = TypeDup (ElementType);
899 ElementType->C |= Qualifiers;
902 /* If the subscript is a bit-field, load it and make it an rvalue */
903 if (ED_IsBitField (&Subscript)) {
904 LoadExpr (CF_NONE, &Subscript);
905 ED_MakeRValExpr (&Subscript);
908 /* Check if the subscript is constant absolute value */
909 if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) {
911 /* The array subscript is a numeric constant. If we had pushed the
912 * array base address onto the stack before, we can remove this value,
913 * since we can generate expression+offset.
915 if (!ConstBaseAddr) {
918 /* Get an array pointer into the primary */
919 LoadExpr (CF_NONE, Expr);
922 if (IsClassPtr (Expr->Type)) {
924 /* Lhs is pointer/array. Scale the subscript value according to
927 Subscript.IVal *= CheckedSizeOf (ElementType);
929 /* Remove the address load code */
932 /* In case of an array, we can adjust the offset of the expression
933 * already in Expr. If the base address was a constant, we can even
934 * remove the code that loaded the address into the primary.
936 if (IsTypeArray (Expr->Type)) {
938 /* Adjust the offset */
939 Expr->IVal += Subscript.IVal;
943 /* It's a pointer, so we do have to load it into the primary
944 * first (if it's not already there).
946 if (ConstBaseAddr || ED_IsLVal (Expr)) {
947 LoadExpr (CF_NONE, Expr);
948 ED_MakeRValExpr (Expr);
952 Expr->IVal = Subscript.IVal;
957 /* Scale the rhs value according to the element type */
958 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
960 /* Add the subscript. Since arrays are indexed by integers,
961 * we will ignore the true type of the subscript here and
962 * use always an int. #### Use offset but beware of LoadExpr!
964 g_inc (CF_INT | CF_CONST, Subscript.IVal);
970 /* Array subscript is not constant. Load it into the primary */
972 LoadExpr (CF_NONE, &Subscript);
975 if (IsClassPtr (Expr->Type)) {
977 /* Indexing is based on unsigneds, so we will just use the integer
978 * portion of the index (which is in (e)ax, so there's no further
981 g_scale (CF_INT, CheckedSizeOf (ElementType));
985 /* Get the int value on top. If we come here, we're sure, both
986 * values are 16 bit (the first one was truncated if necessary
987 * and the second one is a pointer). Note: If ConstBaseAddr is
988 * true, we don't have a value on stack, so to "swap" both, just
989 * push the subscript.
993 LoadExpr (CF_NONE, Expr);
1000 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1004 /* The offset is now in the primary register. It we didn't have a
1005 * constant base address for the lhs, the lhs address is already
1006 * on stack, and we must add the offset. If the base address was
1007 * constant, we call special functions to add the address to the
1010 if (!ConstBaseAddr) {
1012 /* The array base address is on stack and the subscript is in the
1013 * primary. Add both.
1019 /* The subscript is in the primary, and the array base address is
1020 * in Expr. If the subscript has itself a constant address, it is
1021 * often a better idea to reverse again the order of the
1022 * evaluation. This will generate better code if the subscript is
1023 * a byte sized variable. But beware: This is only possible if the
1024 * subscript was not scaled, that is, if this was a byte array
1027 if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
1028 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1032 /* Reverse the order of evaluation */
1033 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
1038 RemoveCode (&Mark2);
1040 /* Get a pointer to the array into the primary. */
1041 LoadExpr (CF_NONE, Expr);
1043 /* Add the variable */
1044 if (ED_IsLocStack (&Subscript)) {
1045 g_addlocal (Flags, Subscript.IVal);
1047 Flags |= GlobalModeFlags (&Subscript);
1048 g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1052 if (ED_IsLocAbs (Expr)) {
1053 /* Constant numeric address. Just add it */
1054 g_inc (CF_INT, Expr->IVal);
1055 } else if (ED_IsLocStack (Expr)) {
1056 /* Base address is a local variable address */
1057 if (IsTypeArray (Expr->Type)) {
1058 g_addaddr_local (CF_INT, Expr->IVal);
1060 g_addlocal (CF_PTR, Expr->IVal);
1063 /* Base address is a static variable address */
1064 unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1065 if (ED_IsRVal (Expr)) {
1066 /* Add the address of the location */
1067 g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1069 /* Add the contents of the location */
1070 g_addstatic (Flags, Expr->Name, Expr->IVal);
1078 /* The result is an expression in the primary */
1079 ED_MakeRValExpr (Expr);
1083 /* Result is of element type */
1084 Expr->Type = ElementType;
1086 /* An array element is actually a variable. So the rules for variables
1087 * with respect to the reference type apply: If it's an array, it is
1088 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1089 * but an array cannot contain functions).
1091 if (IsTypeArray (Expr->Type)) {
1097 /* Consume the closing bracket */
1103 static void StructRef (ExprDesc* Expr)
1104 /* Process struct field after . or ->. */
1111 /* Skip the token and check for an identifier */
1113 if (CurTok.Tok != TOK_IDENT) {
1114 Error ("Identifier expected");
1115 /* Make the expression an integer at address zero */
1116 ED_MakeConstAbs (Expr, 0, type_int);
1120 /* Get the symbol table entry and check for a struct field */
1121 strcpy (Ident, CurTok.Ident);
1123 Field = FindStructField (Expr->Type, Ident);
1125 Error ("Struct/union has no field named `%s'", Ident);
1126 /* Make the expression an integer at address zero */
1127 ED_MakeConstAbs (Expr, 0, type_int);
1131 /* If we have a struct pointer that is an lvalue and not already in the
1132 * primary, load it now.
1134 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1136 /* Load into the primary */
1137 LoadExpr (CF_NONE, Expr);
1139 /* Make it an lvalue expression */
1140 ED_MakeLValExpr (Expr);
1143 /* The type is the type of the field plus any qualifiers from the struct */
1144 if (IsClassStruct (Expr->Type)) {
1145 Q = GetQualifier (Expr->Type);
1147 Q = GetQualifier (Indirect (Expr->Type));
1149 if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1150 FinalType = Field->Type;
1152 FinalType = TypeDup (Field->Type);
1156 /* A struct is usually an lvalue. If not, it is a struct in the primary
1159 if (ED_IsRVal (Expr) && ED_IsLocExpr (Expr) && !IsTypePtr (Expr->Type)) {
1164 /* Get the size of the type */
1165 unsigned Size = SizeOf (Expr->Type);
1168 CHECK (Field->V.Offs + Size <= SIZEOF_LONG);
1170 /* The type of the operation depends on the type of the struct */
1172 case 1: Flags = CF_CHAR | CF_UNSIGNED | CF_CONST; break;
1173 case 2: Flags = CF_INT | CF_UNSIGNED | CF_CONST; break;
1174 case 3: /* FALLTHROUGH */
1175 case 4: Flags = CF_LONG | CF_UNSIGNED | CF_CONST; break;
1176 default: Internal ("Invalid struct size: %u", Size); break;
1179 /* Generate a shift to get the field in the proper position in the
1180 * primary. For bit fields, mask the value.
1182 BitOffs = Field->V.Offs * CHAR_BITS;
1183 if (SymIsBitField (Field)) {
1184 BitOffs += Field->V.B.BitOffs;
1185 g_asr (Flags, BitOffs);
1186 /* Mask the value. This is unnecessary if the shift executed above
1187 * moved only zeroes into the value.
1189 if (BitOffs + Field->V.B.BitWidth != Size * CHAR_BITS) {
1190 g_and (CF_INT | CF_UNSIGNED | CF_CONST,
1191 (0x0001U << Field->V.B.BitWidth) - 1U);
1194 g_asr (Flags, BitOffs);
1197 /* Use the new type */
1198 Expr->Type = FinalType;
1202 /* Set the struct field offset */
1203 Expr->IVal += Field->V.Offs;
1205 /* Use the new type */
1206 Expr->Type = FinalType;
1208 /* An struct member is actually a variable. So the rules for variables
1209 * with respect to the reference type apply: If it's an array, it is
1210 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1211 * but a struct field cannot be a function).
1213 if (IsTypeArray (Expr->Type)) {
1219 /* Make the expression a bit field if necessary */
1220 if (SymIsBitField (Field)) {
1221 ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1229 static void hie11 (ExprDesc *Expr)
1230 /* Handle compound types (structs and arrays) */
1232 /* Name value used in invalid function calls */
1233 static const char IllegalFunc[] = "illegal_function_call";
1235 /* Evaluate the lhs */
1238 /* Check for a rhs */
1239 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1240 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1242 switch (CurTok.Tok) {
1245 /* Array reference */
1250 /* Function call. */
1251 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1252 /* Not a function */
1253 Error ("Illegal function call");
1254 /* Force the type to be a implicitly defined function, one
1255 * returning an int and taking any number of arguments.
1256 * Since we don't have a name, invent one.
1258 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1259 Expr->Name = (long) IllegalFunc;
1261 /* Call the function */
1262 FunctionCall (Expr);
1266 if (!IsClassStruct (Expr->Type)) {
1267 Error ("Struct expected");
1273 /* If we have an array, convert it to pointer to first element */
1274 if (IsTypeArray (Expr->Type)) {
1275 Expr->Type = ArrayToPtr (Expr->Type);
1277 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1278 Error ("Struct pointer expected");
1284 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1292 void Store (ExprDesc* Expr, const Type* StoreType)
1293 /* Store the primary register into the location denoted by Expr. If StoreType
1294 * is given, use this type when storing instead of Expr->Type. If StoreType
1295 * is NULL, use Expr->Type instead.
1300 /* If StoreType was not given, use Expr->Type instead */
1301 if (StoreType == 0) {
1302 StoreType = Expr->Type;
1305 /* Prepare the code generator flags */
1306 Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1308 /* Do the store depending on the location */
1309 switch (ED_GetLoc (Expr)) {
1312 /* Absolute: numeric address or const */
1313 g_putstatic (Flags, Expr->IVal, 0);
1317 /* Global variable */
1318 g_putstatic (Flags, Expr->Name, Expr->IVal);
1323 /* Static variable or literal in the literal pool */
1324 g_putstatic (Flags, Expr->Name, Expr->IVal);
1327 case E_LOC_REGISTER:
1328 /* Register variable */
1329 g_putstatic (Flags, Expr->Name, Expr->IVal);
1333 /* Value on the stack */
1334 g_putlocal (Flags, Expr->IVal, 0);
1338 /* The primary register (value is already there) */
1342 /* An expression in the primary register */
1343 g_putind (Flags, Expr->IVal);
1347 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1350 /* Assume that each one of the stores will invalidate CC */
1351 ED_MarkAsUntested (Expr);
1356 static void PreInc (ExprDesc* Expr)
1357 /* Handle the preincrement operators */
1362 /* Skip the operator token */
1365 /* Evaluate the expression and check that it is an lvalue */
1367 if (!ED_IsLVal (Expr)) {
1368 Error ("Invalid lvalue");
1372 /* We cannot modify const values */
1373 if (IsQualConst (Expr->Type)) {
1374 Error ("Increment of read-only variable");
1377 /* Get the data type */
1378 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1380 /* Get the increment value in bytes */
1381 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1383 /* Check the location of the data */
1384 switch (ED_GetLoc (Expr)) {
1387 /* Absolute: numeric address or const */
1388 g_addeqstatic (Flags, Expr->IVal, 0, Val);
1392 /* Global variable */
1393 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1398 /* Static variable or literal in the literal pool */
1399 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1402 case E_LOC_REGISTER:
1403 /* Register variable */
1404 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1408 /* Value on the stack */
1409 g_addeqlocal (Flags, Expr->IVal, Val);
1413 /* The primary register */
1418 /* An expression in the primary register */
1419 g_addeqind (Flags, Expr->IVal, Val);
1423 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1426 /* Result is an expression, no reference */
1427 ED_MakeRValExpr (Expr);
1432 static void PreDec (ExprDesc* Expr)
1433 /* Handle the predecrement operators */
1438 /* Skip the operator token */
1441 /* Evaluate the expression and check that it is an lvalue */
1443 if (!ED_IsLVal (Expr)) {
1444 Error ("Invalid lvalue");
1448 /* We cannot modify const values */
1449 if (IsQualConst (Expr->Type)) {
1450 Error ("Decrement of read-only variable");
1453 /* Get the data type */
1454 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1456 /* Get the increment value in bytes */
1457 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1459 /* Check the location of the data */
1460 switch (ED_GetLoc (Expr)) {
1463 /* Absolute: numeric address or const */
1464 g_subeqstatic (Flags, Expr->IVal, 0, Val);
1468 /* Global variable */
1469 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1474 /* Static variable or literal in the literal pool */
1475 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1478 case E_LOC_REGISTER:
1479 /* Register variable */
1480 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1484 /* Value on the stack */
1485 g_subeqlocal (Flags, Expr->IVal, Val);
1489 /* The primary register */
1494 /* An expression in the primary register */
1495 g_subeqind (Flags, Expr->IVal, Val);
1499 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1502 /* Result is an expression, no reference */
1503 ED_MakeRValExpr (Expr);
1508 static void PostInc (ExprDesc* Expr)
1509 /* Handle the postincrement operator */
1515 /* The expression to increment must be an lvalue */
1516 if (!ED_IsLVal (Expr)) {
1517 Error ("Invalid lvalue");
1521 /* We cannot modify const values */
1522 if (IsQualConst (Expr->Type)) {
1523 Error ("Increment of read-only variable");
1526 /* Get the data type */
1527 Flags = TypeOf (Expr->Type);
1529 /* Push the address if needed */
1532 /* Fetch the value and save it (since it's the result of the expression) */
1533 LoadExpr (CF_NONE, Expr);
1534 g_save (Flags | CF_FORCECHAR);
1536 /* If we have a pointer expression, increment by the size of the type */
1537 if (IsTypePtr (Expr->Type)) {
1538 g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1540 g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1543 /* Store the result back */
1546 /* Restore the original value in the primary register */
1547 g_restore (Flags | CF_FORCECHAR);
1549 /* The result is always an expression, no reference */
1550 ED_MakeRValExpr (Expr);
1555 static void PostDec (ExprDesc* Expr)
1556 /* Handle the postdecrement operator */
1562 /* The expression to increment must be an lvalue */
1563 if (!ED_IsLVal (Expr)) {
1564 Error ("Invalid lvalue");
1568 /* We cannot modify const values */
1569 if (IsQualConst (Expr->Type)) {
1570 Error ("Decrement of read-only variable");
1573 /* Get the data type */
1574 Flags = TypeOf (Expr->Type);
1576 /* Push the address if needed */
1579 /* Fetch the value and save it (since it's the result of the expression) */
1580 LoadExpr (CF_NONE, Expr);
1581 g_save (Flags | CF_FORCECHAR);
1583 /* If we have a pointer expression, increment by the size of the type */
1584 if (IsTypePtr (Expr->Type)) {
1585 g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1587 g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1590 /* Store the result back */
1593 /* Restore the original value in the primary register */
1594 g_restore (Flags | CF_FORCECHAR);
1596 /* The result is always an expression, no reference */
1597 ED_MakeRValExpr (Expr);
1602 static void UnaryOp (ExprDesc* Expr)
1603 /* Handle unary -/+ and ~ */
1607 /* Remember the operator token and skip it */
1608 token_t Tok = CurTok.Tok;
1611 /* Get the expression */
1614 /* We can only handle integer types */
1615 if (!IsClassInt (Expr->Type)) {
1616 Error ("Argument must have integer type");
1617 ED_MakeConstAbsInt (Expr, 1);
1620 /* Check for a constant expression */
1621 if (ED_IsConstAbs (Expr)) {
1622 /* Value is constant */
1624 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1625 case TOK_PLUS: break;
1626 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1627 default: Internal ("Unexpected token: %d", Tok);
1630 /* Value is not constant */
1631 LoadExpr (CF_NONE, Expr);
1633 /* Get the type of the expression */
1634 Flags = TypeOf (Expr->Type);
1636 /* Handle the operation */
1638 case TOK_MINUS: g_neg (Flags); break;
1639 case TOK_PLUS: break;
1640 case TOK_COMP: g_com (Flags); break;
1641 default: Internal ("Unexpected token: %d", Tok);
1644 /* The result is a rvalue in the primary */
1645 ED_MakeRValExpr (Expr);
1651 void hie10 (ExprDesc* Expr)
1652 /* Handle ++, --, !, unary - etc. */
1656 switch (CurTok.Tok) {
1674 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1675 /* Constant expression */
1676 Expr->IVal = !Expr->IVal;
1678 g_bneg (TypeOf (Expr->Type));
1679 ED_MakeRValExpr (Expr);
1680 ED_TestDone (Expr); /* bneg will set cc */
1686 ExprWithCheck (hie10, Expr);
1687 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1688 /* Not a const, load it into the primary and make it a
1691 LoadExpr (CF_NONE, Expr);
1692 ED_MakeRValExpr (Expr);
1694 /* If the expression is already a pointer to function, the
1695 * additional dereferencing operator must be ignored. A function
1696 * itself is represented as "pointer to function", so any number
1697 * of dereference operators is legal, since the result will
1698 * always be converted to "pointer to function".
1700 if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1701 /* Expression not storable */
1704 if (IsClassPtr (Expr->Type)) {
1705 Expr->Type = Indirect (Expr->Type);
1707 Error ("Illegal indirection");
1709 /* The * operator yields an lvalue */
1716 ExprWithCheck (hie10, Expr);
1717 /* The & operator may be applied to any lvalue, and it may be
1718 * applied to functions, even if they're no lvalues.
1720 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1721 Error ("Illegal address");
1723 if (ED_IsBitField (Expr)) {
1724 Error ("Cannot take address of bit-field");
1725 /* Do it anyway, just to avoid further warnings */
1726 Expr->Flags &= ~E_BITFIELD;
1728 Expr->Type = PointerTo (Expr->Type);
1729 /* The & operator yields an rvalue */
1736 if (TypeSpecAhead ()) {
1739 Size = CheckedSizeOf (ParseType (T));
1742 /* Remember the output queue pointer */
1746 Size = CheckedSizeOf (Expr->Type);
1747 /* Remove any generated code */
1750 ED_MakeConstAbs (Expr, Size, type_size_t);
1751 ED_MarkAsUntested (Expr);
1755 if (TypeSpecAhead ()) {
1765 /* Handle post increment */
1766 switch (CurTok.Tok) {
1767 case TOK_INC: PostInc (Expr); break;
1768 case TOK_DEC: PostDec (Expr); break;
1779 static void hie_internal (const GenDesc* Ops, /* List of generators */
1781 void (*hienext) (ExprDesc*),
1783 /* Helper function */
1789 token_t Tok; /* The operator token */
1790 unsigned ltype, type;
1791 int rconst; /* Operand is a constant */
1797 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1799 /* Tell the caller that we handled it's ops */
1802 /* All operators that call this function expect an int on the lhs */
1803 if (!IsClassInt (Expr->Type)) {
1804 Error ("Integer expression expected");
1805 /* To avoid further errors, make Expr a valid int expression */
1806 ED_MakeConstAbsInt (Expr, 1);
1809 /* Remember the operator token, then skip it */
1813 /* Get the lhs on stack */
1814 GetCodePos (&Mark1);
1815 ltype = TypeOf (Expr->Type);
1816 if (ED_IsConstAbs (Expr)) {
1817 /* Constant value */
1818 GetCodePos (&Mark2);
1819 g_push (ltype | CF_CONST, Expr->IVal);
1821 /* Value not constant */
1822 LoadExpr (CF_NONE, Expr);
1823 GetCodePos (&Mark2);
1827 /* Get the right hand side */
1828 MarkedExprWithCheck (hienext, &Expr2);
1830 /* Check for a constant expression */
1831 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1833 /* Not constant, load into the primary */
1834 LoadExpr (CF_NONE, &Expr2);
1837 /* Check the type of the rhs */
1838 if (!IsClassInt (Expr2.Type)) {
1839 Error ("Integer expression expected");
1842 /* Check for const operands */
1843 if (ED_IsConstAbs (Expr) && rconst) {
1845 /* Both operands are constant, remove the generated code */
1846 RemoveCode (&Mark1);
1848 /* Get the type of the result */
1849 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1851 /* Handle the op differently for signed and unsigned types */
1852 if (IsSignSigned (Expr->Type)) {
1854 /* Evaluate the result for signed operands */
1855 signed long Val1 = Expr->IVal;
1856 signed long Val2 = Expr2.IVal;
1859 Expr->IVal = (Val1 | Val2);
1862 Expr->IVal = (Val1 ^ Val2);
1865 Expr->IVal = (Val1 & Val2);
1868 Expr->IVal = (Val1 * Val2);
1872 Error ("Division by zero");
1873 Expr->IVal = 0x7FFFFFFF;
1875 Expr->IVal = (Val1 / Val2);
1880 Error ("Modulo operation with zero");
1883 Expr->IVal = (Val1 % Val2);
1887 Internal ("hie_internal: got token 0x%X\n", Tok);
1891 /* Evaluate the result for unsigned operands */
1892 unsigned long Val1 = Expr->IVal;
1893 unsigned long Val2 = Expr2.IVal;
1896 Expr->IVal = (Val1 | Val2);
1899 Expr->IVal = (Val1 ^ Val2);
1902 Expr->IVal = (Val1 & Val2);
1905 Expr->IVal = (Val1 * Val2);
1909 Error ("Division by zero");
1910 Expr->IVal = 0xFFFFFFFF;
1912 Expr->IVal = (Val1 / Val2);
1917 Error ("Modulo operation with zero");
1920 Expr->IVal = (Val1 % Val2);
1924 Internal ("hie_internal: got token 0x%X\n", Tok);
1930 /* If the right hand side is constant, and the generator function
1931 * expects the lhs in the primary, remove the push of the primary
1934 unsigned rtype = TypeOf (Expr2.Type);
1937 /* Second value is constant - check for div */
1940 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1941 Error ("Division by zero");
1942 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1943 Error ("Modulo operation with zero");
1945 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1946 RemoveCode (&Mark2);
1947 ltype |= CF_REG; /* Value is in register */
1951 /* Determine the type of the operation result. */
1952 type |= g_typeadjust (ltype, rtype);
1953 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1956 Gen->Func (type, Expr2.IVal);
1958 /* We have a rvalue in the primary now */
1959 ED_MakeRValExpr (Expr);
1966 static void hie_compare (const GenDesc* Ops, /* List of generators */
1968 void (*hienext) (ExprDesc*))
1969 /* Helper function for the compare operators */
1976 token_t Tok; /* The operator token */
1978 int rconst; /* Operand is a constant */
1981 GetCodePos (&Mark0);
1984 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1986 /* Remember the generator function */
1987 void (*GenFunc) (unsigned, unsigned long) = Gen->Func;
1989 /* Remember the operator token, then skip it */
1993 /* Get the lhs on stack */
1994 GetCodePos (&Mark1);
1995 ltype = TypeOf (Expr->Type);
1996 if (ED_IsConstAbs (Expr)) {
1997 /* Constant value */
1998 GetCodePos (&Mark2);
1999 g_push (ltype | CF_CONST, Expr->IVal);
2001 /* Value not constant */
2002 LoadExpr (CF_NONE, Expr);
2003 GetCodePos (&Mark2);
2007 /* Get the right hand side */
2008 MarkedExprWithCheck (hienext, &Expr2);
2010 /* Check for a constant expression */
2011 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
2013 /* Not constant, load into the primary */
2014 LoadExpr (CF_NONE, &Expr2);
2017 /* Make sure, the types are compatible */
2018 if (IsClassInt (Expr->Type)) {
2019 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
2020 Error ("Incompatible types");
2022 } else if (IsClassPtr (Expr->Type)) {
2023 if (IsClassPtr (Expr2.Type)) {
2024 /* Both pointers are allowed in comparison if they point to
2025 * the same type, or if one of them is a void pointer.
2027 Type* left = Indirect (Expr->Type);
2028 Type* right = Indirect (Expr2.Type);
2029 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
2030 /* Incomatible pointers */
2031 Error ("Incompatible types");
2033 } else if (!ED_IsNullPtr (&Expr2)) {
2034 Error ("Incompatible types");
2038 /* Check for const operands */
2039 if (ED_IsConstAbs (Expr) && rconst) {
2041 /* If the result is constant, this is suspicious when not in
2042 * preprocessor mode.
2044 WarnConstCompareResult ();
2046 /* Both operands are constant, remove the generated code */
2047 RemoveCode (&Mark1);
2049 /* Determine if this is a signed or unsigned compare */
2050 if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
2051 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
2053 /* Evaluate the result for signed operands */
2054 signed long Val1 = Expr->IVal;
2055 signed long Val2 = Expr2.IVal;
2057 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2058 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2059 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2060 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2061 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2062 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2063 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2068 /* Evaluate the result for unsigned operands */
2069 unsigned long Val1 = Expr->IVal;
2070 unsigned long Val2 = Expr2.IVal;
2072 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2073 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2074 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2075 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2076 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2077 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2078 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2084 /* Determine the signedness of the operands */
2085 int LeftSigned = IsSignSigned (Expr->Type);
2086 int RightSigned = IsSignSigned (Expr2.Type);
2088 /* If the right hand side is constant, and the generator function
2089 * expects the lhs in the primary, remove the push of the primary
2095 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2096 RemoveCode (&Mark2);
2097 ltype |= CF_REG; /* Value is in register */
2101 /* Determine the type of the operation. */
2102 if (IsTypeChar (Expr->Type) && rconst) {
2104 /* Left side is unsigned char, right side is constant.
2105 * Determine the minimum and maximum values
2107 int LeftMin, LeftMax;
2115 /* An integer value is always represented as a signed in the
2116 * ExprDesc structure. This may lead to false results below,
2117 * if it is actually unsigned, but interpreted as signed
2118 * because of the representation. Fortunately, in this case,
2119 * the actual value doesn't matter, since it's always greater
2120 * than what can be represented in a char. So correct the
2121 * value accordingly.
2123 if (!RightSigned && Expr2.IVal < 0) {
2124 /* Correct the value so it is an unsigned. It will then
2125 * anyway match one of the cases below.
2127 Expr2.IVal = LeftMax + 1;
2130 /* Comparing a char against a constant may have a constant
2131 * result. Please note: It is not possible to remove the code
2132 * for the compare alltogether, because it may have side
2138 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2139 ED_MakeConstAbsInt (Expr, 0);
2140 WarnConstCompareResult ();
2146 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2147 ED_MakeConstAbsInt (Expr, 1);
2148 WarnConstCompareResult ();
2154 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2155 ED_MakeConstAbsInt (Expr, Expr2.IVal > LeftMax);
2156 WarnConstCompareResult ();
2162 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2163 ED_MakeConstAbsInt (Expr, Expr2.IVal >= LeftMax);
2164 WarnConstCompareResult ();
2170 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2171 ED_MakeConstAbsInt (Expr, Expr2.IVal <= LeftMin);
2172 WarnConstCompareResult ();
2178 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2179 ED_MakeConstAbsInt (Expr, Expr2.IVal < LeftMin);
2180 WarnConstCompareResult ();
2186 Internal ("hie_compare: got token 0x%X\n", Tok);
2189 /* If the result is not already constant (as evaluated in the
2190 * switch above), we can execute the operation as a char op,
2191 * since the right side constant is in a valid range.
2193 flags |= (CF_CHAR | CF_FORCECHAR);
2195 flags |= CF_UNSIGNED;
2198 } else if (IsTypeChar (Expr->Type) && IsTypeChar (Expr2.Type) &&
2199 GetSignedness (Expr->Type) == GetSignedness (Expr2.Type)) {
2201 /* Both are chars with the same signedness. We can encode the
2202 * operation as a char operation.
2206 flags |= CF_FORCECHAR;
2209 flags |= CF_UNSIGNED;
2212 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2213 flags |= g_typeadjust (ltype, rtype);
2216 /* If the left side is an unsigned and the right is a constant,
2217 * we may be able to change the compares to something more
2220 if (!LeftSigned && rconst) {
2225 if (Expr2.IVal == 1) {
2226 /* An unsigned compare to one means that the value
2235 if (Expr2.IVal == 0) {
2236 /* An unsigned compare to zero means that the value
2244 if (Expr2.IVal == 1) {
2245 /* An unsigned compare to one means that the value
2254 if (Expr2.IVal == 0) {
2255 /* An unsigned compare to zero means that the value
2270 GenFunc (flags, Expr2.IVal);
2272 /* The result is an rvalue in the primary */
2273 ED_MakeRValExpr (Expr);
2276 /* Result type is always int */
2277 Expr->Type = type_int;
2279 Done: /* Condition codes are set */
2286 static void hie9 (ExprDesc *Expr)
2287 /* Process * and / operators. */
2289 static const GenDesc hie9_ops[] = {
2290 { TOK_STAR, GEN_NOPUSH, g_mul },
2291 { TOK_DIV, GEN_NOPUSH, g_div },
2292 { TOK_MOD, GEN_NOPUSH, g_mod },
2293 { TOK_INVALID, 0, 0 }
2297 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2302 static void parseadd (ExprDesc* Expr)
2303 /* Parse an expression with the binary plus operator. Expr contains the
2304 * unprocessed left hand side of the expression and will contain the
2305 * result of the expression on return.
2309 unsigned flags; /* Operation flags */
2310 CodeMark Mark; /* Remember code position */
2311 Type* lhst; /* Type of left hand side */
2312 Type* rhst; /* Type of right hand side */
2315 /* Skip the PLUS token */
2318 /* Get the left hand side type, initialize operation flags */
2322 /* Check for constness on both sides */
2323 if (ED_IsConst (Expr)) {
2325 /* The left hand side is a constant of some sort. Good. Get rhs */
2327 if (ED_IsConstAbs (&Expr2)) {
2329 /* Right hand side is a constant numeric value. Get the rhs type */
2332 /* Both expressions are constants. Check for pointer arithmetic */
2333 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2334 /* Left is pointer, right is int, must scale rhs */
2335 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2336 /* Result type is a pointer */
2337 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2338 /* Left is int, right is pointer, must scale lhs */
2339 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2340 /* Result type is a pointer */
2341 Expr->Type = Expr2.Type;
2342 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2343 /* Integer addition */
2344 Expr->IVal += Expr2.IVal;
2345 typeadjust (Expr, &Expr2, 1);
2348 Error ("Invalid operands for binary operator `+'");
2353 /* lhs is a constant and rhs is not constant. Load rhs into
2356 LoadExpr (CF_NONE, &Expr2);
2358 /* Beware: The check above (for lhs) lets not only pass numeric
2359 * constants, but also constant addresses (labels), maybe even
2360 * with an offset. We have to check for that here.
2363 /* First, get the rhs type. */
2367 if (ED_IsLocAbs (Expr)) {
2368 /* A numerical constant */
2371 /* Constant address label */
2372 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2375 /* Check for pointer arithmetic */
2376 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2377 /* Left is pointer, right is int, must scale rhs */
2378 g_scale (CF_INT, CheckedPSizeOf (lhst));
2379 /* Operate on pointers, result type is a pointer */
2381 /* Generate the code for the add */
2382 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2383 /* Numeric constant */
2384 g_inc (flags, Expr->IVal);
2386 /* Constant address */
2387 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2389 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2391 /* Left is int, right is pointer, must scale lhs. */
2392 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2394 /* Operate on pointers, result type is a pointer */
2396 Expr->Type = Expr2.Type;
2398 /* Since we do already have rhs in the primary, if lhs is
2399 * not a numeric constant, and the scale factor is not one
2400 * (no scaling), we must take the long way over the stack.
2402 if (ED_IsLocAbs (Expr)) {
2403 /* Numeric constant, scale lhs */
2404 Expr->IVal *= ScaleFactor;
2405 /* Generate the code for the add */
2406 g_inc (flags, Expr->IVal);
2407 } else if (ScaleFactor == 1) {
2408 /* Constant address but no need to scale */
2409 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2411 /* Constant address that must be scaled */
2412 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2413 g_getimmed (flags, Expr->Name, Expr->IVal);
2414 g_scale (CF_PTR, ScaleFactor);
2417 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2418 /* Integer addition */
2419 flags |= typeadjust (Expr, &Expr2, 1);
2420 /* Generate the code for the add */
2421 if (ED_IsLocAbs (Expr)) {
2422 /* Numeric constant */
2423 g_inc (flags, Expr->IVal);
2425 /* Constant address */
2426 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2430 Error ("Invalid operands for binary operator `+'");
2434 /* Result is a rvalue in primary register */
2435 ED_MakeRValExpr (Expr);
2440 /* Left hand side is not constant. Get the value onto the stack. */
2441 LoadExpr (CF_NONE, Expr); /* --> primary register */
2443 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2445 /* Evaluate the rhs */
2446 MarkedExprWithCheck (hie9, &Expr2);
2448 /* Check for a constant rhs expression */
2449 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2451 /* Right hand side is a constant. Get the rhs type */
2454 /* Remove pushed value from stack */
2457 /* Check for pointer arithmetic */
2458 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2459 /* Left is pointer, right is int, must scale rhs */
2460 Expr2.IVal *= CheckedPSizeOf (lhst);
2461 /* Operate on pointers, result type is a pointer */
2463 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2464 /* Left is int, right is pointer, must scale lhs (ptr only) */
2465 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2466 /* Operate on pointers, result type is a pointer */
2468 Expr->Type = Expr2.Type;
2469 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2470 /* Integer addition */
2471 flags = typeadjust (Expr, &Expr2, 1);
2474 Error ("Invalid operands for binary operator `+'");
2478 /* Generate code for the add */
2479 g_inc (flags | CF_CONST, Expr2.IVal);
2483 /* Not constant, load into the primary */
2484 LoadExpr (CF_NONE, &Expr2);
2486 /* lhs and rhs are not constant. Get the rhs type. */
2489 /* Check for pointer arithmetic */
2490 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2491 /* Left is pointer, right is int, must scale rhs */
2492 g_scale (CF_INT, CheckedPSizeOf (lhst));
2493 /* Operate on pointers, result type is a pointer */
2495 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2496 /* Left is int, right is pointer, must scale lhs */
2497 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2498 g_swap (CF_INT); /* Swap TOS and primary */
2499 g_scale (CF_INT, CheckedPSizeOf (rhst));
2500 /* Operate on pointers, result type is a pointer */
2502 Expr->Type = Expr2.Type;
2503 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2504 /* Integer addition. Note: Result is never constant.
2505 * Problem here is that typeadjust does not know if the
2506 * variable is an rvalue or lvalue, so if both operands
2507 * are dereferenced constant numeric addresses, typeadjust
2508 * thinks the operation works on constants. Removing
2509 * CF_CONST here means handling the symptoms, however, the
2510 * whole parser is such a mess that I fear to break anything
2511 * when trying to apply another solution.
2513 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2516 Error ("Invalid operands for binary operator `+'");
2520 /* Generate code for the add */
2525 /* Result is a rvalue in primary register */
2526 ED_MakeRValExpr (Expr);
2529 /* Condition codes not set */
2530 ED_MarkAsUntested (Expr);
2536 static void parsesub (ExprDesc* Expr)
2537 /* Parse an expression with the binary minus operator. Expr contains the
2538 * unprocessed left hand side of the expression and will contain the
2539 * result of the expression on return.
2543 unsigned flags; /* Operation flags */
2544 Type* lhst; /* Type of left hand side */
2545 Type* rhst; /* Type of right hand side */
2546 CodeMark Mark1; /* Save position of output queue */
2547 CodeMark Mark2; /* Another position in the queue */
2548 int rscale; /* Scale factor for the result */
2551 /* Skip the MINUS token */
2554 /* Get the left hand side type, initialize operation flags */
2556 rscale = 1; /* Scale by 1, that is, don't scale */
2558 /* Remember the output queue position, then bring the value onto the stack */
2559 GetCodePos (&Mark1);
2560 LoadExpr (CF_NONE, Expr); /* --> primary register */
2561 GetCodePos (&Mark2);
2562 g_push (TypeOf (lhst), 0); /* --> stack */
2564 /* Parse the right hand side */
2565 MarkedExprWithCheck (hie9, &Expr2);
2567 /* Check for a constant rhs expression */
2568 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2570 /* The right hand side is constant. Get the rhs type. */
2573 /* Check left hand side */
2574 if (ED_IsConstAbs (Expr)) {
2576 /* Both sides are constant, remove generated code */
2577 RemoveCode (&Mark1);
2579 /* Check for pointer arithmetic */
2580 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2581 /* Left is pointer, right is int, must scale rhs */
2582 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2583 /* Operate on pointers, result type is a pointer */
2584 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2585 /* Left is pointer, right is pointer, must scale result */
2586 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2587 Error ("Incompatible pointer types");
2589 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2590 CheckedPSizeOf (lhst);
2592 /* Operate on pointers, result type is an integer */
2593 Expr->Type = type_int;
2594 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2595 /* Integer subtraction */
2596 typeadjust (Expr, &Expr2, 1);
2597 Expr->IVal -= Expr2.IVal;
2600 Error ("Invalid operands for binary operator `-'");
2603 /* Result is constant, condition codes not set */
2604 ED_MarkAsUntested (Expr);
2608 /* Left hand side is not constant, right hand side is.
2609 * Remove pushed value from stack.
2611 RemoveCode (&Mark2);
2613 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2614 /* Left is pointer, right is int, must scale rhs */
2615 Expr2.IVal *= CheckedPSizeOf (lhst);
2616 /* Operate on pointers, result type is a pointer */
2618 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2619 /* Left is pointer, right is pointer, must scale result */
2620 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2621 Error ("Incompatible pointer types");
2623 rscale = CheckedPSizeOf (lhst);
2625 /* Operate on pointers, result type is an integer */
2627 Expr->Type = type_int;
2628 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2629 /* Integer subtraction */
2630 flags = typeadjust (Expr, &Expr2, 1);
2633 Error ("Invalid operands for binary operator `-'");
2637 /* Do the subtraction */
2638 g_dec (flags | CF_CONST, Expr2.IVal);
2640 /* If this was a pointer subtraction, we must scale the result */
2642 g_scale (flags, -rscale);
2645 /* Result is a rvalue in the primary register */
2646 ED_MakeRValExpr (Expr);
2647 ED_MarkAsUntested (Expr);
2653 /* Not constant, load into the primary */
2654 LoadExpr (CF_NONE, &Expr2);
2656 /* Right hand side is not constant. Get the rhs type. */
2659 /* Check for pointer arithmetic */
2660 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2661 /* Left is pointer, right is int, must scale rhs */
2662 g_scale (CF_INT, CheckedPSizeOf (lhst));
2663 /* Operate on pointers, result type is a pointer */
2665 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2666 /* Left is pointer, right is pointer, must scale result */
2667 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2668 Error ("Incompatible pointer types");
2670 rscale = CheckedPSizeOf (lhst);
2672 /* Operate on pointers, result type is an integer */
2674 Expr->Type = type_int;
2675 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2676 /* Integer subtraction. If the left hand side descriptor says that
2677 * the lhs is const, we have to remove this mark, since this is no
2678 * longer true, lhs is on stack instead.
2680 if (ED_IsLocAbs (Expr)) {
2681 ED_MakeRValExpr (Expr);
2683 /* Adjust operand types */
2684 flags = typeadjust (Expr, &Expr2, 0);
2687 Error ("Invalid operands for binary operator `-'");
2691 /* Generate code for the sub (the & is a hack here) */
2692 g_sub (flags & ~CF_CONST, 0);
2694 /* If this was a pointer subtraction, we must scale the result */
2696 g_scale (flags, -rscale);
2699 /* Result is a rvalue in the primary register */
2700 ED_MakeRValExpr (Expr);
2701 ED_MarkAsUntested (Expr);
2707 void hie8 (ExprDesc* Expr)
2708 /* Process + and - binary operators. */
2711 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2712 if (CurTok.Tok == TOK_PLUS) {
2722 static void hie6 (ExprDesc* Expr)
2723 /* Handle greater-than type comparators */
2725 static const GenDesc hie6_ops [] = {
2726 { TOK_LT, GEN_NOPUSH, g_lt },
2727 { TOK_LE, GEN_NOPUSH, g_le },
2728 { TOK_GE, GEN_NOPUSH, g_ge },
2729 { TOK_GT, GEN_NOPUSH, g_gt },
2730 { TOK_INVALID, 0, 0 }
2732 hie_compare (hie6_ops, Expr, ShiftExpr);
2737 static void hie5 (ExprDesc* Expr)
2738 /* Handle == and != */
2740 static const GenDesc hie5_ops[] = {
2741 { TOK_EQ, GEN_NOPUSH, g_eq },
2742 { TOK_NE, GEN_NOPUSH, g_ne },
2743 { TOK_INVALID, 0, 0 }
2745 hie_compare (hie5_ops, Expr, hie6);
2750 static void hie4 (ExprDesc* Expr)
2751 /* Handle & (bitwise and) */
2753 static const GenDesc hie4_ops[] = {
2754 { TOK_AND, GEN_NOPUSH, g_and },
2755 { TOK_INVALID, 0, 0 }
2759 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2764 static void hie3 (ExprDesc* Expr)
2765 /* Handle ^ (bitwise exclusive or) */
2767 static const GenDesc hie3_ops[] = {
2768 { TOK_XOR, GEN_NOPUSH, g_xor },
2769 { TOK_INVALID, 0, 0 }
2773 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2778 static void hie2 (ExprDesc* Expr)
2779 /* Handle | (bitwise or) */
2781 static const GenDesc hie2_ops[] = {
2782 { TOK_OR, GEN_NOPUSH, g_or },
2783 { TOK_INVALID, 0, 0 }
2787 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2792 static void hieAndPP (ExprDesc* Expr)
2793 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2794 * called recursively from the preprocessor.
2799 ConstAbsIntExpr (hie2, Expr);
2800 while (CurTok.Tok == TOK_BOOL_AND) {
2806 ConstAbsIntExpr (hie2, &Expr2);
2808 /* Combine the two */
2809 Expr->IVal = (Expr->IVal && Expr2.IVal);
2815 static void hieOrPP (ExprDesc *Expr)
2816 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2817 * called recursively from the preprocessor.
2822 ConstAbsIntExpr (hieAndPP, Expr);
2823 while (CurTok.Tok == TOK_BOOL_OR) {
2829 ConstAbsIntExpr (hieAndPP, &Expr2);
2831 /* Combine the two */
2832 Expr->IVal = (Expr->IVal || Expr2.IVal);
2838 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2839 /* Process "exp && exp" */
2845 if (CurTok.Tok == TOK_BOOL_AND) {
2847 /* Tell our caller that we're evaluating a boolean */
2850 /* Get a label that we will use for false expressions */
2851 FalseLab = GetLocalLabel ();
2853 /* If the expr hasn't set condition codes, set the force-test flag */
2854 if (!ED_IsTested (Expr)) {
2855 ED_MarkForTest (Expr);
2858 /* Load the value */
2859 LoadExpr (CF_FORCECHAR, Expr);
2861 /* Generate the jump */
2862 g_falsejump (CF_NONE, FalseLab);
2864 /* Parse more boolean and's */
2865 while (CurTok.Tok == TOK_BOOL_AND) {
2872 if (!ED_IsTested (&Expr2)) {
2873 ED_MarkForTest (&Expr2);
2875 LoadExpr (CF_FORCECHAR, &Expr2);
2877 /* Do short circuit evaluation */
2878 if (CurTok.Tok == TOK_BOOL_AND) {
2879 g_falsejump (CF_NONE, FalseLab);
2881 /* Last expression - will evaluate to true */
2882 g_truejump (CF_NONE, TrueLab);
2886 /* Define the false jump label here */
2887 g_defcodelabel (FalseLab);
2889 /* The result is an rvalue in primary */
2890 ED_MakeRValExpr (Expr);
2891 ED_TestDone (Expr); /* Condition codes are set */
2897 static void hieOr (ExprDesc *Expr)
2898 /* Process "exp || exp". */
2901 int BoolOp = 0; /* Did we have a boolean op? */
2902 int AndOp; /* Did we have a && operation? */
2903 unsigned TrueLab; /* Jump to this label if true */
2907 TrueLab = GetLocalLabel ();
2909 /* Call the next level parser */
2910 hieAnd (Expr, TrueLab, &BoolOp);
2912 /* Any boolean or's? */
2913 if (CurTok.Tok == TOK_BOOL_OR) {
2915 /* If the expr hasn't set condition codes, set the force-test flag */
2916 if (!ED_IsTested (Expr)) {
2917 ED_MarkForTest (Expr);
2920 /* Get first expr */
2921 LoadExpr (CF_FORCECHAR, Expr);
2923 /* For each expression jump to TrueLab if true. Beware: If we
2924 * had && operators, the jump is already in place!
2927 g_truejump (CF_NONE, TrueLab);
2930 /* Remember that we had a boolean op */
2933 /* while there's more expr */
2934 while (CurTok.Tok == TOK_BOOL_OR) {
2941 hieAnd (&Expr2, TrueLab, &AndOp);
2942 if (!ED_IsTested (&Expr2)) {
2943 ED_MarkForTest (&Expr2);
2945 LoadExpr (CF_FORCECHAR, &Expr2);
2947 /* If there is more to come, add shortcut boolean eval. */
2948 g_truejump (CF_NONE, TrueLab);
2952 /* The result is an rvalue in primary */
2953 ED_MakeRValExpr (Expr);
2954 ED_TestDone (Expr); /* Condition codes are set */
2957 /* If we really had boolean ops, generate the end sequence */
2959 DoneLab = GetLocalLabel ();
2960 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2961 g_falsejump (CF_NONE, DoneLab);
2962 g_defcodelabel (TrueLab);
2963 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2964 g_defcodelabel (DoneLab);
2970 static void hieQuest (ExprDesc* Expr)
2971 /* Parse the ternary operator */
2975 CodeMark TrueCodeEnd;
2976 ExprDesc Expr2; /* Expression 2 */
2977 ExprDesc Expr3; /* Expression 3 */
2978 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
2979 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
2980 Type* ResultType; /* Type of result */
2983 /* Call the lower level eval routine */
2984 if (Preprocessing) {
2990 /* Check if it's a ternary expression */
2991 if (CurTok.Tok == TOK_QUEST) {
2993 if (!ED_IsTested (Expr)) {
2994 /* Condition codes not set, request a test */
2995 ED_MarkForTest (Expr);
2997 LoadExpr (CF_NONE, Expr);
2998 FalseLab = GetLocalLabel ();
2999 g_falsejump (CF_NONE, FalseLab);
3001 /* Parse second expression. Remember for later if it is a NULL pointer
3002 * expression, then load it into the primary.
3004 ExprWithCheck (hie1, &Expr2);
3005 Expr2IsNULL = ED_IsNullPtr (&Expr2);
3006 if (!IsTypeVoid (Expr2.Type)) {
3007 /* Load it into the primary */
3008 LoadExpr (CF_NONE, &Expr2);
3009 ED_MakeRValExpr (&Expr2);
3010 Expr2.Type = PtrConversion (Expr2.Type);
3013 /* Remember the current code position */
3014 GetCodePos (&TrueCodeEnd);
3016 /* Jump around the evaluation of the third expression */
3017 TrueLab = GetLocalLabel ();
3021 /* Jump here if the first expression was false */
3022 g_defcodelabel (FalseLab);
3024 /* Parse third expression. Remember for later if it is a NULL pointer
3025 * expression, then load it into the primary.
3027 ExprWithCheck (hie1, &Expr3);
3028 Expr3IsNULL = ED_IsNullPtr (&Expr3);
3029 if (!IsTypeVoid (Expr3.Type)) {
3030 /* Load it into the primary */
3031 LoadExpr (CF_NONE, &Expr3);
3032 ED_MakeRValExpr (&Expr3);
3033 Expr3.Type = PtrConversion (Expr3.Type);
3036 /* Check if any conversions are needed, if so, do them.
3037 * Conversion rules for ?: expression are:
3038 * - if both expressions are int expressions, default promotion
3039 * rules for ints apply.
3040 * - if both expressions are pointers of the same type, the
3041 * result of the expression is of this type.
3042 * - if one of the expressions is a pointer and the other is
3043 * a zero constant, the resulting type is that of the pointer
3045 * - if both expressions are void expressions, the result is of
3047 * - all other cases are flagged by an error.
3049 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
3051 CodeMark CvtCodeStart;
3052 CodeMark CvtCodeEnd;
3055 /* Get common type */
3056 ResultType = promoteint (Expr2.Type, Expr3.Type);
3058 /* Convert the third expression to this type if needed */
3059 TypeConversion (&Expr3, ResultType);
3061 /* Emit conversion code for the second expression, but remember
3062 * where it starts end ends.
3064 GetCodePos (&CvtCodeStart);
3065 TypeConversion (&Expr2, ResultType);
3066 GetCodePos (&CvtCodeEnd);
3068 /* If we had conversion code, move it to the right place */
3069 if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
3070 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
3073 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
3074 /* Must point to same type */
3075 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
3076 Error ("Incompatible pointer types");
3078 /* Result has the common type */
3079 ResultType = Expr2.Type;
3080 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
3081 /* Result type is pointer, no cast needed */
3082 ResultType = Expr2.Type;
3083 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
3084 /* Result type is pointer, no cast needed */
3085 ResultType = Expr3.Type;
3086 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
3087 /* Result type is void */
3088 ResultType = Expr3.Type;
3090 Error ("Incompatible types");
3091 ResultType = Expr2.Type; /* Doesn't matter here */
3094 /* Define the final label */
3095 g_defcodelabel (TrueLab);
3097 /* Setup the target expression */
3098 ED_MakeRValExpr (Expr);
3099 Expr->Type = ResultType;
3105 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
3106 /* Process "op=" operators. */
3113 /* op= can only be used with lvalues */
3114 if (!ED_IsLVal (Expr)) {
3115 Error ("Invalid lvalue in assignment");
3119 /* The left side must not be const qualified */
3120 if (IsQualConst (Expr->Type)) {
3121 Error ("Assignment to const");
3124 /* There must be an integer or pointer on the left side */
3125 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3126 Error ("Invalid left operand type");
3127 /* Continue. Wrong code will be generated, but the compiler won't
3128 * break, so this is the best error recovery.
3132 /* Skip the operator token */
3135 /* Determine the type of the lhs */
3136 flags = TypeOf (Expr->Type);
3137 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
3139 /* Get the lhs address on stack (if needed) */
3142 /* Fetch the lhs into the primary register if needed */
3143 LoadExpr (CF_NONE, Expr);
3145 /* Bring the lhs on stack */
3149 /* Evaluate the rhs */
3150 MarkedExprWithCheck (hie1, &Expr2);
3152 /* The rhs must be an integer (or a float, but we don't support that yet */
3153 if (!IsClassInt (Expr2.Type)) {
3154 Error ("Invalid right operand for binary operator `%s'", Op);
3155 /* Continue. Wrong code will be generated, but the compiler won't
3156 * break, so this is the best error recovery.
3160 /* Check for a constant expression */
3161 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
3162 /* The resulting value is a constant. If the generator has the NOPUSH
3163 * flag set, don't push the lhs.
3165 if (Gen->Flags & GEN_NOPUSH) {
3169 /* lhs is a pointer, scale rhs */
3170 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
3173 /* If the lhs is character sized, the operation may be later done
3176 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3177 flags |= CF_FORCECHAR;
3180 /* Special handling for add and sub - some sort of a hack, but short code */
3181 if (Gen->Func == g_add) {
3182 g_inc (flags | CF_CONST, Expr2.IVal);
3183 } else if (Gen->Func == g_sub) {
3184 g_dec (flags | CF_CONST, Expr2.IVal);
3186 if (Expr2.IVal == 0) {
3187 /* Check for div by zero/mod by zero */
3188 if (Gen->Func == g_div) {
3189 Error ("Division by zero");
3190 } else if (Gen->Func == g_mod) {
3191 Error ("Modulo operation with zero");
3194 Gen->Func (flags | CF_CONST, Expr2.IVal);
3198 /* rhs is not constant. Load into the primary */
3199 LoadExpr (CF_NONE, &Expr2);
3201 /* lhs is a pointer, scale rhs */
3202 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
3205 /* If the lhs is character sized, the operation may be later done
3208 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3209 flags |= CF_FORCECHAR;
3212 /* Adjust the types of the operands if needed */
3213 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
3216 ED_MakeRValExpr (Expr);
3221 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3222 /* Process the += and -= operators */
3230 /* We're currently only able to handle some adressing modes */
3231 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3232 /* Use generic routine */
3233 opeq (Gen, Expr, Op);
3237 /* We must have an lvalue */
3238 if (ED_IsRVal (Expr)) {
3239 Error ("Invalid lvalue in assignment");
3243 /* The left side must not be const qualified */
3244 if (IsQualConst (Expr->Type)) {
3245 Error ("Assignment to const");
3248 /* There must be an integer or pointer on the left side */
3249 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3250 Error ("Invalid left operand type");
3251 /* Continue. Wrong code will be generated, but the compiler won't
3252 * break, so this is the best error recovery.
3256 /* Skip the operator */
3259 /* Check if we have a pointer expression and must scale rhs */
3260 MustScale = IsTypePtr (Expr->Type);
3262 /* Initialize the code generator flags */
3266 /* Evaluate the rhs. We expect an integer here, since float is not
3270 if (!IsClassInt (Expr2.Type)) {
3271 Error ("Invalid right operand for binary operator `%s'", Op);
3272 /* Continue. Wrong code will be generated, but the compiler won't
3273 * break, so this is the best error recovery.
3276 if (ED_IsConstAbs (&Expr2)) {
3277 /* The resulting value is a constant. Scale it. */
3279 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3284 /* Not constant, load into the primary */
3285 LoadExpr (CF_NONE, &Expr2);
3287 /* lhs is a pointer, scale rhs */
3288 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3292 /* Setup the code generator flags */
3293 lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3294 rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3296 /* Convert the type of the lhs to that of the rhs */
3297 g_typecast (lflags, rflags);
3299 /* Output apropriate code depending on the location */
3300 switch (ED_GetLoc (Expr)) {
3303 /* Absolute: numeric address or const */
3304 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3305 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3307 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3312 /* Global variable */
3313 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3314 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3316 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3322 /* Static variable or literal in the literal pool */
3323 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3324 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3326 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3330 case E_LOC_REGISTER:
3331 /* Register variable */
3332 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3333 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3335 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3340 /* Value on the stack */
3341 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3342 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3344 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3349 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3352 /* Expression is a rvalue in the primary now */
3353 ED_MakeRValExpr (Expr);
3358 void hie1 (ExprDesc* Expr)
3359 /* Parse first level of expression hierarchy. */
3362 switch (CurTok.Tok) {
3368 case TOK_PLUS_ASSIGN:
3369 addsubeq (&GenPASGN, Expr, "+=");
3372 case TOK_MINUS_ASSIGN:
3373 addsubeq (&GenSASGN, Expr, "-=");
3376 case TOK_MUL_ASSIGN:
3377 opeq (&GenMASGN, Expr, "*=");
3380 case TOK_DIV_ASSIGN:
3381 opeq (&GenDASGN, Expr, "/=");
3384 case TOK_MOD_ASSIGN:
3385 opeq (&GenMOASGN, Expr, "%=");
3388 case TOK_SHL_ASSIGN:
3389 opeq (&GenSLASGN, Expr, "<<=");
3392 case TOK_SHR_ASSIGN:
3393 opeq (&GenSRASGN, Expr, ">>=");
3396 case TOK_AND_ASSIGN:
3397 opeq (&GenAASGN, Expr, "&=");
3400 case TOK_XOR_ASSIGN:
3401 opeq (&GenXOASGN, Expr, "^=");
3405 opeq (&GenOASGN, Expr, "|=");
3415 void hie0 (ExprDesc *Expr)
3416 /* Parse comma operator. */
3419 while (CurTok.Tok == TOK_COMMA) {
3427 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3428 /* Will evaluate an expression via the given function. If the result is a
3429 * constant, 0 is returned and the value is put in the Expr struct. If the
3430 * result is not constant, LoadExpr is called to bring the value into the
3431 * primary register and 1 is returned.
3435 ExprWithCheck (Func, Expr);
3437 /* Check for a constant expression */
3438 if (ED_IsConstAbs (Expr)) {
3439 /* Constant expression */
3442 /* Not constant, load into the primary */
3443 LoadExpr (Flags, Expr);
3450 void Expression0 (ExprDesc* Expr)
3451 /* Evaluate an expression via hie0 and put the result into the primary register */
3453 ExprWithCheck (hie0, Expr);
3454 LoadExpr (CF_NONE, Expr);
3459 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3460 /* Will evaluate an expression via the given function. If the result is not
3461 * a constant of some sort, a diagnostic will be printed, and the value is
3462 * replaced by a constant one to make sure there are no internal errors that
3463 * result from this input error.
3466 ExprWithCheck (Func, Expr);
3467 if (!ED_IsConst (Expr)) {
3468 Error ("Constant expression expected");
3469 /* To avoid any compiler errors, make the expression a valid const */
3470 ED_MakeConstAbsInt (Expr, 1);
3476 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3477 /* Will evaluate an expression via the given function. If the result is not
3478 * something that may be evaluated in a boolean context, a diagnostic will be
3479 * printed, and the value is replaced by a constant one to make sure there
3480 * are no internal errors that result from this input error.
3483 ExprWithCheck (Func, Expr);
3484 if (!ED_IsBool (Expr)) {
3485 Error ("Boolean expression expected");
3486 /* To avoid any compiler errors, make the expression a valid int */
3487 ED_MakeConstAbsInt (Expr, 1);
3493 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3494 /* Will evaluate an expression via the given function. If the result is not
3495 * a constant numeric integer value, a diagnostic will be printed, and the
3496 * value is replaced by a constant one to make sure there are no internal
3497 * errors that result from this input error.
3500 ExprWithCheck (Func, Expr);
3501 if (!ED_IsConstAbsInt (Expr)) {
3502 Error ("Constant integer expression expected");
3503 /* To avoid any compiler errors, make the expression a valid const */
3504 ED_MakeConstAbsInt (Expr, 1);