3 ** 1998-06-21, Ullrich von Bassewitz
4 ** 2015-04-19, Greg King
14 #include "debugflag.h"
21 #include "assignment.h"
33 #include "shiftexpr.h"
44 /*****************************************************************************/
46 /*****************************************************************************/
50 /* Generator attributes */
51 #define GEN_NOPUSH 0x01 /* Don't push lhs */
52 #define GEN_COMM 0x02 /* Operator is commutative */
54 /* Map a generator function and its attributes to a token */
56 token_t Tok; /* Token to map to */
57 unsigned Flags; /* Flags for generator function */
58 void (*Func) (unsigned, unsigned long); /* Generator func */
61 /* Descriptors for the operations */
62 static GenDesc GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add };
63 static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub };
64 static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul };
65 static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div };
66 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod };
67 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl };
68 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr };
69 static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and };
70 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor };
71 static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or };
75 /*****************************************************************************/
76 /* Helper functions */
77 /*****************************************************************************/
81 static unsigned GlobalModeFlags (const ExprDesc* Expr)
82 /* Return the addressing mode flags for the given expression */
84 switch (ED_GetLoc (Expr)) {
85 case E_LOC_ABS: return CF_ABSOLUTE;
86 case E_LOC_GLOBAL: return CF_EXTERNAL;
87 case E_LOC_STATIC: return CF_STATIC;
88 case E_LOC_REGISTER: return CF_REGVAR;
89 case E_LOC_STACK: return CF_NONE;
90 case E_LOC_PRIMARY: return CF_NONE;
91 case E_LOC_EXPR: return CF_NONE;
92 case E_LOC_LITERAL: return CF_STATIC; /* Same as static */
94 Internal ("GlobalModeFlags: Invalid location flags value: 0x%04X", Expr->Flags);
102 void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
103 /* Call an expression function with checks. */
105 /* Remember the stack pointer */
106 int OldSP = StackPtr;
108 /* Call the expression function */
111 /* Do some checks to see if code generation is still consistent */
112 if (StackPtr != OldSP) {
114 Error ("Code generation messed up: "
115 "StackPtr is %d, should be %d",
118 Internal ("Code generation messed up: "
119 "StackPtr is %d, should be %d",
127 void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
128 /* Call an expression function with checks and record start and end of the
134 ExprWithCheck (Func, Expr);
136 ED_SetCodeRange (Expr, &Start, &End);
141 static Type* promoteint (Type* lhst, Type* rhst)
142 /* In an expression with two ints, return the type of the result */
144 /* Rules for integer types:
145 ** - If one of the values is a long, the result is long.
146 ** - If one of the values is unsigned, the result is also unsigned.
147 ** - Otherwise the result is an int.
149 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
150 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
156 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
166 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
167 /* Adjust the two values for a binary operation. lhs is expected on stack or
168 ** to be constant, rhs is expected to be in the primary register or constant.
169 ** The function will put the type of the result into lhs and return the
170 ** code generator flags for the operation.
171 ** If NoPush is given, it is assumed that the operation does not expect the lhs
172 ** to be on stack, and that lhs is in a register instead.
173 ** Beware: The function does only accept int types.
176 unsigned ltype, rtype;
179 /* Get the type strings */
180 Type* lhst = lhs->Type;
181 Type* rhst = rhs->Type;
183 /* Generate type adjustment code if needed */
184 ltype = TypeOf (lhst);
185 if (ED_IsLocAbs (lhs)) {
189 /* Value is in primary register*/
192 rtype = TypeOf (rhst);
193 if (ED_IsLocAbs (rhs)) {
196 flags = g_typeadjust (ltype, rtype);
198 /* Set the type of the result */
199 lhs->Type = promoteint (lhst, rhst);
201 /* Return the code generator flags */
207 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
208 /* Find a token in a generator table */
210 while (Table->Tok != TOK_INVALID) {
211 if (Table->Tok == Tok) {
221 static int TypeSpecAhead (void)
222 /* Return true if some sort of type is waiting (helper for cast and sizeof()
228 /* There's a type waiting if:
230 ** We have an opening paren, and
231 ** a. the next token is a type, or
232 ** b. the next token is a type qualifier, or
233 ** c. the next token is a typedef'd type
235 return CurTok.Tok == TOK_LPAREN && (
236 TokIsType (&NextTok) ||
237 TokIsTypeQual (&NextTok) ||
238 (NextTok.Tok == TOK_IDENT &&
239 (Entry = FindSym (NextTok.Ident)) != 0 &&
240 SymIsTypeDef (Entry)));
245 void PushAddr (const ExprDesc* Expr)
246 /* If the expression contains an address that was somehow evaluated,
247 ** push this address on the stack. This is a helper function for all
248 ** sorts of implicit or explicit assignment functions where the lvalue
249 ** must be saved if it's not constant, before evaluating the rhs.
252 /* Get the address on stack if needed */
253 if (ED_IsLocExpr (Expr)) {
254 /* Push the address (always a pointer) */
261 static void WarnConstCompareResult (void)
262 /* If the result of a comparison is constant, this is suspicious when not in
263 ** preprocessor mode.
266 if (!Preprocessing && IS_Get (&WarnConstComparison) != 0) {
267 Warning ("Result of comparison is constant");
273 /*****************************************************************************/
275 /*****************************************************************************/
279 static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall)
280 /* Parse a function parameter list and pass the parameters to the called
281 ** function. Depending on several criteria this may be done by just pushing
282 ** each parameter separately, or creating the parameter frame once and then
283 ** storing into this frame.
284 ** The function returns the size of the parameters pushed.
289 /* Initialize variables */
290 SymEntry* Param = 0; /* Keep gcc silent */
291 unsigned ParamSize = 0; /* Size of parameters pushed */
292 unsigned ParamCount = 0; /* Number of parameters pushed */
293 unsigned FrameSize = 0; /* Size of parameter frame */
294 unsigned FrameParams = 0; /* Number of params in frame */
295 int FrameOffs = 0; /* Offset into parameter frame */
296 int Ellipsis = 0; /* Function is variadic */
298 /* As an optimization, we may allocate the complete parameter frame at
299 ** once instead of pushing each parameter as it comes. We may do that,
302 ** - optimizations that increase code size are enabled (allocating the
303 ** stack frame at once gives usually larger code).
304 ** - we have more than one parameter to push (don't count the last param
305 ** for __fastcall__ functions).
307 ** The FrameSize variable will contain a value > 0 if storing into a frame
308 ** (instead of pushing) is enabled.
311 if (IS_Get (&CodeSizeFactor) >= 200) {
313 /* Calculate the number and size of the parameters */
314 FrameParams = Func->ParamCount;
315 FrameSize = Func->ParamSize;
316 if (FrameParams > 0 && IsFastcall) {
317 /* Last parameter is not pushed */
318 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
322 /* Do we have more than one parameter in the frame? */
323 if (FrameParams > 1) {
324 /* Okeydokey, setup the frame */
325 FrameOffs = StackPtr;
327 StackPtr -= FrameSize;
329 /* Don't use a preallocated frame */
334 /* Parse the actual parameter list */
335 while (CurTok.Tok != TOK_RPAREN) {
339 /* Count arguments */
342 /* Fetch the pointer to the next argument, check for too many args */
343 if (ParamCount <= Func->ParamCount) {
344 /* Beware: If there are parameters with identical names, they
345 ** cannot go into the same symbol table, which means that in this
346 ** case of errorneous input, the number of nodes in the symbol
347 ** table and ParamCount are NOT equal. We have to handle this case
348 ** below to avoid segmentation violations. Since we know that this
349 ** problem can only occur if there is more than one parameter,
350 ** we will just use the last one.
352 if (ParamCount == 1) {
354 Param = Func->SymTab->SymHead;
355 } else if (Param->NextSym != 0) {
357 Param = Param->NextSym;
358 CHECK ((Param->Flags & SC_PARAM) != 0);
360 } else if (!Ellipsis) {
361 /* Too many arguments. Do we have an open param list? */
362 if ((Func->Flags & FD_VARIADIC) == 0) {
363 /* End of param list reached, no ellipsis */
364 Error ("Too many arguments in function call");
366 /* Assume an ellipsis even in case of errors to avoid an error
367 ** message for each other argument.
372 /* Evaluate the parameter expression */
375 /* If we don't have an argument spec, accept anything, otherwise
376 ** convert the actual argument to the type needed.
381 /* Convert the argument to the parameter type if needed */
382 TypeConversion (&Expr, Param->Type);
384 /* If we have a prototype, chars may be pushed as chars */
385 Flags |= CF_FORCECHAR;
389 /* No prototype available. Convert array to "pointer to first
390 ** element", and function to "pointer to function".
392 Expr.Type = PtrConversion (Expr.Type);
396 /* Load the value into the primary if it is not already there */
397 LoadExpr (Flags, &Expr);
399 /* Use the type of the argument for the push */
400 Flags |= TypeOf (Expr.Type);
402 /* If this is a fastcall function, don't push the last argument */
403 if (ParamCount != Func->ParamCount || !IsFastcall) {
404 unsigned ArgSize = sizeofarg (Flags);
406 /* We have the space already allocated, store in the frame.
407 ** Because of invalid type conversions (that have produced an
408 ** error before), we can end up here with a non-aligned stack
409 ** frame. Since no output will be generated anyway, handle
410 ** these cases gracefully instead of doing a CHECK.
412 if (FrameSize >= ArgSize) {
413 FrameSize -= ArgSize;
417 FrameOffs -= ArgSize;
419 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
421 /* Push the argument */
422 g_push (Flags, Expr.IVal);
425 /* Calculate total parameter size */
426 ParamSize += ArgSize;
429 /* Check for end of argument list */
430 if (CurTok.Tok != TOK_COMMA) {
436 /* Check if we had enough parameters */
437 if (ParamCount < Func->ParamCount) {
438 Error ("Too few arguments in function call");
441 /* The function returns the size of all parameters pushed onto the stack.
442 ** However, if there are parameters missing (which is an error and was
443 ** flagged by the compiler) AND a stack frame was preallocated above,
444 ** we would loose track of the stackpointer and generate an internal error
445 ** later. So we correct the value by the parameters that should have been
446 ** pushed to avoid an internal compiler error. Since an error was
447 ** generated before, no code will be output anyway.
449 return ParamSize + FrameSize;
454 static void FunctionCall (ExprDesc* Expr)
455 /* Perform a function call. */
457 FuncDesc* Func; /* Function descriptor */
458 int IsFuncPtr; /* Flag */
459 unsigned ParamSize; /* Number of parameter bytes */
461 int PtrOffs = 0; /* Offset of function pointer on stack */
462 int IsFastcall = 0; /* True if it's a fast-call function */
463 int PtrOnStack = 0; /* True if a pointer copy is on stack */
465 /* Skip the left paren */
468 /* Get a pointer to the function descriptor from the type string */
469 Func = GetFuncDesc (Expr->Type);
471 /* Handle function pointers transparently */
472 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
474 /* Check whether it's a fastcall function that has parameters */
475 IsFastcall = (Func->Flags & FD_VARIADIC) == 0 && Func->ParamCount > 0 &&
477 IsQualFastcall (Expr->Type + 1) :
478 !IsQualCDecl (Expr->Type + 1));
480 /* Things may be difficult, depending on where the function pointer
481 ** resides. If the function pointer is an expression of some sort
482 ** (not a local or global variable), we have to evaluate this
483 ** expression now and save the result for later. Since calls to
484 ** function pointers may be nested, we must save it onto the stack.
485 ** For fastcall functions we do also need to place a copy of the
486 ** pointer on stack, since we cannot use a/x.
488 PtrOnStack = IsFastcall || !ED_IsConst (Expr);
491 /* Not a global or local variable, or a fastcall function. Load
492 ** the pointer into the primary and mark it as an expression.
494 LoadExpr (CF_NONE, Expr);
495 ED_MakeRValExpr (Expr);
497 /* Remember the code position */
500 /* Push the pointer onto the stack and remember the offset */
506 /* Check function attributes */
507 if (Expr->Sym && SymHasAttr (Expr->Sym, atNoReturn)) {
508 /* For now, handle as if a return statement was encountered */
509 F_ReturnFound (CurrentFunc);
512 /* Check for known standard functions and inline them */
513 if (Expr->Name != 0) {
514 int StdFunc = FindStdFunc ((const char*) Expr->Name);
516 /* Inline this function */
517 HandleStdFunc (StdFunc, Func, Expr);
522 /* If we didn't inline the function, get fastcall info */
523 IsFastcall = (Func->Flags & FD_VARIADIC) == 0 &&
525 IsQualFastcall (Expr->Type) :
526 !IsQualCDecl (Expr->Type));
529 /* Parse the parameter list */
530 ParamSize = FunctionParamList (Func, IsFastcall);
532 /* We need the closing paren here */
535 /* Special handling for function pointers */
538 /* If the function is not a fastcall function, load the pointer to
539 ** the function into the primary.
543 /* Not a fastcall function - we may use the primary */
545 /* If we have no parameters, the pointer is still in the
546 ** primary. Remove the code to push it and correct the
549 if (ParamSize == 0) {
553 /* Load from the saved copy */
554 g_getlocal (CF_PTR, PtrOffs);
557 /* Load from original location */
558 LoadExpr (CF_NONE, Expr);
561 /* Call the function */
562 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
566 /* Fastcall function. We cannot use the primary for the function
567 ** pointer and must therefore use an offset to the stack location.
568 ** Since fastcall functions may never be variadic, we can use the
569 ** index register for this purpose.
571 g_callind (CF_LOCAL, ParamSize, PtrOffs);
574 /* If we have a pointer on stack, remove it */
585 /* Normal function */
586 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
590 /* The function result is an rvalue in the primary register */
591 ED_MakeRValExpr (Expr);
592 Expr->Type = GetFuncReturn (Expr->Type);
597 static void Primary (ExprDesc* E)
598 /* This is the lowest level of the expression parser. */
602 /* Initialize fields in the expression stucture */
605 /* Character and integer constants. */
606 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
607 E->IVal = CurTok.IVal;
608 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
609 E->Type = CurTok.Type;
614 /* Floating point constant */
615 if (CurTok.Tok == TOK_FCONST) {
616 E->FVal = CurTok.FVal;
617 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
618 E->Type = CurTok.Type;
623 /* Process parenthesized subexpression by calling the whole parser
626 if (CurTok.Tok == TOK_LPAREN) {
633 /* If we run into an identifier in preprocessing mode, we assume that this
634 ** is an undefined macro and replace it by a constant value of zero.
636 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
638 ED_MakeConstAbsInt (E, 0);
642 /* All others may only be used if the expression evaluation is not called
643 ** recursively by the preprocessor.
646 /* Illegal expression in PP mode */
647 Error ("Preprocessor expression expected");
648 ED_MakeConstAbsInt (E, 1);
652 switch (CurTok.Tok) {
655 /* Identifier. Get a pointer to the symbol table entry */
656 Sym = E->Sym = FindSym (CurTok.Ident);
658 /* Is the symbol known? */
661 /* We found the symbol - skip the name token */
664 /* Check for illegal symbol types */
665 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
666 if (Sym->Flags & SC_TYPE) {
667 /* Cannot use type symbols */
668 Error ("Variable identifier expected");
669 /* Assume an int type to make E valid */
670 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
675 /* Mark the symbol as referenced */
676 Sym->Flags |= SC_REF;
678 /* The expression type is the symbol type */
681 /* Check for legal symbol types */
682 if ((Sym->Flags & SC_CONST) == SC_CONST) {
683 /* Enum or some other numeric constant */
684 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
685 E->IVal = Sym->V.ConstVal;
686 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
688 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
689 E->Name = (unsigned long) Sym->Name;
690 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
691 /* Local variable. If this is a parameter for a variadic
692 ** function, we have to add some address calculations, and the
693 ** address is not const.
695 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
696 /* Variadic parameter */
697 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
698 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
700 /* Normal parameter */
701 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
702 E->IVal = Sym->V.Offs;
704 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
705 /* Register variable, zero page based */
706 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
707 E->Name = Sym->V.R.RegOffs;
708 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
709 /* Static variable */
710 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
711 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
712 E->Name = (unsigned long) Sym->Name;
714 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
715 E->Name = Sym->V.Label;
718 /* Local static variable */
719 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
720 E->Name = Sym->V.Offs;
723 /* We've made all variables lvalues above. However, this is
724 ** not always correct: An array is actually the address of its
725 ** first element, which is a rvalue, and a function is a
726 ** rvalue, too, because we cannot store anything in a function.
727 ** So fix the flags depending on the type.
729 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
735 /* We did not find the symbol. Remember the name, then skip it */
737 strcpy (Ident, CurTok.Ident);
740 /* IDENT is either an auto-declared function or an undefined variable. */
741 if (CurTok.Tok == TOK_LPAREN) {
742 /* C99 doesn't allow calls to undefined functions, so
743 ** generate an error and otherwise a warning. Declare a
744 ** function returning int. For that purpose, prepare a
745 ** function signature for a function having an empty param
746 ** list and returning int.
748 if (IS_Get (&Standard) >= STD_C99) {
749 Error ("Call to undefined function `%s'", Ident);
751 Warning ("Call to undefined function `%s'", Ident);
753 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
755 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
756 E->Name = (unsigned long) Sym->Name;
758 /* Undeclared Variable */
759 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
760 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
762 Error ("Undefined symbol: `%s'", Ident);
771 E->LVal = UseLiteral (CurTok.SVal);
772 E->Type = GetCharArrayType (GetLiteralSize (CurTok.SVal));
773 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
775 E->Name = GetLiteralLabel (CurTok.SVal);
782 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
787 /* Register pseudo variable */
788 E->Type = type_uchar;
789 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
794 /* Register pseudo variable */
796 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
801 /* Register pseudo variable */
802 E->Type = type_ulong;
803 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
808 /* Illegal primary. Be sure to skip the token to avoid endless
811 Error ("Expression expected");
813 ED_MakeConstAbsInt (E, 1);
820 static void ArrayRef (ExprDesc* Expr)
821 /* Handle an array reference. This function needs a rewrite. */
832 /* Skip the bracket */
835 /* Get the type of left side */
838 /* We can apply a special treatment for arrays that have a const base
839 ** address. This is true for most arrays and will produce a lot better
840 ** code. Check if this is a const base address.
842 ConstBaseAddr = ED_IsRVal (Expr) &&
843 (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
845 /* If we have a constant base, we delay the address fetch */
847 if (!ConstBaseAddr) {
848 /* Get a pointer to the array into the primary */
849 LoadExpr (CF_NONE, Expr);
851 /* Get the array pointer on stack. Do not push more than 16
852 ** bit, even if this value is greater, since we cannot handle
853 ** other than 16bit stuff when doing indexing.
859 /* TOS now contains ptr to array elements. Get the subscript. */
860 MarkedExprWithCheck (hie0, &Subscript);
862 /* Check the types of array and subscript. We can either have a
863 ** pointer/array to the left, in which case the subscript must be of an
864 ** integer type, or we have an integer to the left, in which case the
865 ** subscript must be a pointer/array.
866 ** Since we do the necessary checking here, we can rely later on the
869 Qualifiers = T_QUAL_NONE;
870 if (IsClassPtr (Expr->Type)) {
871 if (!IsClassInt (Subscript.Type)) {
872 Error ("Array subscript is not an integer");
873 /* To avoid any compiler errors, make the expression a valid int */
874 ED_MakeConstAbsInt (&Subscript, 0);
876 if (IsTypeArray (Expr->Type)) {
877 Qualifiers = GetQualifier (Expr->Type);
879 ElementType = Indirect (Expr->Type);
880 } else if (IsClassInt (Expr->Type)) {
881 if (!IsClassPtr (Subscript.Type)) {
882 Error ("Subscripted value is neither array nor pointer");
883 /* To avoid compiler errors, make the subscript a char[] at
886 ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
887 } else if (IsTypeArray (Subscript.Type)) {
888 Qualifiers = GetQualifier (Subscript.Type);
890 ElementType = Indirect (Subscript.Type);
892 Error ("Cannot subscript");
893 /* To avoid compiler errors, fake both the array and the subscript, so
894 ** we can just proceed.
896 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
897 ED_MakeConstAbsInt (&Subscript, 0);
898 ElementType = Indirect (Expr->Type);
901 /* The element type has the combined qualifiers from itself and the array,
902 ** it is a member of (if any).
904 if (GetQualifier (ElementType) != (GetQualifier (ElementType) | Qualifiers)) {
905 ElementType = TypeDup (ElementType);
906 ElementType->C |= Qualifiers;
909 /* If the subscript is a bit-field, load it and make it an rvalue */
910 if (ED_IsBitField (&Subscript)) {
911 LoadExpr (CF_NONE, &Subscript);
912 ED_MakeRValExpr (&Subscript);
915 /* Check if the subscript is constant absolute value */
916 if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) {
918 /* The array subscript is a numeric constant. If we had pushed the
919 ** array base address onto the stack before, we can remove this value,
920 ** since we can generate expression+offset.
922 if (!ConstBaseAddr) {
925 /* Get an array pointer into the primary */
926 LoadExpr (CF_NONE, Expr);
929 if (IsClassPtr (Expr->Type)) {
931 /* Lhs is pointer/array. Scale the subscript value according to
934 Subscript.IVal *= CheckedSizeOf (ElementType);
936 /* Remove the address load code */
939 /* In case of an array, we can adjust the offset of the expression
940 ** already in Expr. If the base address was a constant, we can even
941 ** remove the code that loaded the address into the primary.
943 if (IsTypeArray (Expr->Type)) {
945 /* Adjust the offset */
946 Expr->IVal += Subscript.IVal;
950 /* It's a pointer, so we do have to load it into the primary
951 ** first (if it's not already there).
953 if (ConstBaseAddr || ED_IsLVal (Expr)) {
954 LoadExpr (CF_NONE, Expr);
955 ED_MakeRValExpr (Expr);
959 Expr->IVal = Subscript.IVal;
964 /* Scale the rhs value according to the element type */
965 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
967 /* Add the subscript. Since arrays are indexed by integers,
968 ** we will ignore the true type of the subscript here and
969 ** use always an int. #### Use offset but beware of LoadExpr!
971 g_inc (CF_INT | CF_CONST, Subscript.IVal);
977 /* Array subscript is not constant. Load it into the primary */
979 LoadExpr (CF_NONE, &Subscript);
982 if (IsClassPtr (Expr->Type)) {
984 /* Indexing is based on unsigneds, so we will just use the integer
985 ** portion of the index (which is in (e)ax, so there's no further
988 g_scale (CF_INT, CheckedSizeOf (ElementType));
992 /* Get the int value on top. If we come here, we're sure, both
993 ** values are 16 bit (the first one was truncated if necessary
994 ** and the second one is a pointer). Note: If ConstBaseAddr is
995 ** true, we don't have a value on stack, so to "swap" both, just
996 ** push the subscript.
1000 LoadExpr (CF_NONE, Expr);
1007 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1011 /* The offset is now in the primary register. It we didn't have a
1012 ** constant base address for the lhs, the lhs address is already
1013 ** on stack, and we must add the offset. If the base address was
1014 ** constant, we call special functions to add the address to the
1017 if (!ConstBaseAddr) {
1019 /* The array base address is on stack and the subscript is in the
1020 ** primary. Add both.
1026 /* The subscript is in the primary, and the array base address is
1027 ** in Expr. If the subscript has itself a constant address, it is
1028 ** often a better idea to reverse again the order of the
1029 ** evaluation. This will generate better code if the subscript is
1030 ** a byte sized variable. But beware: This is only possible if the
1031 ** subscript was not scaled, that is, if this was a byte array
1034 if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
1035 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1039 /* Reverse the order of evaluation */
1040 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
1045 RemoveCode (&Mark2);
1047 /* Get a pointer to the array into the primary. */
1048 LoadExpr (CF_NONE, Expr);
1050 /* Add the variable */
1051 if (ED_IsLocStack (&Subscript)) {
1052 g_addlocal (Flags, Subscript.IVal);
1054 Flags |= GlobalModeFlags (&Subscript);
1055 g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1059 if (ED_IsLocAbs (Expr)) {
1060 /* Constant numeric address. Just add it */
1061 g_inc (CF_INT, Expr->IVal);
1062 } else if (ED_IsLocStack (Expr)) {
1063 /* Base address is a local variable address */
1064 if (IsTypeArray (Expr->Type)) {
1065 g_addaddr_local (CF_INT, Expr->IVal);
1067 g_addlocal (CF_PTR, Expr->IVal);
1070 /* Base address is a static variable address */
1071 unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1072 if (ED_IsRVal (Expr)) {
1073 /* Add the address of the location */
1074 g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1076 /* Add the contents of the location */
1077 g_addstatic (Flags, Expr->Name, Expr->IVal);
1085 /* The result is an expression in the primary */
1086 ED_MakeRValExpr (Expr);
1090 /* Result is of element type */
1091 Expr->Type = ElementType;
1093 /* An array element is actually a variable. So the rules for variables
1094 ** with respect to the reference type apply: If it's an array, it is
1095 ** a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1096 ** but an array cannot contain functions).
1098 if (IsTypeArray (Expr->Type)) {
1104 /* Consume the closing bracket */
1110 static void StructRef (ExprDesc* Expr)
1111 /* Process struct field after . or ->. */
1118 /* Skip the token and check for an identifier */
1120 if (CurTok.Tok != TOK_IDENT) {
1121 Error ("Identifier expected");
1122 /* Make the expression an integer at address zero */
1123 ED_MakeConstAbs (Expr, 0, type_int);
1127 /* Get the symbol table entry and check for a struct field */
1128 strcpy (Ident, CurTok.Ident);
1130 Field = FindStructField (Expr->Type, Ident);
1132 Error ("Struct/union has no field named `%s'", Ident);
1133 /* Make the expression an integer at address zero */
1134 ED_MakeConstAbs (Expr, 0, type_int);
1138 /* If we have a struct pointer that is an lvalue and not already in the
1139 ** primary, load it now.
1141 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1143 /* Load into the primary */
1144 LoadExpr (CF_NONE, Expr);
1146 /* Make it an lvalue expression */
1147 ED_MakeLValExpr (Expr);
1150 /* The type is the type of the field plus any qualifiers from the struct */
1151 if (IsClassStruct (Expr->Type)) {
1152 Q = GetQualifier (Expr->Type);
1154 Q = GetQualifier (Indirect (Expr->Type));
1156 if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1157 FinalType = Field->Type;
1159 FinalType = TypeDup (Field->Type);
1163 /* A struct is usually an lvalue. If not, it is a struct in the primary
1166 if (ED_IsRVal (Expr) && ED_IsLocExpr (Expr) && !IsTypePtr (Expr->Type)) {
1171 /* Get the size of the type */
1172 unsigned Size = SizeOf (Expr->Type);
1175 CHECK (Field->V.Offs + Size <= SIZEOF_LONG);
1177 /* The type of the operation depends on the type of the struct */
1179 case 1: Flags = CF_CHAR | CF_UNSIGNED | CF_CONST; break;
1180 case 2: Flags = CF_INT | CF_UNSIGNED | CF_CONST; break;
1181 case 3: /* FALLTHROUGH */
1182 case 4: Flags = CF_LONG | CF_UNSIGNED | CF_CONST; break;
1183 default: Internal ("Invalid struct size: %u", Size); break;
1186 /* Generate a shift to get the field in the proper position in the
1187 ** primary. For bit fields, mask the value.
1189 BitOffs = Field->V.Offs * CHAR_BITS;
1190 if (SymIsBitField (Field)) {
1191 BitOffs += Field->V.B.BitOffs;
1192 g_asr (Flags, BitOffs);
1193 /* Mask the value. This is unnecessary if the shift executed above
1194 ** moved only zeroes into the value.
1196 if (BitOffs + Field->V.B.BitWidth != Size * CHAR_BITS) {
1197 g_and (CF_INT | CF_UNSIGNED | CF_CONST,
1198 (0x0001U << Field->V.B.BitWidth) - 1U);
1201 g_asr (Flags, BitOffs);
1204 /* Use the new type */
1205 Expr->Type = FinalType;
1209 /* Set the struct field offset */
1210 Expr->IVal += Field->V.Offs;
1212 /* Use the new type */
1213 Expr->Type = FinalType;
1215 /* An struct member is actually a variable. So the rules for variables
1216 ** with respect to the reference type apply: If it's an array, it is
1217 ** a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1218 ** but a struct field cannot be a function).
1220 if (IsTypeArray (Expr->Type)) {
1226 /* Make the expression a bit field if necessary */
1227 if (SymIsBitField (Field)) {
1228 ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1236 static void hie11 (ExprDesc *Expr)
1237 /* Handle compound types (structs and arrays) */
1239 /* Name value used in invalid function calls */
1240 static const char IllegalFunc[] = "illegal_function_call";
1242 /* Evaluate the lhs */
1245 /* Check for a rhs */
1246 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1247 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1249 switch (CurTok.Tok) {
1252 /* Array reference */
1257 /* Function call. */
1258 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1259 /* Not a function */
1260 Error ("Illegal function call");
1261 /* Force the type to be a implicitly defined function, one
1262 ** returning an int and taking any number of arguments.
1263 ** Since we don't have a name, invent one.
1265 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1266 Expr->Name = (long) IllegalFunc;
1268 /* Call the function */
1269 FunctionCall (Expr);
1273 if (!IsClassStruct (Expr->Type)) {
1274 Error ("Struct expected");
1280 /* If we have an array, convert it to pointer to first element */
1281 if (IsTypeArray (Expr->Type)) {
1282 Expr->Type = ArrayToPtr (Expr->Type);
1284 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1285 Error ("Struct pointer expected");
1291 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1299 void Store (ExprDesc* Expr, const Type* StoreType)
1300 /* Store the primary register into the location denoted by Expr. If StoreType
1301 ** is given, use this type when storing instead of Expr->Type. If StoreType
1302 ** is NULL, use Expr->Type instead.
1307 /* If StoreType was not given, use Expr->Type instead */
1308 if (StoreType == 0) {
1309 StoreType = Expr->Type;
1312 /* Prepare the code generator flags */
1313 Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1315 /* Do the store depending on the location */
1316 switch (ED_GetLoc (Expr)) {
1319 /* Absolute: numeric address or const */
1320 g_putstatic (Flags, Expr->IVal, 0);
1324 /* Global variable */
1325 g_putstatic (Flags, Expr->Name, Expr->IVal);
1330 /* Static variable or literal in the literal pool */
1331 g_putstatic (Flags, Expr->Name, Expr->IVal);
1334 case E_LOC_REGISTER:
1335 /* Register variable */
1336 g_putstatic (Flags, Expr->Name, Expr->IVal);
1340 /* Value on the stack */
1341 g_putlocal (Flags, Expr->IVal, 0);
1345 /* The primary register (value is already there) */
1349 /* An expression in the primary register */
1350 g_putind (Flags, Expr->IVal);
1354 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1357 /* Assume that each one of the stores will invalidate CC */
1358 ED_MarkAsUntested (Expr);
1363 static void PreInc (ExprDesc* Expr)
1364 /* Handle the preincrement operators */
1369 /* Skip the operator token */
1372 /* Evaluate the expression and check that it is an lvalue */
1374 if (!ED_IsLVal (Expr)) {
1375 Error ("Invalid lvalue");
1379 /* We cannot modify const values */
1380 if (IsQualConst (Expr->Type)) {
1381 Error ("Increment of read-only variable");
1384 /* Get the data type */
1385 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1387 /* Get the increment value in bytes */
1388 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1390 /* Check the location of the data */
1391 switch (ED_GetLoc (Expr)) {
1394 /* Absolute: numeric address or const */
1395 g_addeqstatic (Flags, Expr->IVal, 0, Val);
1399 /* Global variable */
1400 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1405 /* Static variable or literal in the literal pool */
1406 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1409 case E_LOC_REGISTER:
1410 /* Register variable */
1411 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1415 /* Value on the stack */
1416 g_addeqlocal (Flags, Expr->IVal, Val);
1420 /* The primary register */
1425 /* An expression in the primary register */
1426 g_addeqind (Flags, Expr->IVal, Val);
1430 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1433 /* Result is an expression, no reference */
1434 ED_MakeRValExpr (Expr);
1439 static void PreDec (ExprDesc* Expr)
1440 /* Handle the predecrement operators */
1445 /* Skip the operator token */
1448 /* Evaluate the expression and check that it is an lvalue */
1450 if (!ED_IsLVal (Expr)) {
1451 Error ("Invalid lvalue");
1455 /* We cannot modify const values */
1456 if (IsQualConst (Expr->Type)) {
1457 Error ("Decrement of read-only variable");
1460 /* Get the data type */
1461 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1463 /* Get the increment value in bytes */
1464 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1466 /* Check the location of the data */
1467 switch (ED_GetLoc (Expr)) {
1470 /* Absolute: numeric address or const */
1471 g_subeqstatic (Flags, Expr->IVal, 0, Val);
1475 /* Global variable */
1476 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1481 /* Static variable or literal in the literal pool */
1482 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1485 case E_LOC_REGISTER:
1486 /* Register variable */
1487 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1491 /* Value on the stack */
1492 g_subeqlocal (Flags, Expr->IVal, Val);
1496 /* The primary register */
1501 /* An expression in the primary register */
1502 g_subeqind (Flags, Expr->IVal, Val);
1506 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1509 /* Result is an expression, no reference */
1510 ED_MakeRValExpr (Expr);
1515 static void PostInc (ExprDesc* Expr)
1516 /* Handle the postincrement operator */
1522 /* The expression to increment must be an lvalue */
1523 if (!ED_IsLVal (Expr)) {
1524 Error ("Invalid lvalue");
1528 /* We cannot modify const values */
1529 if (IsQualConst (Expr->Type)) {
1530 Error ("Increment of read-only variable");
1533 /* Get the data type */
1534 Flags = TypeOf (Expr->Type);
1536 /* Push the address if needed */
1539 /* Fetch the value and save it (since it's the result of the expression) */
1540 LoadExpr (CF_NONE, Expr);
1541 g_save (Flags | CF_FORCECHAR);
1543 /* If we have a pointer expression, increment by the size of the type */
1544 if (IsTypePtr (Expr->Type)) {
1545 g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1547 g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1550 /* Store the result back */
1553 /* Restore the original value in the primary register */
1554 g_restore (Flags | CF_FORCECHAR);
1556 /* The result is always an expression, no reference */
1557 ED_MakeRValExpr (Expr);
1562 static void PostDec (ExprDesc* Expr)
1563 /* Handle the postdecrement operator */
1569 /* The expression to increment must be an lvalue */
1570 if (!ED_IsLVal (Expr)) {
1571 Error ("Invalid lvalue");
1575 /* We cannot modify const values */
1576 if (IsQualConst (Expr->Type)) {
1577 Error ("Decrement of read-only variable");
1580 /* Get the data type */
1581 Flags = TypeOf (Expr->Type);
1583 /* Push the address if needed */
1586 /* Fetch the value and save it (since it's the result of the expression) */
1587 LoadExpr (CF_NONE, Expr);
1588 g_save (Flags | CF_FORCECHAR);
1590 /* If we have a pointer expression, increment by the size of the type */
1591 if (IsTypePtr (Expr->Type)) {
1592 g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1594 g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1597 /* Store the result back */
1600 /* Restore the original value in the primary register */
1601 g_restore (Flags | CF_FORCECHAR);
1603 /* The result is always an expression, no reference */
1604 ED_MakeRValExpr (Expr);
1609 static void UnaryOp (ExprDesc* Expr)
1610 /* Handle unary -/+ and ~ */
1614 /* Remember the operator token and skip it */
1615 token_t Tok = CurTok.Tok;
1618 /* Get the expression */
1621 /* We can only handle integer types */
1622 if (!IsClassInt (Expr->Type)) {
1623 Error ("Argument must have integer type");
1624 ED_MakeConstAbsInt (Expr, 1);
1627 /* Check for a constant expression */
1628 if (ED_IsConstAbs (Expr)) {
1629 /* Value is constant */
1631 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1632 case TOK_PLUS: break;
1633 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1634 default: Internal ("Unexpected token: %d", Tok);
1637 /* Value is not constant */
1638 LoadExpr (CF_NONE, Expr);
1640 /* Get the type of the expression */
1641 Flags = TypeOf (Expr->Type);
1643 /* Handle the operation */
1645 case TOK_MINUS: g_neg (Flags); break;
1646 case TOK_PLUS: break;
1647 case TOK_COMP: g_com (Flags); break;
1648 default: Internal ("Unexpected token: %d", Tok);
1651 /* The result is a rvalue in the primary */
1652 ED_MakeRValExpr (Expr);
1658 void hie10 (ExprDesc* Expr)
1659 /* Handle ++, --, !, unary - etc. */
1663 switch (CurTok.Tok) {
1681 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1682 /* Constant expression */
1683 Expr->IVal = !Expr->IVal;
1685 g_bneg (TypeOf (Expr->Type));
1686 ED_MakeRValExpr (Expr);
1687 ED_TestDone (Expr); /* bneg will set cc */
1693 ExprWithCheck (hie10, Expr);
1694 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1695 /* Not a const, load it into the primary and make it a
1696 ** calculated value.
1698 LoadExpr (CF_NONE, Expr);
1699 ED_MakeRValExpr (Expr);
1701 /* If the expression is already a pointer to function, the
1702 ** additional dereferencing operator must be ignored. A function
1703 ** itself is represented as "pointer to function", so any number
1704 ** of dereference operators is legal, since the result will
1705 ** always be converted to "pointer to function".
1707 if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1708 /* Expression not storable */
1711 if (IsClassPtr (Expr->Type)) {
1712 Expr->Type = Indirect (Expr->Type);
1714 Error ("Illegal indirection");
1716 /* The * operator yields an lvalue */
1723 ExprWithCheck (hie10, Expr);
1724 /* The & operator may be applied to any lvalue, and it may be
1725 ** applied to functions, even if they're no lvalues.
1727 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1728 Error ("Illegal address");
1730 if (ED_IsBitField (Expr)) {
1731 Error ("Cannot take address of bit-field");
1732 /* Do it anyway, just to avoid further warnings */
1733 Expr->Flags &= ~E_BITFIELD;
1735 Expr->Type = PointerTo (Expr->Type);
1736 /* The & operator yields an rvalue */
1743 if (TypeSpecAhead ()) {
1746 Size = CheckedSizeOf (ParseType (T));
1749 /* Remember the output queue pointer */
1753 /* If the expression is a literal string, release it, so it
1754 ** won't be output as data if not used elsewhere.
1756 if (ED_IsLocLiteral (Expr)) {
1757 ReleaseLiteral (Expr->LVal);
1759 /* Calculate the size */
1760 Size = CheckedSizeOf (Expr->Type);
1761 /* Remove any generated code */
1764 ED_MakeConstAbs (Expr, Size, type_size_t);
1765 ED_MarkAsUntested (Expr);
1769 if (TypeSpecAhead ()) {
1779 /* Handle post increment */
1780 switch (CurTok.Tok) {
1781 case TOK_INC: PostInc (Expr); break;
1782 case TOK_DEC: PostDec (Expr); break;
1793 static void hie_internal (const GenDesc* Ops, /* List of generators */
1795 void (*hienext) (ExprDesc*),
1797 /* Helper function */
1803 token_t Tok; /* The operator token */
1804 unsigned ltype, type;
1805 int lconst; /* Left operand is a constant */
1806 int rconst; /* Right operand is a constant */
1809 ExprWithCheck (hienext, Expr);
1812 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1814 /* Tell the caller that we handled it's ops */
1817 /* All operators that call this function expect an int on the lhs */
1818 if (!IsClassInt (Expr->Type)) {
1819 Error ("Integer expression expected");
1820 /* To avoid further errors, make Expr a valid int expression */
1821 ED_MakeConstAbsInt (Expr, 1);
1824 /* Remember the operator token, then skip it */
1828 /* Get the lhs on stack */
1829 GetCodePos (&Mark1);
1830 ltype = TypeOf (Expr->Type);
1831 lconst = ED_IsConstAbs (Expr);
1833 /* Constant value */
1834 GetCodePos (&Mark2);
1835 /* If the operator is commutative, don't push the left side, if
1836 ** it's a constant, since we will exchange both operands.
1838 if ((Gen->Flags & GEN_COMM) == 0) {
1839 g_push (ltype | CF_CONST, Expr->IVal);
1842 /* Value not constant */
1843 LoadExpr (CF_NONE, Expr);
1844 GetCodePos (&Mark2);
1848 /* Get the right hand side */
1849 MarkedExprWithCheck (hienext, &Expr2);
1851 /* Check for a constant expression */
1852 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1854 /* Not constant, load into the primary */
1855 LoadExpr (CF_NONE, &Expr2);
1858 /* Check the type of the rhs */
1859 if (!IsClassInt (Expr2.Type)) {
1860 Error ("Integer expression expected");
1863 /* Check for const operands */
1864 if (lconst && rconst) {
1866 /* Both operands are constant, remove the generated code */
1867 RemoveCode (&Mark1);
1869 /* Get the type of the result */
1870 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1872 /* Handle the op differently for signed and unsigned types */
1873 if (IsSignSigned (Expr->Type)) {
1875 /* Evaluate the result for signed operands */
1876 signed long Val1 = Expr->IVal;
1877 signed long Val2 = Expr2.IVal;
1880 Expr->IVal = (Val1 | Val2);
1883 Expr->IVal = (Val1 ^ Val2);
1886 Expr->IVal = (Val1 & Val2);
1889 Expr->IVal = (Val1 * Val2);
1893 Error ("Division by zero");
1894 Expr->IVal = 0x7FFFFFFF;
1896 Expr->IVal = (Val1 / Val2);
1901 Error ("Modulo operation with zero");
1904 Expr->IVal = (Val1 % Val2);
1908 Internal ("hie_internal: got token 0x%X\n", Tok);
1912 /* Evaluate the result for unsigned operands */
1913 unsigned long Val1 = Expr->IVal;
1914 unsigned long Val2 = Expr2.IVal;
1917 Expr->IVal = (Val1 | Val2);
1920 Expr->IVal = (Val1 ^ Val2);
1923 Expr->IVal = (Val1 & Val2);
1926 Expr->IVal = (Val1 * Val2);
1930 Error ("Division by zero");
1931 Expr->IVal = 0xFFFFFFFF;
1933 Expr->IVal = (Val1 / Val2);
1938 Error ("Modulo operation with zero");
1941 Expr->IVal = (Val1 % Val2);
1945 Internal ("hie_internal: got token 0x%X\n", Tok);
1949 } else if (lconst && (Gen->Flags & GEN_COMM) && !rconst) {
1951 /* The left side is constant, the right side is not, and the
1952 ** operator allows swapping the operands. We haven't pushed the
1953 ** left side onto the stack in this case, and will reverse the
1954 ** operation because this allows for better code.
1956 unsigned rtype = ltype | CF_CONST;
1957 ltype = TypeOf (Expr2.Type); /* Expr2 is now left */
1959 if ((Gen->Flags & GEN_NOPUSH) == 0) {
1962 ltype |= CF_REG; /* Value is in register */
1965 /* Determine the type of the operation result. */
1966 type |= g_typeadjust (ltype, rtype);
1967 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1970 Gen->Func (type, Expr->IVal);
1972 /* We have a rvalue in the primary now */
1973 ED_MakeRValExpr (Expr);
1977 /* If the right hand side is constant, and the generator function
1978 ** expects the lhs in the primary, remove the push of the primary
1981 unsigned rtype = TypeOf (Expr2.Type);
1984 /* Second value is constant - check for div */
1987 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1988 Error ("Division by zero");
1989 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1990 Error ("Modulo operation with zero");
1992 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1993 RemoveCode (&Mark2);
1994 ltype |= CF_REG; /* Value is in register */
1998 /* Determine the type of the operation result. */
1999 type |= g_typeadjust (ltype, rtype);
2000 Expr->Type = promoteint (Expr->Type, Expr2.Type);
2003 Gen->Func (type, Expr2.IVal);
2005 /* We have a rvalue in the primary now */
2006 ED_MakeRValExpr (Expr);
2013 static void hie_compare (const GenDesc* Ops, /* List of generators */
2015 void (*hienext) (ExprDesc*))
2016 /* Helper function for the compare operators */
2023 token_t Tok; /* The operator token */
2025 int rconst; /* Operand is a constant */
2028 GetCodePos (&Mark0);
2029 ExprWithCheck (hienext, Expr);
2031 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
2033 /* Remember the generator function */
2034 void (*GenFunc) (unsigned, unsigned long) = Gen->Func;
2036 /* Remember the operator token, then skip it */
2040 /* Get the lhs on stack */
2041 GetCodePos (&Mark1);
2042 ltype = TypeOf (Expr->Type);
2043 if (ED_IsConstAbs (Expr)) {
2044 /* Constant value */
2045 GetCodePos (&Mark2);
2046 g_push (ltype | CF_CONST, Expr->IVal);
2048 /* Value not constant */
2049 LoadExpr (CF_NONE, Expr);
2050 GetCodePos (&Mark2);
2054 /* Get the right hand side */
2055 MarkedExprWithCheck (hienext, &Expr2);
2057 /* Check for a constant expression */
2058 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
2060 /* Not constant, load into the primary */
2061 LoadExpr (CF_NONE, &Expr2);
2064 /* Make sure, the types are compatible */
2065 if (IsClassInt (Expr->Type)) {
2066 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
2067 Error ("Incompatible types");
2069 } else if (IsClassPtr (Expr->Type)) {
2070 if (IsClassPtr (Expr2.Type)) {
2071 /* Both pointers are allowed in comparison if they point to
2072 ** the same type, or if one of them is a void pointer.
2074 Type* left = Indirect (Expr->Type);
2075 Type* right = Indirect (Expr2.Type);
2076 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
2077 /* Incomatible pointers */
2078 Error ("Incompatible types");
2080 } else if (!ED_IsNullPtr (&Expr2)) {
2081 Error ("Incompatible types");
2085 /* Check for const operands */
2086 if (ED_IsConstAbs (Expr) && rconst) {
2088 /* If the result is constant, this is suspicious when not in
2089 ** preprocessor mode.
2091 WarnConstCompareResult ();
2093 /* Both operands are constant, remove the generated code */
2094 RemoveCode (&Mark1);
2096 /* Determine if this is a signed or unsigned compare */
2097 if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
2098 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
2100 /* Evaluate the result for signed operands */
2101 signed long Val1 = Expr->IVal;
2102 signed long Val2 = Expr2.IVal;
2104 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2105 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2106 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2107 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2108 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2109 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2110 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2115 /* Evaluate the result for unsigned operands */
2116 unsigned long Val1 = Expr->IVal;
2117 unsigned long Val2 = Expr2.IVal;
2119 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2120 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2121 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2122 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2123 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2124 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2125 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2131 /* Determine the signedness of the operands */
2132 int LeftSigned = IsSignSigned (Expr->Type);
2133 int RightSigned = IsSignSigned (Expr2.Type);
2135 /* If the right hand side is constant, and the generator function
2136 ** expects the lhs in the primary, remove the push of the primary
2142 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2143 RemoveCode (&Mark2);
2144 ltype |= CF_REG; /* Value is in register */
2148 /* Determine the type of the operation. */
2149 if (IsTypeChar (Expr->Type) && rconst) {
2151 /* Left side is unsigned char, right side is constant.
2152 ** Determine the minimum and maximum values
2154 int LeftMin, LeftMax;
2162 /* An integer value is always represented as a signed in the
2163 ** ExprDesc structure. This may lead to false results below,
2164 ** if it is actually unsigned, but interpreted as signed
2165 ** because of the representation. Fortunately, in this case,
2166 ** the actual value doesn't matter, since it's always greater
2167 ** than what can be represented in a char. So correct the
2168 ** value accordingly.
2170 if (!RightSigned && Expr2.IVal < 0) {
2171 /* Correct the value so it is an unsigned. It will then
2172 ** anyway match one of the cases below.
2174 Expr2.IVal = LeftMax + 1;
2177 /* Comparing a char against a constant may have a constant
2178 ** result. Please note: It is not possible to remove the code
2179 ** for the compare alltogether, because it may have side
2185 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2186 ED_MakeConstAbsInt (Expr, 0);
2187 WarnConstCompareResult ();
2193 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2194 ED_MakeConstAbsInt (Expr, 1);
2195 WarnConstCompareResult ();
2201 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2202 ED_MakeConstAbsInt (Expr, Expr2.IVal > LeftMax);
2203 WarnConstCompareResult ();
2209 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2210 ED_MakeConstAbsInt (Expr, Expr2.IVal >= LeftMax);
2211 WarnConstCompareResult ();
2217 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2218 ED_MakeConstAbsInt (Expr, Expr2.IVal <= LeftMin);
2219 WarnConstCompareResult ();
2225 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2226 ED_MakeConstAbsInt (Expr, Expr2.IVal < LeftMin);
2227 WarnConstCompareResult ();
2233 Internal ("hie_compare: got token 0x%X\n", Tok);
2236 /* If the result is not already constant (as evaluated in the
2237 ** switch above), we can execute the operation as a char op,
2238 ** since the right side constant is in a valid range.
2240 flags |= (CF_CHAR | CF_FORCECHAR);
2242 flags |= CF_UNSIGNED;
2245 } else if (IsTypeChar (Expr->Type) && IsTypeChar (Expr2.Type) &&
2246 GetSignedness (Expr->Type) == GetSignedness (Expr2.Type)) {
2248 /* Both are chars with the same signedness. We can encode the
2249 ** operation as a char operation.
2253 flags |= CF_FORCECHAR;
2256 flags |= CF_UNSIGNED;
2259 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2260 flags |= g_typeadjust (ltype, rtype);
2263 /* If the left side is an unsigned and the right is a constant,
2264 ** we may be able to change the compares to something more
2267 if (!LeftSigned && rconst) {
2272 if (Expr2.IVal == 1) {
2273 /* An unsigned compare to one means that the value
2282 if (Expr2.IVal == 0) {
2283 /* An unsigned compare to zero means that the value
2291 if (Expr2.IVal == 1) {
2292 /* An unsigned compare to one means that the value
2293 ** must not be zero.
2301 if (Expr2.IVal == 0) {
2302 /* An unsigned compare to zero means that the value
2303 ** must not be zero.
2317 GenFunc (flags, Expr2.IVal);
2319 /* The result is an rvalue in the primary */
2320 ED_MakeRValExpr (Expr);
2323 /* Result type is always int */
2324 Expr->Type = type_int;
2326 Done: /* Condition codes are set */
2333 static void hie9 (ExprDesc *Expr)
2334 /* Process * and / operators. */
2336 static const GenDesc hie9_ops[] = {
2337 { TOK_STAR, GEN_NOPUSH | GEN_COMM, g_mul },
2338 { TOK_DIV, GEN_NOPUSH, g_div },
2339 { TOK_MOD, GEN_NOPUSH, g_mod },
2340 { TOK_INVALID, 0, 0 }
2344 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2349 static void parseadd (ExprDesc* Expr)
2350 /* Parse an expression with the binary plus operator. Expr contains the
2351 ** unprocessed left hand side of the expression and will contain the
2352 ** result of the expression on return.
2356 unsigned flags; /* Operation flags */
2357 CodeMark Mark; /* Remember code position */
2358 Type* lhst; /* Type of left hand side */
2359 Type* rhst; /* Type of right hand side */
2362 /* Skip the PLUS token */
2365 /* Get the left hand side type, initialize operation flags */
2369 /* Check for constness on both sides */
2370 if (ED_IsConst (Expr)) {
2372 /* The left hand side is a constant of some sort. Good. Get rhs */
2373 ExprWithCheck (hie9, &Expr2);
2374 if (ED_IsConstAbs (&Expr2)) {
2376 /* Right hand side is a constant numeric value. Get the rhs type */
2379 /* Both expressions are constants. Check for pointer arithmetic */
2380 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2381 /* Left is pointer, right is int, must scale rhs */
2382 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2383 /* Result type is a pointer */
2384 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2385 /* Left is int, right is pointer, must scale lhs */
2386 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2387 /* Result type is a pointer */
2388 Expr->Type = Expr2.Type;
2389 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2390 /* Integer addition */
2391 Expr->IVal += Expr2.IVal;
2392 typeadjust (Expr, &Expr2, 1);
2395 Error ("Invalid operands for binary operator `+'");
2400 /* lhs is a constant and rhs is not constant. Load rhs into
2403 LoadExpr (CF_NONE, &Expr2);
2405 /* Beware: The check above (for lhs) lets not only pass numeric
2406 ** constants, but also constant addresses (labels), maybe even
2407 ** with an offset. We have to check for that here.
2410 /* First, get the rhs type. */
2414 if (ED_IsLocAbs (Expr)) {
2415 /* A numerical constant */
2418 /* Constant address label */
2419 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2422 /* Check for pointer arithmetic */
2423 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2424 /* Left is pointer, right is int, must scale rhs */
2425 g_scale (CF_INT, CheckedPSizeOf (lhst));
2426 /* Operate on pointers, result type is a pointer */
2428 /* Generate the code for the add */
2429 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2430 /* Numeric constant */
2431 g_inc (flags, Expr->IVal);
2433 /* Constant address */
2434 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2436 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2438 /* Left is int, right is pointer, must scale lhs. */
2439 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2441 /* Operate on pointers, result type is a pointer */
2443 Expr->Type = Expr2.Type;
2445 /* Since we do already have rhs in the primary, if lhs is
2446 ** not a numeric constant, and the scale factor is not one
2447 ** (no scaling), we must take the long way over the stack.
2449 if (ED_IsLocAbs (Expr)) {
2450 /* Numeric constant, scale lhs */
2451 Expr->IVal *= ScaleFactor;
2452 /* Generate the code for the add */
2453 g_inc (flags, Expr->IVal);
2454 } else if (ScaleFactor == 1) {
2455 /* Constant address but no need to scale */
2456 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2458 /* Constant address that must be scaled */
2459 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2460 g_getimmed (flags, Expr->Name, Expr->IVal);
2461 g_scale (CF_PTR, ScaleFactor);
2464 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2465 /* Integer addition */
2466 flags |= typeadjust (Expr, &Expr2, 1);
2467 /* Generate the code for the add */
2468 if (ED_IsLocAbs (Expr)) {
2469 /* Numeric constant */
2470 g_inc (flags, Expr->IVal);
2472 /* Constant address */
2473 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2477 Error ("Invalid operands for binary operator `+'");
2481 /* Result is a rvalue in primary register */
2482 ED_MakeRValExpr (Expr);
2487 /* Left hand side is not constant. Get the value onto the stack. */
2488 LoadExpr (CF_NONE, Expr); /* --> primary register */
2490 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2492 /* Evaluate the rhs */
2493 MarkedExprWithCheck (hie9, &Expr2);
2495 /* Check for a constant rhs expression */
2496 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2498 /* Right hand side is a constant. Get the rhs type */
2501 /* Remove pushed value from stack */
2504 /* Check for pointer arithmetic */
2505 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2506 /* Left is pointer, right is int, must scale rhs */
2507 Expr2.IVal *= CheckedPSizeOf (lhst);
2508 /* Operate on pointers, result type is a pointer */
2510 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2511 /* Left is int, right is pointer, must scale lhs (ptr only) */
2512 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2513 /* Operate on pointers, result type is a pointer */
2515 Expr->Type = Expr2.Type;
2516 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2517 /* Integer addition */
2518 flags = typeadjust (Expr, &Expr2, 1);
2521 Error ("Invalid operands for binary operator `+'");
2525 /* Generate code for the add */
2526 g_inc (flags | CF_CONST, Expr2.IVal);
2530 /* Not constant, load into the primary */
2531 LoadExpr (CF_NONE, &Expr2);
2533 /* lhs and rhs are not constant. Get the rhs type. */
2536 /* Check for pointer arithmetic */
2537 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2538 /* Left is pointer, right is int, must scale rhs */
2539 g_scale (CF_INT, CheckedPSizeOf (lhst));
2540 /* Operate on pointers, result type is a pointer */
2542 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2543 /* Left is int, right is pointer, must scale lhs */
2544 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2545 g_swap (CF_INT); /* Swap TOS and primary */
2546 g_scale (CF_INT, CheckedPSizeOf (rhst));
2547 /* Operate on pointers, result type is a pointer */
2549 Expr->Type = Expr2.Type;
2550 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2551 /* Integer addition. Note: Result is never constant.
2552 ** Problem here is that typeadjust does not know if the
2553 ** variable is an rvalue or lvalue, so if both operands
2554 ** are dereferenced constant numeric addresses, typeadjust
2555 ** thinks the operation works on constants. Removing
2556 ** CF_CONST here means handling the symptoms, however, the
2557 ** whole parser is such a mess that I fear to break anything
2558 ** when trying to apply another solution.
2560 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2563 Error ("Invalid operands for binary operator `+'");
2567 /* Generate code for the add */
2572 /* Result is a rvalue in primary register */
2573 ED_MakeRValExpr (Expr);
2576 /* Condition codes not set */
2577 ED_MarkAsUntested (Expr);
2583 static void parsesub (ExprDesc* Expr)
2584 /* Parse an expression with the binary minus operator. Expr contains the
2585 ** unprocessed left hand side of the expression and will contain the
2586 ** result of the expression on return.
2590 unsigned flags; /* Operation flags */
2591 Type* lhst; /* Type of left hand side */
2592 Type* rhst; /* Type of right hand side */
2593 CodeMark Mark1; /* Save position of output queue */
2594 CodeMark Mark2; /* Another position in the queue */
2595 int rscale; /* Scale factor for the result */
2598 /* Skip the MINUS token */
2601 /* Get the left hand side type, initialize operation flags */
2603 rscale = 1; /* Scale by 1, that is, don't scale */
2605 /* Remember the output queue position, then bring the value onto the stack */
2606 GetCodePos (&Mark1);
2607 LoadExpr (CF_NONE, Expr); /* --> primary register */
2608 GetCodePos (&Mark2);
2609 g_push (TypeOf (lhst), 0); /* --> stack */
2611 /* Parse the right hand side */
2612 MarkedExprWithCheck (hie9, &Expr2);
2614 /* Check for a constant rhs expression */
2615 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2617 /* The right hand side is constant. Get the rhs type. */
2620 /* Check left hand side */
2621 if (ED_IsConstAbs (Expr)) {
2623 /* Both sides are constant, remove generated code */
2624 RemoveCode (&Mark1);
2626 /* Check for pointer arithmetic */
2627 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2628 /* Left is pointer, right is int, must scale rhs */
2629 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2630 /* Operate on pointers, result type is a pointer */
2631 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2632 /* Left is pointer, right is pointer, must scale result */
2633 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2634 Error ("Incompatible pointer types");
2636 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2637 CheckedPSizeOf (lhst);
2639 /* Operate on pointers, result type is an integer */
2640 Expr->Type = type_int;
2641 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2642 /* Integer subtraction */
2643 typeadjust (Expr, &Expr2, 1);
2644 Expr->IVal -= Expr2.IVal;
2647 Error ("Invalid operands for binary operator `-'");
2650 /* Result is constant, condition codes not set */
2651 ED_MarkAsUntested (Expr);
2655 /* Left hand side is not constant, right hand side is.
2656 ** Remove pushed value from stack.
2658 RemoveCode (&Mark2);
2660 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2661 /* Left is pointer, right is int, must scale rhs */
2662 Expr2.IVal *= 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 */
2677 flags = typeadjust (Expr, &Expr2, 1);
2680 Error ("Invalid operands for binary operator `-'");
2684 /* Do the subtraction */
2685 g_dec (flags | CF_CONST, Expr2.IVal);
2687 /* If this was a pointer subtraction, we must scale the result */
2689 g_scale (flags, -rscale);
2692 /* Result is a rvalue in the primary register */
2693 ED_MakeRValExpr (Expr);
2694 ED_MarkAsUntested (Expr);
2700 /* Not constant, load into the primary */
2701 LoadExpr (CF_NONE, &Expr2);
2703 /* Right hand side is not constant. Get the rhs type. */
2706 /* Check for pointer arithmetic */
2707 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2708 /* Left is pointer, right is int, must scale rhs */
2709 g_scale (CF_INT, CheckedPSizeOf (lhst));
2710 /* Operate on pointers, result type is a pointer */
2712 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2713 /* Left is pointer, right is pointer, must scale result */
2714 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2715 Error ("Incompatible pointer types");
2717 rscale = CheckedPSizeOf (lhst);
2719 /* Operate on pointers, result type is an integer */
2721 Expr->Type = type_int;
2722 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2723 /* Integer subtraction. If the left hand side descriptor says that
2724 ** the lhs is const, we have to remove this mark, since this is no
2725 ** longer true, lhs is on stack instead.
2727 if (ED_IsLocAbs (Expr)) {
2728 ED_MakeRValExpr (Expr);
2730 /* Adjust operand types */
2731 flags = typeadjust (Expr, &Expr2, 0);
2734 Error ("Invalid operands for binary operator `-'");
2738 /* Generate code for the sub (the & is a hack here) */
2739 g_sub (flags & ~CF_CONST, 0);
2741 /* If this was a pointer subtraction, we must scale the result */
2743 g_scale (flags, -rscale);
2746 /* Result is a rvalue in the primary register */
2747 ED_MakeRValExpr (Expr);
2748 ED_MarkAsUntested (Expr);
2754 void hie8 (ExprDesc* Expr)
2755 /* Process + and - binary operators. */
2757 ExprWithCheck (hie9, Expr);
2758 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2759 if (CurTok.Tok == TOK_PLUS) {
2769 static void hie6 (ExprDesc* Expr)
2770 /* Handle greater-than type comparators */
2772 static const GenDesc hie6_ops [] = {
2773 { TOK_LT, GEN_NOPUSH, g_lt },
2774 { TOK_LE, GEN_NOPUSH, g_le },
2775 { TOK_GE, GEN_NOPUSH, g_ge },
2776 { TOK_GT, GEN_NOPUSH, g_gt },
2777 { TOK_INVALID, 0, 0 }
2779 hie_compare (hie6_ops, Expr, ShiftExpr);
2784 static void hie5 (ExprDesc* Expr)
2785 /* Handle == and != */
2787 static const GenDesc hie5_ops[] = {
2788 { TOK_EQ, GEN_NOPUSH, g_eq },
2789 { TOK_NE, GEN_NOPUSH, g_ne },
2790 { TOK_INVALID, 0, 0 }
2792 hie_compare (hie5_ops, Expr, hie6);
2797 static void hie4 (ExprDesc* Expr)
2798 /* Handle & (bitwise and) */
2800 static const GenDesc hie4_ops[] = {
2801 { TOK_AND, GEN_NOPUSH | GEN_COMM, g_and },
2802 { TOK_INVALID, 0, 0 }
2806 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2811 static void hie3 (ExprDesc* Expr)
2812 /* Handle ^ (bitwise exclusive or) */
2814 static const GenDesc hie3_ops[] = {
2815 { TOK_XOR, GEN_NOPUSH | GEN_COMM, g_xor },
2816 { TOK_INVALID, 0, 0 }
2820 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2825 static void hie2 (ExprDesc* Expr)
2826 /* Handle | (bitwise or) */
2828 static const GenDesc hie2_ops[] = {
2829 { TOK_OR, GEN_NOPUSH | GEN_COMM, g_or },
2830 { TOK_INVALID, 0, 0 }
2834 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2839 static void hieAndPP (ExprDesc* Expr)
2840 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2841 ** called recursively from the preprocessor.
2846 ConstAbsIntExpr (hie2, Expr);
2847 while (CurTok.Tok == TOK_BOOL_AND) {
2853 ConstAbsIntExpr (hie2, &Expr2);
2855 /* Combine the two */
2856 Expr->IVal = (Expr->IVal && Expr2.IVal);
2862 static void hieOrPP (ExprDesc *Expr)
2863 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2864 ** called recursively from the preprocessor.
2869 ConstAbsIntExpr (hieAndPP, Expr);
2870 while (CurTok.Tok == TOK_BOOL_OR) {
2876 ConstAbsIntExpr (hieAndPP, &Expr2);
2878 /* Combine the two */
2879 Expr->IVal = (Expr->IVal || Expr2.IVal);
2885 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2886 /* Process "exp && exp" */
2891 ExprWithCheck (hie2, Expr);
2892 if (CurTok.Tok == TOK_BOOL_AND) {
2894 /* Tell our caller that we're evaluating a boolean */
2897 /* Get a label that we will use for false expressions */
2898 FalseLab = GetLocalLabel ();
2900 /* If the expr hasn't set condition codes, set the force-test flag */
2901 if (!ED_IsTested (Expr)) {
2902 ED_MarkForTest (Expr);
2905 /* Load the value */
2906 LoadExpr (CF_FORCECHAR, Expr);
2908 /* Generate the jump */
2909 g_falsejump (CF_NONE, FalseLab);
2911 /* Parse more boolean and's */
2912 while (CurTok.Tok == TOK_BOOL_AND) {
2919 if (!ED_IsTested (&Expr2)) {
2920 ED_MarkForTest (&Expr2);
2922 LoadExpr (CF_FORCECHAR, &Expr2);
2924 /* Do short circuit evaluation */
2925 if (CurTok.Tok == TOK_BOOL_AND) {
2926 g_falsejump (CF_NONE, FalseLab);
2928 /* Last expression - will evaluate to true */
2929 g_truejump (CF_NONE, TrueLab);
2933 /* Define the false jump label here */
2934 g_defcodelabel (FalseLab);
2936 /* The result is an rvalue in primary */
2937 ED_MakeRValExpr (Expr);
2938 ED_TestDone (Expr); /* Condition codes are set */
2944 static void hieOr (ExprDesc *Expr)
2945 /* Process "exp || exp". */
2948 int BoolOp = 0; /* Did we have a boolean op? */
2949 int AndOp; /* Did we have a && operation? */
2950 unsigned TrueLab; /* Jump to this label if true */
2954 TrueLab = GetLocalLabel ();
2956 /* Call the next level parser */
2957 hieAnd (Expr, TrueLab, &BoolOp);
2959 /* Any boolean or's? */
2960 if (CurTok.Tok == TOK_BOOL_OR) {
2962 /* If the expr hasn't set condition codes, set the force-test flag */
2963 if (!ED_IsTested (Expr)) {
2964 ED_MarkForTest (Expr);
2967 /* Get first expr */
2968 LoadExpr (CF_FORCECHAR, Expr);
2970 /* For each expression jump to TrueLab if true. Beware: If we
2971 ** had && operators, the jump is already in place!
2974 g_truejump (CF_NONE, TrueLab);
2977 /* Remember that we had a boolean op */
2980 /* while there's more expr */
2981 while (CurTok.Tok == TOK_BOOL_OR) {
2988 hieAnd (&Expr2, TrueLab, &AndOp);
2989 if (!ED_IsTested (&Expr2)) {
2990 ED_MarkForTest (&Expr2);
2992 LoadExpr (CF_FORCECHAR, &Expr2);
2994 /* If there is more to come, add shortcut boolean eval. */
2995 g_truejump (CF_NONE, TrueLab);
2999 /* The result is an rvalue in primary */
3000 ED_MakeRValExpr (Expr);
3001 ED_TestDone (Expr); /* Condition codes are set */
3004 /* If we really had boolean ops, generate the end sequence */
3006 DoneLab = GetLocalLabel ();
3007 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
3008 g_falsejump (CF_NONE, DoneLab);
3009 g_defcodelabel (TrueLab);
3010 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
3011 g_defcodelabel (DoneLab);
3017 static void hieQuest (ExprDesc* Expr)
3018 /* Parse the ternary operator */
3022 CodeMark TrueCodeEnd;
3023 ExprDesc Expr2; /* Expression 2 */
3024 ExprDesc Expr3; /* Expression 3 */
3025 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
3026 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
3027 Type* ResultType; /* Type of result */
3030 /* Call the lower level eval routine */
3031 if (Preprocessing) {
3032 ExprWithCheck (hieOrPP, Expr);
3034 ExprWithCheck (hieOr, Expr);
3037 /* Check if it's a ternary expression */
3038 if (CurTok.Tok == TOK_QUEST) {
3040 if (!ED_IsTested (Expr)) {
3041 /* Condition codes not set, request a test */
3042 ED_MarkForTest (Expr);
3044 LoadExpr (CF_NONE, Expr);
3045 FalseLab = GetLocalLabel ();
3046 g_falsejump (CF_NONE, FalseLab);
3048 /* Parse second expression. Remember for later if it is a NULL pointer
3049 ** expression, then load it into the primary.
3051 ExprWithCheck (hie1, &Expr2);
3052 Expr2IsNULL = ED_IsNullPtr (&Expr2);
3053 if (!IsTypeVoid (Expr2.Type)) {
3054 /* Load it into the primary */
3055 LoadExpr (CF_NONE, &Expr2);
3056 ED_MakeRValExpr (&Expr2);
3057 Expr2.Type = PtrConversion (Expr2.Type);
3060 /* Remember the current code position */
3061 GetCodePos (&TrueCodeEnd);
3063 /* Jump around the evaluation of the third expression */
3064 TrueLab = GetLocalLabel ();
3068 /* Jump here if the first expression was false */
3069 g_defcodelabel (FalseLab);
3071 /* Parse third expression. Remember for later if it is a NULL pointer
3072 ** expression, then load it into the primary.
3074 ExprWithCheck (hie1, &Expr3);
3075 Expr3IsNULL = ED_IsNullPtr (&Expr3);
3076 if (!IsTypeVoid (Expr3.Type)) {
3077 /* Load it into the primary */
3078 LoadExpr (CF_NONE, &Expr3);
3079 ED_MakeRValExpr (&Expr3);
3080 Expr3.Type = PtrConversion (Expr3.Type);
3083 /* Check if any conversions are needed, if so, do them.
3084 ** Conversion rules for ?: expression are:
3085 ** - if both expressions are int expressions, default promotion
3086 ** rules for ints apply.
3087 ** - if both expressions are pointers of the same type, the
3088 ** result of the expression is of this type.
3089 ** - if one of the expressions is a pointer and the other is
3090 ** a zero constant, the resulting type is that of the pointer
3092 ** - if both expressions are void expressions, the result is of
3094 ** - all other cases are flagged by an error.
3096 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
3098 CodeMark CvtCodeStart;
3099 CodeMark CvtCodeEnd;
3102 /* Get common type */
3103 ResultType = promoteint (Expr2.Type, Expr3.Type);
3105 /* Convert the third expression to this type if needed */
3106 TypeConversion (&Expr3, ResultType);
3108 /* Emit conversion code for the second expression, but remember
3109 ** where it starts end ends.
3111 GetCodePos (&CvtCodeStart);
3112 TypeConversion (&Expr2, ResultType);
3113 GetCodePos (&CvtCodeEnd);
3115 /* If we had conversion code, move it to the right place */
3116 if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
3117 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
3120 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
3121 /* Must point to same type */
3122 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
3123 Error ("Incompatible pointer types");
3125 /* Result has the common type */
3126 ResultType = Expr2.Type;
3127 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
3128 /* Result type is pointer, no cast needed */
3129 ResultType = Expr2.Type;
3130 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
3131 /* Result type is pointer, no cast needed */
3132 ResultType = Expr3.Type;
3133 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
3134 /* Result type is void */
3135 ResultType = Expr3.Type;
3137 Error ("Incompatible types");
3138 ResultType = Expr2.Type; /* Doesn't matter here */
3141 /* Define the final label */
3142 g_defcodelabel (TrueLab);
3144 /* Setup the target expression */
3145 ED_MakeRValExpr (Expr);
3146 Expr->Type = ResultType;
3152 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
3153 /* Process "op=" operators. */
3160 /* op= can only be used with lvalues */
3161 if (!ED_IsLVal (Expr)) {
3162 Error ("Invalid lvalue in assignment");
3166 /* The left side must not be const qualified */
3167 if (IsQualConst (Expr->Type)) {
3168 Error ("Assignment to const");
3171 /* There must be an integer or pointer on the left side */
3172 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3173 Error ("Invalid left operand type");
3174 /* Continue. Wrong code will be generated, but the compiler won't
3175 ** break, so this is the best error recovery.
3179 /* Skip the operator token */
3182 /* Determine the type of the lhs */
3183 flags = TypeOf (Expr->Type);
3184 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
3186 /* Get the lhs address on stack (if needed) */
3189 /* Fetch the lhs into the primary register if needed */
3190 LoadExpr (CF_NONE, Expr);
3192 /* Bring the lhs on stack */
3196 /* Evaluate the rhs */
3197 MarkedExprWithCheck (hie1, &Expr2);
3199 /* The rhs must be an integer (or a float, but we don't support that yet */
3200 if (!IsClassInt (Expr2.Type)) {
3201 Error ("Invalid right operand for binary operator `%s'", Op);
3202 /* Continue. Wrong code will be generated, but the compiler won't
3203 ** break, so this is the best error recovery.
3207 /* Check for a constant expression */
3208 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
3209 /* The resulting value is a constant. If the generator has the NOPUSH
3210 ** flag set, don't push the lhs.
3212 if (Gen->Flags & GEN_NOPUSH) {
3216 /* lhs is a pointer, scale rhs */
3217 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
3220 /* If the lhs is character sized, the operation may be later done
3223 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3224 flags |= CF_FORCECHAR;
3227 /* Special handling for add and sub - some sort of a hack, but short code */
3228 if (Gen->Func == g_add) {
3229 g_inc (flags | CF_CONST, Expr2.IVal);
3230 } else if (Gen->Func == g_sub) {
3231 g_dec (flags | CF_CONST, Expr2.IVal);
3233 if (Expr2.IVal == 0) {
3234 /* Check for div by zero/mod by zero */
3235 if (Gen->Func == g_div) {
3236 Error ("Division by zero");
3237 } else if (Gen->Func == g_mod) {
3238 Error ("Modulo operation with zero");
3241 Gen->Func (flags | CF_CONST, Expr2.IVal);
3245 /* rhs is not constant. Load into the primary */
3246 LoadExpr (CF_NONE, &Expr2);
3248 /* lhs is a pointer, scale rhs */
3249 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
3252 /* If the lhs is character sized, the operation may be later done
3255 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3256 flags |= CF_FORCECHAR;
3259 /* Adjust the types of the operands if needed */
3260 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
3263 ED_MakeRValExpr (Expr);
3268 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3269 /* Process the += and -= operators */
3277 /* We're currently only able to handle some adressing modes */
3278 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3279 /* Use generic routine */
3280 opeq (Gen, Expr, Op);
3284 /* We must have an lvalue */
3285 if (ED_IsRVal (Expr)) {
3286 Error ("Invalid lvalue in assignment");
3290 /* The left side must not be const qualified */
3291 if (IsQualConst (Expr->Type)) {
3292 Error ("Assignment to const");
3295 /* There must be an integer or pointer on the left side */
3296 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3297 Error ("Invalid left operand type");
3298 /* Continue. Wrong code will be generated, but the compiler won't
3299 ** break, so this is the best error recovery.
3303 /* Skip the operator */
3306 /* Check if we have a pointer expression and must scale rhs */
3307 MustScale = IsTypePtr (Expr->Type);
3309 /* Initialize the code generator flags */
3313 /* Evaluate the rhs. We expect an integer here, since float is not
3317 if (!IsClassInt (Expr2.Type)) {
3318 Error ("Invalid right operand for binary operator `%s'", Op);
3319 /* Continue. Wrong code will be generated, but the compiler won't
3320 ** break, so this is the best error recovery.
3323 if (ED_IsConstAbs (&Expr2)) {
3324 /* The resulting value is a constant. Scale it. */
3326 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3331 /* Not constant, load into the primary */
3332 LoadExpr (CF_NONE, &Expr2);
3334 /* lhs is a pointer, scale rhs */
3335 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3339 /* Setup the code generator flags */
3340 lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3341 rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3343 /* Convert the type of the lhs to that of the rhs */
3344 g_typecast (lflags, rflags);
3346 /* Output apropriate code depending on the location */
3347 switch (ED_GetLoc (Expr)) {
3350 /* Absolute: numeric address or const */
3351 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3352 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3354 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3359 /* Global variable */
3360 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3361 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3363 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3369 /* Static variable or literal in the literal pool */
3370 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3371 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3373 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3377 case E_LOC_REGISTER:
3378 /* Register variable */
3379 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3380 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3382 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3387 /* Value on the stack */
3388 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3389 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3391 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3396 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3399 /* Expression is a rvalue in the primary now */
3400 ED_MakeRValExpr (Expr);
3405 void hie1 (ExprDesc* Expr)
3406 /* Parse first level of expression hierarchy. */
3409 switch (CurTok.Tok) {
3415 case TOK_PLUS_ASSIGN:
3416 addsubeq (&GenPASGN, Expr, "+=");
3419 case TOK_MINUS_ASSIGN:
3420 addsubeq (&GenSASGN, Expr, "-=");
3423 case TOK_MUL_ASSIGN:
3424 opeq (&GenMASGN, Expr, "*=");
3427 case TOK_DIV_ASSIGN:
3428 opeq (&GenDASGN, Expr, "/=");
3431 case TOK_MOD_ASSIGN:
3432 opeq (&GenMOASGN, Expr, "%=");
3435 case TOK_SHL_ASSIGN:
3436 opeq (&GenSLASGN, Expr, "<<=");
3439 case TOK_SHR_ASSIGN:
3440 opeq (&GenSRASGN, Expr, ">>=");
3443 case TOK_AND_ASSIGN:
3444 opeq (&GenAASGN, Expr, "&=");
3447 case TOK_XOR_ASSIGN:
3448 opeq (&GenXOASGN, Expr, "^=");
3452 opeq (&GenOASGN, Expr, "|=");
3462 void hie0 (ExprDesc *Expr)
3463 /* Parse comma operator. */
3466 while (CurTok.Tok == TOK_COMMA) {
3474 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3475 /* Will evaluate an expression via the given function. If the result is a
3476 ** constant, 0 is returned and the value is put in the Expr struct. If the
3477 ** result is not constant, LoadExpr is called to bring the value into the
3478 ** primary register and 1 is returned.
3482 ExprWithCheck (Func, Expr);
3484 /* Check for a constant expression */
3485 if (ED_IsConstAbs (Expr)) {
3486 /* Constant expression */
3489 /* Not constant, load into the primary */
3490 LoadExpr (Flags, Expr);
3497 void Expression0 (ExprDesc* Expr)
3498 /* Evaluate an expression via hie0 and put the result into the primary register */
3500 ExprWithCheck (hie0, Expr);
3501 LoadExpr (CF_NONE, Expr);
3506 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3507 /* Will evaluate an expression via the given function. If the result is not
3508 ** a constant of some sort, a diagnostic will be printed, and the value is
3509 ** replaced by a constant one to make sure there are no internal errors that
3510 ** result from this input error.
3513 ExprWithCheck (Func, Expr);
3514 if (!ED_IsConst (Expr)) {
3515 Error ("Constant expression expected");
3516 /* To avoid any compiler errors, make the expression a valid const */
3517 ED_MakeConstAbsInt (Expr, 1);
3523 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3524 /* Will evaluate an expression via the given function. If the result is not
3525 ** something that may be evaluated in a boolean context, a diagnostic will be
3526 ** printed, and the value is replaced by a constant one to make sure there
3527 ** are no internal errors that result from this input error.
3530 ExprWithCheck (Func, Expr);
3531 if (!ED_IsBool (Expr)) {
3532 Error ("Boolean expression expected");
3533 /* To avoid any compiler errors, make the expression a valid int */
3534 ED_MakeConstAbsInt (Expr, 1);
3540 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3541 /* Will evaluate an expression via the given function. If the result is not
3542 ** a constant numeric integer value, a diagnostic will be printed, and the
3543 ** value is replaced by a constant one to make sure there are no internal
3544 ** errors that result from this input error.
3547 ExprWithCheck (Func, Expr);
3548 if (!ED_IsConstAbsInt (Expr)) {
3549 Error ("Constant integer expression expected");
3550 /* To avoid any compiler errors, make the expression a valid const */
3551 ED_MakeConstAbsInt (Expr, 1);