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) {
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 ->. */
1110 /* Skip the token and check for an identifier */
1112 if (CurTok.Tok != TOK_IDENT) {
1113 Error ("Identifier expected");
1114 /* Make the expression an integer at address zero */
1115 ED_MakeConstAbs (Expr, 0, type_int);
1119 /* Get the symbol table entry and check for a struct field */
1120 strcpy (Ident, CurTok.Ident);
1122 Field = FindStructField (Expr->Type, Ident);
1124 Error ("Struct/union has no field named `%s'", Ident);
1125 /* Make the expression an integer at address zero */
1126 ED_MakeConstAbs (Expr, 0, type_int);
1130 /* If we have a struct pointer that is an lvalue and not already in the
1131 * primary, load it now.
1133 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1135 /* Load into the primary */
1136 LoadExpr (CF_NONE, Expr);
1138 /* Make it an lvalue expression */
1139 ED_MakeLValExpr (Expr);
1142 /* Set the struct field offset */
1143 Expr->IVal += Field->V.Offs;
1145 /* The type is the type of the field plus any qualifiers from the struct */
1146 if (IsClassStruct (Expr->Type)) {
1147 Q = GetQualifier (Expr->Type);
1149 Q = GetQualifier (Indirect (Expr->Type));
1151 if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1152 Expr->Type = Field->Type;
1154 Expr->Type = TypeDup (Field->Type);
1158 /* An struct member is actually a variable. So the rules for variables
1159 * with respect to the reference type apply: If it's an array, it is
1160 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1161 * but a struct field cannot be a function).
1163 if (IsTypeArray (Expr->Type)) {
1169 /* Make the expression a bit field if necessary */
1170 if (SymIsBitField (Field)) {
1171 ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1177 static void hie11 (ExprDesc *Expr)
1178 /* Handle compound types (structs and arrays) */
1180 /* Name value used in invalid function calls */
1181 static const char IllegalFunc[] = "illegal_function_call";
1183 /* Evaluate the lhs */
1186 /* Check for a rhs */
1187 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1188 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1190 switch (CurTok.Tok) {
1193 /* Array reference */
1198 /* Function call. */
1199 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1200 /* Not a function */
1201 Error ("Illegal function call");
1202 /* Force the type to be a implicitly defined function, one
1203 * returning an int and taking any number of arguments.
1204 * Since we don't have a name, invent one.
1206 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1207 Expr->Name = (long) IllegalFunc;
1209 /* Call the function */
1210 FunctionCall (Expr);
1214 if (!IsClassStruct (Expr->Type)) {
1215 Error ("Struct expected");
1221 /* If we have an array, convert it to pointer to first element */
1222 if (IsTypeArray (Expr->Type)) {
1223 Expr->Type = ArrayToPtr (Expr->Type);
1225 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1226 Error ("Struct pointer expected");
1232 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1240 void Store (ExprDesc* Expr, const Type* StoreType)
1241 /* Store the primary register into the location denoted by Expr. If StoreType
1242 * is given, use this type when storing instead of Expr->Type. If StoreType
1243 * is NULL, use Expr->Type instead.
1248 /* If StoreType was not given, use Expr->Type instead */
1249 if (StoreType == 0) {
1250 StoreType = Expr->Type;
1253 /* Prepare the code generator flags */
1254 Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1256 /* Do the store depending on the location */
1257 switch (ED_GetLoc (Expr)) {
1260 /* Absolute: numeric address or const */
1261 g_putstatic (Flags, Expr->IVal, 0);
1265 /* Global variable */
1266 g_putstatic (Flags, Expr->Name, Expr->IVal);
1271 /* Static variable or literal in the literal pool */
1272 g_putstatic (Flags, Expr->Name, Expr->IVal);
1275 case E_LOC_REGISTER:
1276 /* Register variable */
1277 g_putstatic (Flags, Expr->Name, Expr->IVal);
1281 /* Value on the stack */
1282 g_putlocal (Flags, Expr->IVal, 0);
1286 /* The primary register (value is already there) */
1290 /* An expression in the primary register */
1291 g_putind (Flags, Expr->IVal);
1295 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1298 /* Assume that each one of the stores will invalidate CC */
1299 ED_MarkAsUntested (Expr);
1304 static void PreInc (ExprDesc* Expr)
1305 /* Handle the preincrement operators */
1310 /* Skip the operator token */
1313 /* Evaluate the expression and check that it is an lvalue */
1315 if (!ED_IsLVal (Expr)) {
1316 Error ("Invalid lvalue");
1320 /* We cannot modify const values */
1321 if (IsQualConst (Expr->Type)) {
1322 Error ("Increment of read-only variable");
1325 /* Get the data type */
1326 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1328 /* Get the increment value in bytes */
1329 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1331 /* Check the location of the data */
1332 switch (ED_GetLoc (Expr)) {
1335 /* Absolute: numeric address or const */
1336 g_addeqstatic (Flags, Expr->IVal, 0, Val);
1340 /* Global variable */
1341 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1346 /* Static variable or literal in the literal pool */
1347 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1350 case E_LOC_REGISTER:
1351 /* Register variable */
1352 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1356 /* Value on the stack */
1357 g_addeqlocal (Flags, Expr->IVal, Val);
1361 /* The primary register */
1366 /* An expression in the primary register */
1367 g_addeqind (Flags, Expr->IVal, Val);
1371 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1374 /* Result is an expression, no reference */
1375 ED_MakeRValExpr (Expr);
1380 static void PreDec (ExprDesc* Expr)
1381 /* Handle the predecrement operators */
1386 /* Skip the operator token */
1389 /* Evaluate the expression and check that it is an lvalue */
1391 if (!ED_IsLVal (Expr)) {
1392 Error ("Invalid lvalue");
1396 /* We cannot modify const values */
1397 if (IsQualConst (Expr->Type)) {
1398 Error ("Decrement of read-only variable");
1401 /* Get the data type */
1402 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1404 /* Get the increment value in bytes */
1405 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1407 /* Check the location of the data */
1408 switch (ED_GetLoc (Expr)) {
1411 /* Absolute: numeric address or const */
1412 g_subeqstatic (Flags, Expr->IVal, 0, Val);
1416 /* Global variable */
1417 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1422 /* Static variable or literal in the literal pool */
1423 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1426 case E_LOC_REGISTER:
1427 /* Register variable */
1428 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1432 /* Value on the stack */
1433 g_subeqlocal (Flags, Expr->IVal, Val);
1437 /* The primary register */
1442 /* An expression in the primary register */
1443 g_subeqind (Flags, Expr->IVal, Val);
1447 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1450 /* Result is an expression, no reference */
1451 ED_MakeRValExpr (Expr);
1456 static void PostInc (ExprDesc* Expr)
1457 /* Handle the postincrement operator */
1463 /* The expression to increment must be an lvalue */
1464 if (!ED_IsLVal (Expr)) {
1465 Error ("Invalid lvalue");
1469 /* We cannot modify const values */
1470 if (IsQualConst (Expr->Type)) {
1471 Error ("Increment of read-only variable");
1474 /* Get the data type */
1475 Flags = TypeOf (Expr->Type);
1477 /* Push the address if needed */
1480 /* Fetch the value and save it (since it's the result of the expression) */
1481 LoadExpr (CF_NONE, Expr);
1482 g_save (Flags | CF_FORCECHAR);
1484 /* If we have a pointer expression, increment by the size of the type */
1485 if (IsTypePtr (Expr->Type)) {
1486 g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1488 g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1491 /* Store the result back */
1494 /* Restore the original value in the primary register */
1495 g_restore (Flags | CF_FORCECHAR);
1497 /* The result is always an expression, no reference */
1498 ED_MakeRValExpr (Expr);
1503 static void PostDec (ExprDesc* Expr)
1504 /* Handle the postdecrement operator */
1510 /* The expression to increment must be an lvalue */
1511 if (!ED_IsLVal (Expr)) {
1512 Error ("Invalid lvalue");
1516 /* We cannot modify const values */
1517 if (IsQualConst (Expr->Type)) {
1518 Error ("Decrement of read-only variable");
1521 /* Get the data type */
1522 Flags = TypeOf (Expr->Type);
1524 /* Push the address if needed */
1527 /* Fetch the value and save it (since it's the result of the expression) */
1528 LoadExpr (CF_NONE, Expr);
1529 g_save (Flags | CF_FORCECHAR);
1531 /* If we have a pointer expression, increment by the size of the type */
1532 if (IsTypePtr (Expr->Type)) {
1533 g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1535 g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1538 /* Store the result back */
1541 /* Restore the original value in the primary register */
1542 g_restore (Flags | CF_FORCECHAR);
1544 /* The result is always an expression, no reference */
1545 ED_MakeRValExpr (Expr);
1550 static void UnaryOp (ExprDesc* Expr)
1551 /* Handle unary -/+ and ~ */
1555 /* Remember the operator token and skip it */
1556 token_t Tok = CurTok.Tok;
1559 /* Get the expression */
1562 /* We can only handle integer types */
1563 if (!IsClassInt (Expr->Type)) {
1564 Error ("Argument must have integer type");
1565 ED_MakeConstAbsInt (Expr, 1);
1568 /* Check for a constant expression */
1569 if (ED_IsConstAbs (Expr)) {
1570 /* Value is constant */
1572 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1573 case TOK_PLUS: break;
1574 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1575 default: Internal ("Unexpected token: %d", Tok);
1578 /* Value is not constant */
1579 LoadExpr (CF_NONE, Expr);
1581 /* Get the type of the expression */
1582 Flags = TypeOf (Expr->Type);
1584 /* Handle the operation */
1586 case TOK_MINUS: g_neg (Flags); break;
1587 case TOK_PLUS: break;
1588 case TOK_COMP: g_com (Flags); break;
1589 default: Internal ("Unexpected token: %d", Tok);
1592 /* The result is a rvalue in the primary */
1593 ED_MakeRValExpr (Expr);
1599 void hie10 (ExprDesc* Expr)
1600 /* Handle ++, --, !, unary - etc. */
1604 switch (CurTok.Tok) {
1622 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1623 /* Constant expression */
1624 Expr->IVal = !Expr->IVal;
1626 g_bneg (TypeOf (Expr->Type));
1627 ED_MakeRValExpr (Expr);
1628 ED_TestDone (Expr); /* bneg will set cc */
1634 ExprWithCheck (hie10, Expr);
1635 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1636 /* Not a const, load it into the primary and make it a
1639 LoadExpr (CF_NONE, Expr);
1640 ED_MakeRValExpr (Expr);
1642 /* If the expression is already a pointer to function, the
1643 * additional dereferencing operator must be ignored. A function
1644 * itself is represented as "pointer to function", so any number
1645 * of dereference operators is legal, since the result will
1646 * always be converted to "pointer to function".
1648 if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1649 /* Expression not storable */
1652 if (IsClassPtr (Expr->Type)) {
1653 Expr->Type = Indirect (Expr->Type);
1655 Error ("Illegal indirection");
1657 /* The * operator yields an lvalue */
1664 ExprWithCheck (hie10, Expr);
1665 /* The & operator may be applied to any lvalue, and it may be
1666 * applied to functions, even if they're no lvalues.
1668 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1669 Error ("Illegal address");
1671 if (ED_IsBitField (Expr)) {
1672 Error ("Cannot take address of bit-field");
1673 /* Do it anyway, just to avoid further warnings */
1674 Expr->Flags &= ~E_BITFIELD;
1676 Expr->Type = PointerTo (Expr->Type);
1677 /* The & operator yields an rvalue */
1684 if (TypeSpecAhead ()) {
1687 Size = CheckedSizeOf (ParseType (T));
1690 /* Remember the output queue pointer */
1694 Size = CheckedSizeOf (Expr->Type);
1695 /* Remove any generated code */
1698 ED_MakeConstAbs (Expr, Size, type_size_t);
1699 ED_MarkAsUntested (Expr);
1703 if (TypeSpecAhead ()) {
1713 /* Handle post increment */
1714 switch (CurTok.Tok) {
1715 case TOK_INC: PostInc (Expr); break;
1716 case TOK_DEC: PostDec (Expr); break;
1727 static void hie_internal (const GenDesc* Ops, /* List of generators */
1729 void (*hienext) (ExprDesc*),
1731 /* Helper function */
1737 token_t Tok; /* The operator token */
1738 unsigned ltype, type;
1739 int rconst; /* Operand is a constant */
1745 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1747 /* Tell the caller that we handled it's ops */
1750 /* All operators that call this function expect an int on the lhs */
1751 if (!IsClassInt (Expr->Type)) {
1752 Error ("Integer expression expected");
1753 /* To avoid further errors, make Expr a valid int expression */
1754 ED_MakeConstAbsInt (Expr, 1);
1757 /* Remember the operator token, then skip it */
1761 /* Get the lhs on stack */
1762 GetCodePos (&Mark1);
1763 ltype = TypeOf (Expr->Type);
1764 if (ED_IsConstAbs (Expr)) {
1765 /* Constant value */
1766 GetCodePos (&Mark2);
1767 g_push (ltype | CF_CONST, Expr->IVal);
1769 /* Value not constant */
1770 LoadExpr (CF_NONE, Expr);
1771 GetCodePos (&Mark2);
1775 /* Get the right hand side */
1776 MarkedExprWithCheck (hienext, &Expr2);
1778 /* Check for a constant expression */
1779 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1781 /* Not constant, load into the primary */
1782 LoadExpr (CF_NONE, &Expr2);
1785 /* Check the type of the rhs */
1786 if (!IsClassInt (Expr2.Type)) {
1787 Error ("Integer expression expected");
1790 /* Check for const operands */
1791 if (ED_IsConstAbs (Expr) && rconst) {
1793 /* Both operands are constant, remove the generated code */
1794 RemoveCode (&Mark1);
1796 /* Get the type of the result */
1797 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1799 /* Handle the op differently for signed and unsigned types */
1800 if (IsSignSigned (Expr->Type)) {
1802 /* Evaluate the result for signed operands */
1803 signed long Val1 = Expr->IVal;
1804 signed long Val2 = Expr2.IVal;
1807 Expr->IVal = (Val1 | Val2);
1810 Expr->IVal = (Val1 ^ Val2);
1813 Expr->IVal = (Val1 & Val2);
1816 Expr->IVal = (Val1 * Val2);
1820 Error ("Division by zero");
1821 Expr->IVal = 0x7FFFFFFF;
1823 Expr->IVal = (Val1 / Val2);
1828 Error ("Modulo operation with zero");
1831 Expr->IVal = (Val1 % Val2);
1835 Internal ("hie_internal: got token 0x%X\n", Tok);
1839 /* Evaluate the result for unsigned operands */
1840 unsigned long Val1 = Expr->IVal;
1841 unsigned long Val2 = Expr2.IVal;
1844 Expr->IVal = (Val1 | Val2);
1847 Expr->IVal = (Val1 ^ Val2);
1850 Expr->IVal = (Val1 & Val2);
1853 Expr->IVal = (Val1 * Val2);
1857 Error ("Division by zero");
1858 Expr->IVal = 0xFFFFFFFF;
1860 Expr->IVal = (Val1 / Val2);
1865 Error ("Modulo operation with zero");
1868 Expr->IVal = (Val1 % Val2);
1872 Internal ("hie_internal: got token 0x%X\n", Tok);
1878 /* If the right hand side is constant, and the generator function
1879 * expects the lhs in the primary, remove the push of the primary
1882 unsigned rtype = TypeOf (Expr2.Type);
1885 /* Second value is constant - check for div */
1888 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1889 Error ("Division by zero");
1890 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1891 Error ("Modulo operation with zero");
1893 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1894 RemoveCode (&Mark2);
1895 ltype |= CF_REG; /* Value is in register */
1899 /* Determine the type of the operation result. */
1900 type |= g_typeadjust (ltype, rtype);
1901 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1904 Gen->Func (type, Expr2.IVal);
1906 /* We have a rvalue in the primary now */
1907 ED_MakeRValExpr (Expr);
1914 static void hie_compare (const GenDesc* Ops, /* List of generators */
1916 void (*hienext) (ExprDesc*))
1917 /* Helper function for the compare operators */
1924 token_t Tok; /* The operator token */
1926 int rconst; /* Operand is a constant */
1929 GetCodePos (&Mark0);
1932 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1934 /* Remember the generator function */
1935 void (*GenFunc) (unsigned, unsigned long) = Gen->Func;
1937 /* Remember the operator token, then skip it */
1941 /* Get the lhs on stack */
1942 GetCodePos (&Mark1);
1943 ltype = TypeOf (Expr->Type);
1944 if (ED_IsConstAbs (Expr)) {
1945 /* Constant value */
1946 GetCodePos (&Mark2);
1947 g_push (ltype | CF_CONST, Expr->IVal);
1949 /* Value not constant */
1950 LoadExpr (CF_NONE, Expr);
1951 GetCodePos (&Mark2);
1955 /* Get the right hand side */
1956 MarkedExprWithCheck (hienext, &Expr2);
1958 /* Check for a constant expression */
1959 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1961 /* Not constant, load into the primary */
1962 LoadExpr (CF_NONE, &Expr2);
1965 /* Make sure, the types are compatible */
1966 if (IsClassInt (Expr->Type)) {
1967 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1968 Error ("Incompatible types");
1970 } else if (IsClassPtr (Expr->Type)) {
1971 if (IsClassPtr (Expr2.Type)) {
1972 /* Both pointers are allowed in comparison if they point to
1973 * the same type, or if one of them is a void pointer.
1975 Type* left = Indirect (Expr->Type);
1976 Type* right = Indirect (Expr2.Type);
1977 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
1978 /* Incomatible pointers */
1979 Error ("Incompatible types");
1981 } else if (!ED_IsNullPtr (&Expr2)) {
1982 Error ("Incompatible types");
1986 /* Check for const operands */
1987 if (ED_IsConstAbs (Expr) && rconst) {
1989 /* If the result is constant, this is suspicious when not in
1990 * preprocessor mode.
1992 WarnConstCompareResult ();
1994 /* Both operands are constant, remove the generated code */
1995 RemoveCode (&Mark1);
1997 /* Determine if this is a signed or unsigned compare */
1998 if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
1999 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
2001 /* Evaluate the result for signed operands */
2002 signed long Val1 = Expr->IVal;
2003 signed long Val2 = Expr2.IVal;
2005 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2006 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2007 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2008 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2009 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2010 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2011 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2016 /* Evaluate the result for unsigned operands */
2017 unsigned long Val1 = Expr->IVal;
2018 unsigned long Val2 = Expr2.IVal;
2020 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2021 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2022 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2023 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2024 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2025 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2026 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2032 /* Determine the signedness of the operands */
2033 int LeftSigned = IsSignSigned (Expr->Type);
2034 int RightSigned = IsSignSigned (Expr2.Type);
2036 /* If the right hand side is constant, and the generator function
2037 * expects the lhs in the primary, remove the push of the primary
2043 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2044 RemoveCode (&Mark2);
2045 ltype |= CF_REG; /* Value is in register */
2049 /* Determine the type of the operation. */
2050 if (IsTypeChar (Expr->Type) && rconst) {
2052 /* Left side is unsigned char, right side is constant.
2053 * Determine the minimum and maximum values
2055 int LeftMin, LeftMax;
2063 /* An integer value is always represented as a signed in the
2064 * ExprDesc structure. This may lead to false results below,
2065 * if it is actually unsigned, but interpreted as signed
2066 * because of the representation. Fortunately, in this case,
2067 * the actual value doesn't matter, since it's always greater
2068 * than what can be represented in a char. So correct the
2069 * value accordingly.
2071 if (!RightSigned && Expr2.IVal < 0) {
2072 /* Correct the value so it is an unsigned. It will then
2073 * anyway match one of the cases below.
2075 Expr2.IVal = LeftMax + 1;
2078 /* Comparing a char against a constant may have a constant
2084 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2085 ED_MakeConstAbsInt (Expr, 0);
2086 WarnConstCompareResult ();
2087 RemoveCode (&Mark0);
2093 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2094 ED_MakeConstAbsInt (Expr, 1);
2095 WarnConstCompareResult ();
2096 RemoveCode (&Mark0);
2102 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2103 ED_MakeConstAbsInt (Expr, Expr2.IVal > LeftMax);
2104 WarnConstCompareResult ();
2105 RemoveCode (&Mark0);
2111 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2112 ED_MakeConstAbsInt (Expr, Expr2.IVal >= LeftMax);
2113 WarnConstCompareResult ();
2114 RemoveCode (&Mark0);
2120 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2121 ED_MakeConstAbsInt (Expr, Expr2.IVal <= LeftMin);
2122 WarnConstCompareResult ();
2123 RemoveCode (&Mark0);
2129 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2130 ED_MakeConstAbsInt (Expr, Expr2.IVal < LeftMin);
2131 WarnConstCompareResult ();
2132 RemoveCode (&Mark0);
2138 Internal ("hie_compare: got token 0x%X\n", Tok);
2141 /* If the result is not already constant (as evaluated in the
2142 * switch above), we can execute the operation as a char op,
2143 * since the right side constant is in a valid range.
2145 flags |= (CF_CHAR | CF_FORCECHAR);
2147 flags |= CF_UNSIGNED;
2150 } else if (IsTypeChar (Expr->Type) && IsTypeChar (Expr2.Type) &&
2151 GetSignedness (Expr->Type) == GetSignedness (Expr2.Type)) {
2153 /* Both are chars with the same signedness. We can encode the
2154 * operation as a char operation.
2158 flags |= CF_FORCECHAR;
2161 flags |= CF_UNSIGNED;
2164 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2165 flags |= g_typeadjust (ltype, rtype);
2168 /* If the left side is an unsigned and the right is a constant,
2169 * we may be able to change the compares to something more
2172 if (!LeftSigned && rconst) {
2177 if (Expr2.IVal == 1) {
2178 /* An unsigned compare to one means that the value
2187 if (Expr2.IVal == 0) {
2188 /* An unsigned compare to zero means that the value
2196 if (Expr2.IVal == 1) {
2197 /* An unsigned compare to one means that the value
2206 if (Expr2.IVal == 0) {
2207 /* An unsigned compare to zero means that the value
2222 GenFunc (flags, Expr2.IVal);
2224 /* The result is an rvalue in the primary */
2225 ED_MakeRValExpr (Expr);
2228 /* Result type is always int */
2229 Expr->Type = type_int;
2231 Done: /* Condition codes are set */
2238 static void hie9 (ExprDesc *Expr)
2239 /* Process * and / operators. */
2241 static const GenDesc hie9_ops[] = {
2242 { TOK_STAR, GEN_NOPUSH, g_mul },
2243 { TOK_DIV, GEN_NOPUSH, g_div },
2244 { TOK_MOD, GEN_NOPUSH, g_mod },
2245 { TOK_INVALID, 0, 0 }
2249 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2254 static void parseadd (ExprDesc* Expr)
2255 /* Parse an expression with the binary plus operator. Expr contains the
2256 * unprocessed left hand side of the expression and will contain the
2257 * result of the expression on return.
2261 unsigned flags; /* Operation flags */
2262 CodeMark Mark; /* Remember code position */
2263 Type* lhst; /* Type of left hand side */
2264 Type* rhst; /* Type of right hand side */
2267 /* Skip the PLUS token */
2270 /* Get the left hand side type, initialize operation flags */
2274 /* Check for constness on both sides */
2275 if (ED_IsConst (Expr)) {
2277 /* The left hand side is a constant of some sort. Good. Get rhs */
2279 if (ED_IsConstAbs (&Expr2)) {
2281 /* Right hand side is a constant numeric value. Get the rhs type */
2284 /* Both expressions are constants. Check for pointer arithmetic */
2285 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2286 /* Left is pointer, right is int, must scale rhs */
2287 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2288 /* Result type is a pointer */
2289 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2290 /* Left is int, right is pointer, must scale lhs */
2291 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2292 /* Result type is a pointer */
2293 Expr->Type = Expr2.Type;
2294 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2295 /* Integer addition */
2296 Expr->IVal += Expr2.IVal;
2297 typeadjust (Expr, &Expr2, 1);
2300 Error ("Invalid operands for binary operator `+'");
2305 /* lhs is a constant and rhs is not constant. Load rhs into
2308 LoadExpr (CF_NONE, &Expr2);
2310 /* Beware: The check above (for lhs) lets not only pass numeric
2311 * constants, but also constant addresses (labels), maybe even
2312 * with an offset. We have to check for that here.
2315 /* First, get the rhs type. */
2319 if (ED_IsLocAbs (Expr)) {
2320 /* A numerical constant */
2323 /* Constant address label */
2324 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2327 /* Check for pointer arithmetic */
2328 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2329 /* Left is pointer, right is int, must scale rhs */
2330 g_scale (CF_INT, CheckedPSizeOf (lhst));
2331 /* Operate on pointers, result type is a pointer */
2333 /* Generate the code for the add */
2334 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2335 /* Numeric constant */
2336 g_inc (flags, Expr->IVal);
2338 /* Constant address */
2339 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2341 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2343 /* Left is int, right is pointer, must scale lhs. */
2344 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2346 /* Operate on pointers, result type is a pointer */
2348 Expr->Type = Expr2.Type;
2350 /* Since we do already have rhs in the primary, if lhs is
2351 * not a numeric constant, and the scale factor is not one
2352 * (no scaling), we must take the long way over the stack.
2354 if (ED_IsLocAbs (Expr)) {
2355 /* Numeric constant, scale lhs */
2356 Expr->IVal *= ScaleFactor;
2357 /* Generate the code for the add */
2358 g_inc (flags, Expr->IVal);
2359 } else if (ScaleFactor == 1) {
2360 /* Constant address but no need to scale */
2361 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2363 /* Constant address that must be scaled */
2364 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2365 g_getimmed (flags, Expr->Name, Expr->IVal);
2366 g_scale (CF_PTR, ScaleFactor);
2369 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2370 /* Integer addition */
2371 flags |= typeadjust (Expr, &Expr2, 1);
2372 /* Generate the code for the add */
2373 if (ED_IsLocAbs (Expr)) {
2374 /* Numeric constant */
2375 g_inc (flags, Expr->IVal);
2377 /* Constant address */
2378 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2382 Error ("Invalid operands for binary operator `+'");
2386 /* Result is a rvalue in primary register */
2387 ED_MakeRValExpr (Expr);
2392 /* Left hand side is not constant. Get the value onto the stack. */
2393 LoadExpr (CF_NONE, Expr); /* --> primary register */
2395 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2397 /* Evaluate the rhs */
2398 MarkedExprWithCheck (hie9, &Expr2);
2400 /* Check for a constant rhs expression */
2401 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2403 /* Right hand side is a constant. Get the rhs type */
2406 /* Remove pushed value from stack */
2409 /* Check for pointer arithmetic */
2410 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2411 /* Left is pointer, right is int, must scale rhs */
2412 Expr2.IVal *= CheckedPSizeOf (lhst);
2413 /* Operate on pointers, result type is a pointer */
2415 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2416 /* Left is int, right is pointer, must scale lhs (ptr only) */
2417 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2418 /* Operate on pointers, result type is a pointer */
2420 Expr->Type = Expr2.Type;
2421 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2422 /* Integer addition */
2423 flags = typeadjust (Expr, &Expr2, 1);
2426 Error ("Invalid operands for binary operator `+'");
2430 /* Generate code for the add */
2431 g_inc (flags | CF_CONST, Expr2.IVal);
2435 /* Not constant, load into the primary */
2436 LoadExpr (CF_NONE, &Expr2);
2438 /* lhs and rhs are not constant. Get the rhs type. */
2441 /* Check for pointer arithmetic */
2442 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2443 /* Left is pointer, right is int, must scale rhs */
2444 g_scale (CF_INT, CheckedPSizeOf (lhst));
2445 /* Operate on pointers, result type is a pointer */
2447 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2448 /* Left is int, right is pointer, must scale lhs */
2449 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2450 g_swap (CF_INT); /* Swap TOS and primary */
2451 g_scale (CF_INT, CheckedPSizeOf (rhst));
2452 /* Operate on pointers, result type is a pointer */
2454 Expr->Type = Expr2.Type;
2455 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2456 /* Integer addition. Note: Result is never constant.
2457 * Problem here is that typeadjust does not know if the
2458 * variable is an rvalue or lvalue, so if both operands
2459 * are dereferenced constant numeric addresses, typeadjust
2460 * thinks the operation works on constants. Removing
2461 * CF_CONST here means handling the symptoms, however, the
2462 * whole parser is such a mess that I fear to break anything
2463 * when trying to apply another solution.
2465 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2468 Error ("Invalid operands for binary operator `+'");
2472 /* Generate code for the add */
2477 /* Result is a rvalue in primary register */
2478 ED_MakeRValExpr (Expr);
2481 /* Condition codes not set */
2482 ED_MarkAsUntested (Expr);
2488 static void parsesub (ExprDesc* Expr)
2489 /* Parse an expression with the binary minus operator. Expr contains the
2490 * unprocessed left hand side of the expression and will contain the
2491 * result of the expression on return.
2495 unsigned flags; /* Operation flags */
2496 Type* lhst; /* Type of left hand side */
2497 Type* rhst; /* Type of right hand side */
2498 CodeMark Mark1; /* Save position of output queue */
2499 CodeMark Mark2; /* Another position in the queue */
2500 int rscale; /* Scale factor for the result */
2503 /* Skip the MINUS token */
2506 /* Get the left hand side type, initialize operation flags */
2508 rscale = 1; /* Scale by 1, that is, don't scale */
2510 /* Remember the output queue position, then bring the value onto the stack */
2511 GetCodePos (&Mark1);
2512 LoadExpr (CF_NONE, Expr); /* --> primary register */
2513 GetCodePos (&Mark2);
2514 g_push (TypeOf (lhst), 0); /* --> stack */
2516 /* Parse the right hand side */
2517 MarkedExprWithCheck (hie9, &Expr2);
2519 /* Check for a constant rhs expression */
2520 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2522 /* The right hand side is constant. Get the rhs type. */
2525 /* Check left hand side */
2526 if (ED_IsConstAbs (Expr)) {
2528 /* Both sides are constant, remove generated code */
2529 RemoveCode (&Mark1);
2531 /* Check for pointer arithmetic */
2532 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2533 /* Left is pointer, right is int, must scale rhs */
2534 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2535 /* Operate on pointers, result type is a pointer */
2536 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2537 /* Left is pointer, right is pointer, must scale result */
2538 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2539 Error ("Incompatible pointer types");
2541 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2542 CheckedPSizeOf (lhst);
2544 /* Operate on pointers, result type is an integer */
2545 Expr->Type = type_int;
2546 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2547 /* Integer subtraction */
2548 typeadjust (Expr, &Expr2, 1);
2549 Expr->IVal -= Expr2.IVal;
2552 Error ("Invalid operands for binary operator `-'");
2555 /* Result is constant, condition codes not set */
2556 ED_MarkAsUntested (Expr);
2560 /* Left hand side is not constant, right hand side is.
2561 * Remove pushed value from stack.
2563 RemoveCode (&Mark2);
2565 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2566 /* Left is pointer, right is int, must scale rhs */
2567 Expr2.IVal *= CheckedPSizeOf (lhst);
2568 /* Operate on pointers, result type is a pointer */
2570 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2571 /* Left is pointer, right is pointer, must scale result */
2572 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2573 Error ("Incompatible pointer types");
2575 rscale = CheckedPSizeOf (lhst);
2577 /* Operate on pointers, result type is an integer */
2579 Expr->Type = type_int;
2580 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2581 /* Integer subtraction */
2582 flags = typeadjust (Expr, &Expr2, 1);
2585 Error ("Invalid operands for binary operator `-'");
2589 /* Do the subtraction */
2590 g_dec (flags | CF_CONST, Expr2.IVal);
2592 /* If this was a pointer subtraction, we must scale the result */
2594 g_scale (flags, -rscale);
2597 /* Result is a rvalue in the primary register */
2598 ED_MakeRValExpr (Expr);
2599 ED_MarkAsUntested (Expr);
2605 /* Not constant, load into the primary */
2606 LoadExpr (CF_NONE, &Expr2);
2608 /* Right hand side is not constant. Get the rhs type. */
2611 /* Check for pointer arithmetic */
2612 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2613 /* Left is pointer, right is int, must scale rhs */
2614 g_scale (CF_INT, CheckedPSizeOf (lhst));
2615 /* Operate on pointers, result type is a pointer */
2617 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2618 /* Left is pointer, right is pointer, must scale result */
2619 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2620 Error ("Incompatible pointer types");
2622 rscale = CheckedPSizeOf (lhst);
2624 /* Operate on pointers, result type is an integer */
2626 Expr->Type = type_int;
2627 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2628 /* Integer subtraction. If the left hand side descriptor says that
2629 * the lhs is const, we have to remove this mark, since this is no
2630 * longer true, lhs is on stack instead.
2632 if (ED_IsLocAbs (Expr)) {
2633 ED_MakeRValExpr (Expr);
2635 /* Adjust operand types */
2636 flags = typeadjust (Expr, &Expr2, 0);
2639 Error ("Invalid operands for binary operator `-'");
2643 /* Generate code for the sub (the & is a hack here) */
2644 g_sub (flags & ~CF_CONST, 0);
2646 /* If this was a pointer subtraction, we must scale the result */
2648 g_scale (flags, -rscale);
2651 /* Result is a rvalue in the primary register */
2652 ED_MakeRValExpr (Expr);
2653 ED_MarkAsUntested (Expr);
2659 void hie8 (ExprDesc* Expr)
2660 /* Process + and - binary operators. */
2663 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2664 if (CurTok.Tok == TOK_PLUS) {
2674 static void hie6 (ExprDesc* Expr)
2675 /* Handle greater-than type comparators */
2677 static const GenDesc hie6_ops [] = {
2678 { TOK_LT, GEN_NOPUSH, g_lt },
2679 { TOK_LE, GEN_NOPUSH, g_le },
2680 { TOK_GE, GEN_NOPUSH, g_ge },
2681 { TOK_GT, GEN_NOPUSH, g_gt },
2682 { TOK_INVALID, 0, 0 }
2684 hie_compare (hie6_ops, Expr, ShiftExpr);
2689 static void hie5 (ExprDesc* Expr)
2690 /* Handle == and != */
2692 static const GenDesc hie5_ops[] = {
2693 { TOK_EQ, GEN_NOPUSH, g_eq },
2694 { TOK_NE, GEN_NOPUSH, g_ne },
2695 { TOK_INVALID, 0, 0 }
2697 hie_compare (hie5_ops, Expr, hie6);
2702 static void hie4 (ExprDesc* Expr)
2703 /* Handle & (bitwise and) */
2705 static const GenDesc hie4_ops[] = {
2706 { TOK_AND, GEN_NOPUSH, g_and },
2707 { TOK_INVALID, 0, 0 }
2711 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2716 static void hie3 (ExprDesc* Expr)
2717 /* Handle ^ (bitwise exclusive or) */
2719 static const GenDesc hie3_ops[] = {
2720 { TOK_XOR, GEN_NOPUSH, g_xor },
2721 { TOK_INVALID, 0, 0 }
2725 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2730 static void hie2 (ExprDesc* Expr)
2731 /* Handle | (bitwise or) */
2733 static const GenDesc hie2_ops[] = {
2734 { TOK_OR, GEN_NOPUSH, g_or },
2735 { TOK_INVALID, 0, 0 }
2739 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2744 static void hieAndPP (ExprDesc* Expr)
2745 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2746 * called recursively from the preprocessor.
2751 ConstAbsIntExpr (hie2, Expr);
2752 while (CurTok.Tok == TOK_BOOL_AND) {
2758 ConstAbsIntExpr (hie2, &Expr2);
2760 /* Combine the two */
2761 Expr->IVal = (Expr->IVal && Expr2.IVal);
2767 static void hieOrPP (ExprDesc *Expr)
2768 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2769 * called recursively from the preprocessor.
2774 ConstAbsIntExpr (hieAndPP, Expr);
2775 while (CurTok.Tok == TOK_BOOL_OR) {
2781 ConstAbsIntExpr (hieAndPP, &Expr2);
2783 /* Combine the two */
2784 Expr->IVal = (Expr->IVal || Expr2.IVal);
2790 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2791 /* Process "exp && exp" */
2797 if (CurTok.Tok == TOK_BOOL_AND) {
2799 /* Tell our caller that we're evaluating a boolean */
2802 /* Get a label that we will use for false expressions */
2803 FalseLab = GetLocalLabel ();
2805 /* If the expr hasn't set condition codes, set the force-test flag */
2806 if (!ED_IsTested (Expr)) {
2807 ED_MarkForTest (Expr);
2810 /* Load the value */
2811 LoadExpr (CF_FORCECHAR, Expr);
2813 /* Generate the jump */
2814 g_falsejump (CF_NONE, FalseLab);
2816 /* Parse more boolean and's */
2817 while (CurTok.Tok == TOK_BOOL_AND) {
2824 if (!ED_IsTested (&Expr2)) {
2825 ED_MarkForTest (&Expr2);
2827 LoadExpr (CF_FORCECHAR, &Expr2);
2829 /* Do short circuit evaluation */
2830 if (CurTok.Tok == TOK_BOOL_AND) {
2831 g_falsejump (CF_NONE, FalseLab);
2833 /* Last expression - will evaluate to true */
2834 g_truejump (CF_NONE, TrueLab);
2838 /* Define the false jump label here */
2839 g_defcodelabel (FalseLab);
2841 /* The result is an rvalue in primary */
2842 ED_MakeRValExpr (Expr);
2843 ED_TestDone (Expr); /* Condition codes are set */
2849 static void hieOr (ExprDesc *Expr)
2850 /* Process "exp || exp". */
2853 int BoolOp = 0; /* Did we have a boolean op? */
2854 int AndOp; /* Did we have a && operation? */
2855 unsigned TrueLab; /* Jump to this label if true */
2859 TrueLab = GetLocalLabel ();
2861 /* Call the next level parser */
2862 hieAnd (Expr, TrueLab, &BoolOp);
2864 /* Any boolean or's? */
2865 if (CurTok.Tok == TOK_BOOL_OR) {
2867 /* If the expr hasn't set condition codes, set the force-test flag */
2868 if (!ED_IsTested (Expr)) {
2869 ED_MarkForTest (Expr);
2872 /* Get first expr */
2873 LoadExpr (CF_FORCECHAR, Expr);
2875 /* For each expression jump to TrueLab if true. Beware: If we
2876 * had && operators, the jump is already in place!
2879 g_truejump (CF_NONE, TrueLab);
2882 /* Remember that we had a boolean op */
2885 /* while there's more expr */
2886 while (CurTok.Tok == TOK_BOOL_OR) {
2893 hieAnd (&Expr2, TrueLab, &AndOp);
2894 if (!ED_IsTested (&Expr2)) {
2895 ED_MarkForTest (&Expr2);
2897 LoadExpr (CF_FORCECHAR, &Expr2);
2899 /* If there is more to come, add shortcut boolean eval. */
2900 g_truejump (CF_NONE, TrueLab);
2904 /* The result is an rvalue in primary */
2905 ED_MakeRValExpr (Expr);
2906 ED_TestDone (Expr); /* Condition codes are set */
2909 /* If we really had boolean ops, generate the end sequence */
2911 DoneLab = GetLocalLabel ();
2912 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2913 g_falsejump (CF_NONE, DoneLab);
2914 g_defcodelabel (TrueLab);
2915 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2916 g_defcodelabel (DoneLab);
2922 static void hieQuest (ExprDesc* Expr)
2923 /* Parse the ternary operator */
2927 CodeMark TrueCodeEnd;
2928 ExprDesc Expr2; /* Expression 2 */
2929 ExprDesc Expr3; /* Expression 3 */
2930 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
2931 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
2932 Type* ResultType; /* Type of result */
2935 /* Call the lower level eval routine */
2936 if (Preprocessing) {
2942 /* Check if it's a ternary expression */
2943 if (CurTok.Tok == TOK_QUEST) {
2945 if (!ED_IsTested (Expr)) {
2946 /* Condition codes not set, request a test */
2947 ED_MarkForTest (Expr);
2949 LoadExpr (CF_NONE, Expr);
2950 FalseLab = GetLocalLabel ();
2951 g_falsejump (CF_NONE, FalseLab);
2953 /* Parse second expression. Remember for later if it is a NULL pointer
2954 * expression, then load it into the primary.
2956 ExprWithCheck (hie1, &Expr2);
2957 Expr2IsNULL = ED_IsNullPtr (&Expr2);
2958 if (!IsTypeVoid (Expr2.Type)) {
2959 /* Load it into the primary */
2960 LoadExpr (CF_NONE, &Expr2);
2961 ED_MakeRValExpr (&Expr2);
2962 Expr2.Type = PtrConversion (Expr2.Type);
2965 /* Remember the current code position */
2966 GetCodePos (&TrueCodeEnd);
2968 /* Jump around the evaluation of the third expression */
2969 TrueLab = GetLocalLabel ();
2973 /* Jump here if the first expression was false */
2974 g_defcodelabel (FalseLab);
2976 /* Parse third expression. Remember for later if it is a NULL pointer
2977 * expression, then load it into the primary.
2979 ExprWithCheck (hie1, &Expr3);
2980 Expr3IsNULL = ED_IsNullPtr (&Expr3);
2981 if (!IsTypeVoid (Expr3.Type)) {
2982 /* Load it into the primary */
2983 LoadExpr (CF_NONE, &Expr3);
2984 ED_MakeRValExpr (&Expr3);
2985 Expr3.Type = PtrConversion (Expr3.Type);
2988 /* Check if any conversions are needed, if so, do them.
2989 * Conversion rules for ?: expression are:
2990 * - if both expressions are int expressions, default promotion
2991 * rules for ints apply.
2992 * - if both expressions are pointers of the same type, the
2993 * result of the expression is of this type.
2994 * - if one of the expressions is a pointer and the other is
2995 * a zero constant, the resulting type is that of the pointer
2997 * - if both expressions are void expressions, the result is of
2999 * - all other cases are flagged by an error.
3001 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
3003 CodeMark CvtCodeStart;
3004 CodeMark CvtCodeEnd;
3007 /* Get common type */
3008 ResultType = promoteint (Expr2.Type, Expr3.Type);
3010 /* Convert the third expression to this type if needed */
3011 TypeConversion (&Expr3, ResultType);
3013 /* Emit conversion code for the second expression, but remember
3014 * where it starts end ends.
3016 GetCodePos (&CvtCodeStart);
3017 TypeConversion (&Expr2, ResultType);
3018 GetCodePos (&CvtCodeEnd);
3020 /* If we had conversion code, move it to the right place */
3021 if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
3022 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
3025 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
3026 /* Must point to same type */
3027 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
3028 Error ("Incompatible pointer types");
3030 /* Result has the common type */
3031 ResultType = Expr2.Type;
3032 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
3033 /* Result type is pointer, no cast needed */
3034 ResultType = Expr2.Type;
3035 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
3036 /* Result type is pointer, no cast needed */
3037 ResultType = Expr3.Type;
3038 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
3039 /* Result type is void */
3040 ResultType = Expr3.Type;
3042 Error ("Incompatible types");
3043 ResultType = Expr2.Type; /* Doesn't matter here */
3046 /* Define the final label */
3047 g_defcodelabel (TrueLab);
3049 /* Setup the target expression */
3050 ED_MakeRValExpr (Expr);
3051 Expr->Type = ResultType;
3057 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
3058 /* Process "op=" operators. */
3065 /* op= can only be used with lvalues */
3066 if (!ED_IsLVal (Expr)) {
3067 Error ("Invalid lvalue in assignment");
3071 /* The left side must not be const qualified */
3072 if (IsQualConst (Expr->Type)) {
3073 Error ("Assignment to const");
3076 /* There must be an integer or pointer on the left side */
3077 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3078 Error ("Invalid left operand type");
3079 /* Continue. Wrong code will be generated, but the compiler won't
3080 * break, so this is the best error recovery.
3084 /* Skip the operator token */
3087 /* Determine the type of the lhs */
3088 flags = TypeOf (Expr->Type);
3089 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
3091 /* Get the lhs address on stack (if needed) */
3094 /* Fetch the lhs into the primary register if needed */
3095 LoadExpr (CF_NONE, Expr);
3097 /* Bring the lhs on stack */
3101 /* Evaluate the rhs */
3102 MarkedExprWithCheck (hie1, &Expr2);
3104 /* The rhs must be an integer (or a float, but we don't support that yet */
3105 if (!IsClassInt (Expr2.Type)) {
3106 Error ("Invalid right operand for binary operator `%s'", Op);
3107 /* Continue. Wrong code will be generated, but the compiler won't
3108 * break, so this is the best error recovery.
3112 /* Check for a constant expression */
3113 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
3114 /* The resulting value is a constant. If the generator has the NOPUSH
3115 * flag set, don't push the lhs.
3117 if (Gen->Flags & GEN_NOPUSH) {
3121 /* lhs is a pointer, scale rhs */
3122 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
3125 /* If the lhs is character sized, the operation may be later done
3128 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3129 flags |= CF_FORCECHAR;
3132 /* Special handling for add and sub - some sort of a hack, but short code */
3133 if (Gen->Func == g_add) {
3134 g_inc (flags | CF_CONST, Expr2.IVal);
3135 } else if (Gen->Func == g_sub) {
3136 g_dec (flags | CF_CONST, Expr2.IVal);
3138 if (Expr2.IVal == 0) {
3139 /* Check for div by zero/mod by zero */
3140 if (Gen->Func == g_div) {
3141 Error ("Division by zero");
3142 } else if (Gen->Func == g_mod) {
3143 Error ("Modulo operation with zero");
3146 Gen->Func (flags | CF_CONST, Expr2.IVal);
3150 /* rhs is not constant. Load into the primary */
3151 LoadExpr (CF_NONE, &Expr2);
3153 /* lhs is a pointer, scale rhs */
3154 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
3157 /* If the lhs is character sized, the operation may be later done
3160 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3161 flags |= CF_FORCECHAR;
3164 /* Adjust the types of the operands if needed */
3165 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
3168 ED_MakeRValExpr (Expr);
3173 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3174 /* Process the += and -= operators */
3182 /* We're currently only able to handle some adressing modes */
3183 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3184 /* Use generic routine */
3185 opeq (Gen, Expr, Op);
3189 /* We must have an lvalue */
3190 if (ED_IsRVal (Expr)) {
3191 Error ("Invalid lvalue in assignment");
3195 /* The left side must not be const qualified */
3196 if (IsQualConst (Expr->Type)) {
3197 Error ("Assignment to const");
3200 /* There must be an integer or pointer on the left side */
3201 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3202 Error ("Invalid left operand type");
3203 /* Continue. Wrong code will be generated, but the compiler won't
3204 * break, so this is the best error recovery.
3208 /* Skip the operator */
3211 /* Check if we have a pointer expression and must scale rhs */
3212 MustScale = IsTypePtr (Expr->Type);
3214 /* Initialize the code generator flags */
3218 /* Evaluate the rhs. We expect an integer here, since float is not
3222 if (!IsClassInt (Expr2.Type)) {
3223 Error ("Invalid right operand for binary operator `%s'", Op);
3224 /* Continue. Wrong code will be generated, but the compiler won't
3225 * break, so this is the best error recovery.
3228 if (ED_IsConstAbs (&Expr2)) {
3229 /* The resulting value is a constant. Scale it. */
3231 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3236 /* Not constant, load into the primary */
3237 LoadExpr (CF_NONE, &Expr2);
3239 /* lhs is a pointer, scale rhs */
3240 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3244 /* Setup the code generator flags */
3245 lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3246 rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3248 /* Convert the type of the lhs to that of the rhs */
3249 g_typecast (lflags, rflags);
3251 /* Output apropriate code depending on the location */
3252 switch (ED_GetLoc (Expr)) {
3255 /* Absolute: numeric address or const */
3256 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3257 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3259 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3264 /* Global variable */
3265 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3266 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3268 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3274 /* Static variable or literal in the literal pool */
3275 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3276 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3278 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3282 case E_LOC_REGISTER:
3283 /* Register variable */
3284 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3285 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3287 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3292 /* Value on the stack */
3293 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3294 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3296 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3301 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3304 /* Expression is a rvalue in the primary now */
3305 ED_MakeRValExpr (Expr);
3310 void hie1 (ExprDesc* Expr)
3311 /* Parse first level of expression hierarchy. */
3314 switch (CurTok.Tok) {
3320 case TOK_PLUS_ASSIGN:
3321 addsubeq (&GenPASGN, Expr, "+=");
3324 case TOK_MINUS_ASSIGN:
3325 addsubeq (&GenSASGN, Expr, "-=");
3328 case TOK_MUL_ASSIGN:
3329 opeq (&GenMASGN, Expr, "*=");
3332 case TOK_DIV_ASSIGN:
3333 opeq (&GenDASGN, Expr, "/=");
3336 case TOK_MOD_ASSIGN:
3337 opeq (&GenMOASGN, Expr, "%=");
3340 case TOK_SHL_ASSIGN:
3341 opeq (&GenSLASGN, Expr, "<<=");
3344 case TOK_SHR_ASSIGN:
3345 opeq (&GenSRASGN, Expr, ">>=");
3348 case TOK_AND_ASSIGN:
3349 opeq (&GenAASGN, Expr, "&=");
3352 case TOK_XOR_ASSIGN:
3353 opeq (&GenXOASGN, Expr, "^=");
3357 opeq (&GenOASGN, Expr, "|=");
3367 void hie0 (ExprDesc *Expr)
3368 /* Parse comma operator. */
3371 while (CurTok.Tok == TOK_COMMA) {
3379 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3380 /* Will evaluate an expression via the given function. If the result is a
3381 * constant, 0 is returned and the value is put in the Expr struct. If the
3382 * result is not constant, LoadExpr is called to bring the value into the
3383 * primary register and 1 is returned.
3387 ExprWithCheck (Func, Expr);
3389 /* Check for a constant expression */
3390 if (ED_IsConstAbs (Expr)) {
3391 /* Constant expression */
3394 /* Not constant, load into the primary */
3395 LoadExpr (Flags, Expr);
3402 void Expression0 (ExprDesc* Expr)
3403 /* Evaluate an expression via hie0 and put the result into the primary register */
3405 ExprWithCheck (hie0, Expr);
3406 LoadExpr (CF_NONE, Expr);
3411 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3412 /* Will evaluate an expression via the given function. If the result is not
3413 * a constant of some sort, a diagnostic will be printed, and the value is
3414 * replaced by a constant one to make sure there are no internal errors that
3415 * result from this input error.
3418 ExprWithCheck (Func, Expr);
3419 if (!ED_IsConst (Expr)) {
3420 Error ("Constant expression expected");
3421 /* To avoid any compiler errors, make the expression a valid const */
3422 ED_MakeConstAbsInt (Expr, 1);
3428 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3429 /* Will evaluate an expression via the given function. If the result is not
3430 * something that may be evaluated in a boolean context, a diagnostic will be
3431 * printed, and the value is replaced by a constant one to make sure there
3432 * are no internal errors that result from this input error.
3435 ExprWithCheck (Func, Expr);
3436 if (!ED_IsBool (Expr)) {
3437 Error ("Boolean expression expected");
3438 /* To avoid any compiler errors, make the expression a valid int */
3439 ED_MakeConstAbsInt (Expr, 1);
3445 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3446 /* Will evaluate an expression via the given function. If the result is not
3447 * a constant numeric integer value, a diagnostic will be printed, and the
3448 * value is replaced by a constant one to make sure there are no internal
3449 * errors that result from this input error.
3452 ExprWithCheck (Func, Expr);
3453 if (!ED_IsConstAbsInt (Expr)) {
3454 Error ("Constant integer expression expected");
3455 /* To avoid any compiler errors, make the expression a valid const */
3456 ED_MakeConstAbsInt (Expr, 1);