3 * Ullrich von Bassewitz, 21.06.1998
13 #include "debugflag.h"
20 #include "assignment.h"
40 /*****************************************************************************/
42 /*****************************************************************************/
46 /* Generator attributes */
47 #define GEN_NOPUSH 0x01 /* Don't push lhs */
49 /* Map a generator function and its attributes to a token */
51 token_t Tok; /* Token to map to */
52 unsigned Flags; /* Flags for generator function */
53 void (*Func) (unsigned, unsigned long); /* Generator func */
56 /* Descriptors for the operations */
57 static GenDesc GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add };
58 static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub };
59 static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul };
60 static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div };
61 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod };
62 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl };
63 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr };
64 static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and };
65 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor };
66 static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or };
70 /*****************************************************************************/
71 /* Function forwards */
72 /*****************************************************************************/
76 void hie0 (ExprDesc *lval);
77 /* Parse comma operator. */
81 /*****************************************************************************/
82 /* Helper functions */
83 /*****************************************************************************/
87 static unsigned GlobalModeFlags (unsigned Flags)
88 /* Return the addressing mode flags for the variable with the given flags */
90 switch (Flags & E_MASK_LOC) {
91 case E_LOC_GLOBAL: return CF_EXTERNAL;
92 case E_LOC_STATIC: return CF_STATIC;
93 case E_LOC_REGISTER: return CF_REGVAR;
95 Internal ("GlobalModeFlags: Invalid flags value: %u", Flags);
101 void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc *Expr)
102 /* Call an expression function with checks. */
104 /* Remember the stack pointer */
105 int OldSP = StackPtr;
107 /* Call the expression function */
110 /* Do some checks if code generation is still constistent */
111 if (StackPtr != OldSP) {
114 "Code generation messed up!\n"
115 "StackPtr is %d, should be %d",
118 Internal ("StackPtr is %d, should be %d\n", StackPtr, OldSP);
125 static type* promoteint (type* lhst, type* rhst)
126 /* In an expression with two ints, return the type of the result */
128 /* Rules for integer types:
129 * - If one of the values is a long, the result is long.
130 * - If one of the values is unsigned, the result is also unsigned.
131 * - Otherwise the result is an int.
133 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
134 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
140 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
150 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
151 /* Adjust the two values for a binary operation. lhs is expected on stack or
152 * to be constant, rhs is expected to be in the primary register or constant.
153 * The function will put the type of the result into lhs and return the
154 * code generator flags for the operation.
155 * If NoPush is given, it is assumed that the operation does not expect the lhs
156 * to be on stack, and that lhs is in a register instead.
157 * Beware: The function does only accept int types.
160 unsigned ltype, rtype;
163 /* Get the type strings */
164 type* lhst = lhs->Type;
165 type* rhst = rhs->Type;
167 /* Generate type adjustment code if needed */
168 ltype = TypeOf (lhst);
169 if (ED_IsLocAbs (lhs)) {
173 /* Value is in primary register*/
176 rtype = TypeOf (rhst);
177 if (ED_IsLocAbs (rhs)) {
180 flags = g_typeadjust (ltype, rtype);
182 /* Set the type of the result */
183 lhs->Type = promoteint (lhst, rhst);
185 /* Return the code generator flags */
191 void DefineData (ExprDesc* Expr)
192 /* Output a data definition for the given expression */
194 switch (ED_GetLoc (Expr)) {
197 /* Absolute: numeric address or const */
198 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
202 /* Global variable */
203 g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal);
208 /* Static variable or literal in the literal pool */
209 g_defdata (CF_STATIC, Expr->Name, Expr->IVal);
213 /* Register variable. Taking the address is usually not
216 if (IS_Get (&AllowRegVarAddr) == 0) {
217 Error ("Cannot take the address of a register variable");
219 g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
223 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
229 static void LoadConstant (unsigned Flags, ExprDesc* Expr)
230 /* Load the primary register with some constant value. */
232 switch (ED_GetLoc (Expr)) {
235 /* Number constant */
236 g_getimmed (Flags | TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0);
240 /* Global symbol, load address */
241 g_getimmed ((Flags | CF_EXTERNAL) & ~CF_CONST, Expr->Name, Expr->IVal);
246 /* Static symbol or literal, load address */
247 g_getimmed ((Flags | CF_STATIC) & ~CF_CONST, Expr->Name, Expr->IVal);
251 /* Register variable. Taking the address is usually not
254 if (IS_Get (&AllowRegVarAddr) == 0) {
255 Error ("Cannot take the address of a register variable");
257 g_getimmed ((Flags | CF_REGVAR) & ~CF_CONST, Expr->Name, Expr->IVal);
260 g_leasp (Expr->IVal);
264 Internal ("Unknown constant type: %04X", Expr->Flags);
270 static int kcalc (token_t tok, long val1, long val2)
271 /* Calculate an operation with left and right operand constant. */
275 return (val1 == val2);
277 return (val1 != val2);
279 return (val1 < val2);
281 return (val1 <= val2);
283 return (val1 >= val2);
285 return (val1 > val2);
287 return (val1 | val2);
289 return (val1 ^ val2);
291 return (val1 & val2);
293 return (val1 >> val2);
295 return (val1 << val2);
297 return (val1 * val2);
300 Error ("Division by zero");
303 return (val1 / val2);
306 Error ("Modulo operation with zero");
309 return (val1 % val2);
311 Internal ("kcalc: got token 0x%X\n", tok);
318 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
319 /* Find a token in a generator table */
321 while (Table->Tok != TOK_INVALID) {
322 if (Table->Tok == Tok) {
332 static int TypeSpecAhead (void)
333 /* Return true if some sort of type is waiting (helper for cast and sizeof()
339 /* There's a type waiting if:
341 * We have an opening paren, and
342 * a. the next token is a type, or
343 * b. the next token is a type qualifier, or
344 * c. the next token is a typedef'd type
346 return CurTok.Tok == TOK_LPAREN && (
347 TokIsType (&NextTok) ||
348 TokIsTypeQual (&NextTok) ||
349 (NextTok.Tok == TOK_IDENT &&
350 (Entry = FindSym (NextTok.Ident)) != 0 &&
351 SymIsTypeDef (Entry)));
356 void PushAddr (const ExprDesc* Expr)
357 /* If the expression contains an address that was somehow evaluated,
358 * push this address on the stack. This is a helper function for all
359 * sorts of implicit or explicit assignment functions where the lvalue
360 * must be saved if it's not constant, before evaluating the rhs.
363 /* Get the address on stack if needed */
364 if (ED_IsLocExpr (Expr)) {
365 /* Push the address (always a pointer) */
372 /*****************************************************************************/
374 /*****************************************************************************/
378 void ExprLoad (unsigned Flags, ExprDesc* Expr)
379 /* Place the result of an expression into the primary register if it is not
383 if (ED_IsLVal (Expr)) {
385 /* Dereferenced lvalue */
386 Flags |= TypeOf (Expr->Type);
387 if (ED_NeedsTest (Expr)) {
391 switch (ED_GetLoc (Expr)) {
394 /* Absolute: numeric address or const */
395 g_getstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0);
399 /* Global variable */
400 g_getstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal);
405 /* Static variable or literal in the literal pool */
406 g_getstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal);
410 /* Register variable */
411 g_getstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal);
415 /* Value on the stack */
416 g_getlocal (Flags, Expr->IVal);
420 /* The primary register - just test if necessary */
421 if (Flags & CF_TEST) {
427 /* Reference to address in primary with offset in Expr */
428 g_getind (Flags, Expr->IVal);
432 Internal ("Invalid location in ExprLoad: 0x%04X", ED_GetLoc (Expr));
435 /* Expression was tested */
440 if (ED_IsLocExpr (Expr)) {
441 if (Expr->IVal != 0) {
442 /* We have an expression in the primary plus a constant
443 * offset. Adjust the value in the primary accordingly.
445 Flags |= TypeOf (Expr->Type);
446 g_inc (Flags | CF_CONST, Expr->IVal);
449 /* Constant of some sort, load it into the primary */
450 LoadConstant (Flags, Expr);
453 /* Are we testing this value? */
454 if (ED_NeedsTest (Expr)) {
455 /* Yes, force a test */
456 Flags |= TypeOf (Expr->Type);
465 static unsigned FunctionParamList (FuncDesc* Func)
466 /* Parse a function parameter list and pass the parameters to the called
467 * function. Depending on several criteria this may be done by just pushing
468 * each parameter separately, or creating the parameter frame once and then
469 * storing into this frame.
470 * The function returns the size of the parameters pushed.
475 /* Initialize variables */
476 SymEntry* Param = 0; /* Keep gcc silent */
477 unsigned ParamSize = 0; /* Size of parameters pushed */
478 unsigned ParamCount = 0; /* Number of parameters pushed */
479 unsigned FrameSize = 0; /* Size of parameter frame */
480 unsigned FrameParams = 0; /* Number of params in frame */
481 int FrameOffs = 0; /* Offset into parameter frame */
482 int Ellipsis = 0; /* Function is variadic */
484 /* As an optimization, we may allocate the complete parameter frame at
485 * once instead of pushing each parameter as it comes. We may do that,
488 * - optimizations that increase code size are enabled (allocating the
489 * stack frame at once gives usually larger code).
490 * - we have more than one parameter to push (don't count the last param
491 * for __fastcall__ functions).
493 * The FrameSize variable will contain a value > 0 if storing into a frame
494 * (instead of pushing) is enabled.
497 if (CodeSizeFactor >= 200) {
499 /* Calculate the number and size of the parameters */
500 FrameParams = Func->ParamCount;
501 FrameSize = Func->ParamSize;
502 if (FrameParams > 0 && (Func->Flags & FD_FASTCALL) != 0) {
503 /* Last parameter is not pushed */
504 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
508 /* Do we have more than one parameter in the frame? */
509 if (FrameParams > 1) {
510 /* Okeydokey, setup the frame */
511 FrameOffs = StackPtr;
513 StackPtr -= FrameSize;
515 /* Don't use a preallocated frame */
520 /* Parse the actual parameter list */
521 while (CurTok.Tok != TOK_RPAREN) {
525 /* Count arguments */
528 /* Fetch the pointer to the next argument, check for too many args */
529 if (ParamCount <= Func->ParamCount) {
530 /* Beware: If there are parameters with identical names, they
531 * cannot go into the same symbol table, which means that in this
532 * case of errorneous input, the number of nodes in the symbol
533 * table and ParamCount are NOT equal. We have to handle this case
534 * below to avoid segmentation violations. Since we know that this
535 * problem can only occur if there is more than one parameter,
536 * we will just use the last one.
538 if (ParamCount == 1) {
540 Param = Func->SymTab->SymHead;
541 } else if (Param->NextSym != 0) {
543 Param = Param->NextSym;
544 CHECK ((Param->Flags & SC_PARAM) != 0);
546 } else if (!Ellipsis) {
547 /* Too many arguments. Do we have an open param list? */
548 if ((Func->Flags & FD_VARIADIC) == 0) {
549 /* End of param list reached, no ellipsis */
550 Error ("Too many arguments in function call");
552 /* Assume an ellipsis even in case of errors to avoid an error
553 * message for each other argument.
558 /* Evaluate the parameter expression */
561 /* If we don't have an argument spec, accept anything, otherwise
562 * convert the actual argument to the type needed.
566 /* Convert the argument to the parameter type if needed */
567 TypeConversion (&Expr, Param->Type);
569 /* If we have a prototype, chars may be pushed as chars */
570 Flags |= CF_FORCECHAR;
573 /* Load the value into the primary if it is not already there */
574 ExprLoad (Flags, &Expr);
576 /* Use the type of the argument for the push */
577 Flags |= TypeOf (Expr.Type);
579 /* If this is a fastcall function, don't push the last argument */
580 if (ParamCount != Func->ParamCount || (Func->Flags & FD_FASTCALL) == 0) {
581 unsigned ArgSize = sizeofarg (Flags);
583 /* We have the space already allocated, store in the frame.
584 * Because of invalid type conversions (that have produced an
585 * error before), we can end up here with a non aligned stack
586 * frame. Since no output will be generated anyway, handle
587 * these cases gracefully instead of doing a CHECK.
589 if (FrameSize >= ArgSize) {
590 FrameSize -= ArgSize;
594 FrameOffs -= ArgSize;
596 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
598 /* Push the argument */
599 g_push (Flags, Expr.IVal);
602 /* Calculate total parameter size */
603 ParamSize += ArgSize;
606 /* Check for end of argument list */
607 if (CurTok.Tok != TOK_COMMA) {
613 /* Check if we had enough parameters */
614 if (ParamCount < Func->ParamCount) {
615 Error ("Too few arguments in function call");
618 /* The function returns the size of all parameters pushed onto the stack.
619 * However, if there are parameters missing (which is an error and was
620 * flagged by the compiler) AND a stack frame was preallocated above,
621 * we would loose track of the stackpointer and generate an internal error
622 * later. So we correct the value by the parameters that should have been
623 * pushed to avoid an internal compiler error. Since an error was
624 * generated before, no code will be output anyway.
626 return ParamSize + FrameSize;
631 static void FunctionCall (ExprDesc* Expr)
632 /* Perform a function call. */
634 FuncDesc* Func; /* Function descriptor */
635 int IsFuncPtr; /* Flag */
636 int StdFunc; /* Standard function index */
637 unsigned ParamSize; /* Number of parameter bytes */
638 CodeMark Mark = 0; /* Initialize to keep gcc silent */
639 int PtrOffs = 0; /* Offset of function pointer on stack */
640 int IsFastCall = 0; /* True if it's a fast call function */
641 int PtrOnStack = 0; /* True if a pointer copy is on stack */
643 /* Skip the left paren */
646 /* Get a pointer to the function descriptor from the type string */
647 Func = GetFuncDesc (Expr->Type);
649 /* Handle function pointers transparently */
650 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
653 /* Check wether it's a fastcall function that has parameters */
654 IsFastCall = IsFastCallFunc (Expr->Type + 1) && (Func->ParamCount > 0);
656 /* Things may be difficult, depending on where the function pointer
657 * resides. If the function pointer is an expression of some sort
658 * (not a local or global variable), we have to evaluate this
659 * expression now and save the result for later. Since calls to
660 * function pointers may be nested, we must save it onto the stack.
661 * For fastcall functions we do also need to place a copy of the
662 * pointer on stack, since we cannot use a/x.
664 PtrOnStack = IsFastCall || !ED_IsConst (Expr);
667 /* Not a global or local variable, or a fastcall function. Load
668 * the pointer into the primary and mark it as an expression.
670 ExprLoad (CF_NONE, Expr);
671 ED_MakeRValExpr (Expr);
673 /* Remember the code position */
674 Mark = GetCodePos ();
676 /* Push the pointer onto the stack and remember the offset */
681 /* Check for known standard functions and inline them */
682 } else if ((StdFunc = FindStdFunc ((const char*) Expr->Name)) >= 0) {
684 /* Inline this function */
685 HandleStdFunc (StdFunc, Func, Expr);
690 /* Parse the parameter list */
691 ParamSize = FunctionParamList (Func);
693 /* We need the closing paren here */
696 /* Special handling for function pointers */
699 /* If the function is not a fastcall function, load the pointer to
700 * the function into the primary.
704 /* Not a fastcall function - we may use the primary */
706 /* If we have no parameters, the pointer is still in the
707 * primary. Remove the code to push it and correct the
710 if (ParamSize == 0) {
715 /* Load from the saved copy */
716 g_getlocal (CF_PTR, PtrOffs);
719 /* Load from original location */
720 ExprLoad (CF_NONE, Expr);
723 /* Call the function */
724 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
728 /* Fastcall function. We cannot use the primary for the function
729 * pointer and must therefore use an offset to the stack location.
730 * Since fastcall functions may never be variadic, we can use the
731 * index register for this purpose.
733 g_callind (CF_LOCAL, ParamSize, PtrOffs);
736 /* If we have a pointer on stack, remove it */
738 g_space (- (int) sizeofarg (CF_PTR));
747 /* Normal function */
748 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
752 /* The function result is an rvalue in the primary register */
753 ED_MakeRValExpr (Expr);
754 Expr->Type = GetFuncReturn (Expr->Type);
759 static void Primary (ExprDesc* E)
760 /* This is the lowest level of the expression parser. */
764 /* Initialize fields in the expression stucture */
767 /* Character and integer constants. */
768 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
769 E->IVal = CurTok.IVal;
770 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
771 E->Type = CurTok.Type;
776 /* Floating point constant */
777 if (CurTok.Tok == TOK_FCONST) {
778 E->FVal = CurTok.FVal;
779 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
780 E->Type = CurTok.Type;
785 /* Process parenthesized subexpression by calling the whole parser
788 if (CurTok.Tok == TOK_LPAREN) {
795 /* If we run into an identifier in preprocessing mode, we assume that this
796 * is an undefined macro and replace it by a constant value of zero.
798 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
799 ED_MakeConstAbsInt (E, 0);
803 /* All others may only be used if the expression evaluation is not called
804 * recursively by the preprocessor.
807 /* Illegal expression in PP mode */
808 Error ("Preprocessor expression expected");
809 ED_MakeConstAbsInt (E, 1);
813 switch (CurTok.Tok) {
816 /* Identifier. Get a pointer to the symbol table entry */
817 Sym = E->Sym = FindSym (CurTok.Ident);
819 /* Is the symbol known? */
822 /* We found the symbol - skip the name token */
825 /* Check for illegal symbol types */
826 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
827 if (Sym->Flags & SC_TYPE) {
828 /* Cannot use type symbols */
829 Error ("Variable identifier expected");
830 /* Assume an int type to make E valid */
831 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
836 /* Mark the symbol as referenced */
837 Sym->Flags |= SC_REF;
839 /* The expression type is the symbol type */
842 /* Check for legal symbol types */
843 if ((Sym->Flags & SC_CONST) == SC_CONST) {
844 /* Enum or some other numeric constant */
845 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
846 E->IVal = Sym->V.ConstVal;
847 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
849 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
850 E->Name = (unsigned long) Sym->Name;
851 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
852 /* Local variable. If this is a parameter for a variadic
853 * function, we have to add some address calculations, and the
854 * address is not const.
856 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
857 /* Variadic parameter */
858 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
859 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
861 /* Normal parameter */
862 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
863 E->IVal = Sym->V.Offs;
865 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
866 /* Register variable, zero page based */
867 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
868 E->Name = Sym->V.R.RegOffs;
869 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
870 /* Static variable */
871 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
872 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
873 E->Name = (unsigned long) Sym->Name;
875 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
876 E->Name = Sym->V.Label;
879 /* Local static variable */
880 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
881 E->Name = Sym->V.Offs;
884 /* We've made all variables lvalues above. However, this is
885 * not always correct: An array is actually the address of its
886 * first element, which is a rvalue, and a function is a
887 * rvalue, too, because we cannot store anything in a function.
888 * So fix the flags depending on the type.
890 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
896 /* We did not find the symbol. Remember the name, then skip it */
898 strcpy (Ident, CurTok.Ident);
901 /* IDENT is either an auto-declared function or an undefined variable. */
902 if (CurTok.Tok == TOK_LPAREN) {
903 /* Declare a function returning int. For that purpose, prepare a
904 * function signature for a function having an empty param list
907 Warning ("Function call without a prototype");
908 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
910 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
911 E->Name = (unsigned long) Sym->Name;
913 /* Undeclared Variable */
914 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
915 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
917 Error ("Undefined symbol: `%s'", Ident);
925 E->Type = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
926 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
927 E->IVal = CurTok.IVal;
928 E->Name = LiteralPoolLabel;
935 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
940 /* Register pseudo variable */
941 E->Type = type_uchar;
942 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
947 /* Register pseudo variable */
949 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
954 /* Register pseudo variable */
955 E->Type = type_ulong;
956 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
961 /* Illegal primary. */
962 Error ("Expression expected");
963 ED_MakeConstAbsInt (E, 1);
970 static void ArrayRef (ExprDesc* Expr)
971 /* Handle an array reference */
981 /* Skip the bracket */
984 /* Get the type of left side */
987 /* We can apply a special treatment for arrays that have a const base
988 * address. This is true for most arrays and will produce a lot better
989 * code. Check if this is a const base address.
991 ConstBaseAddr = (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
993 /* If we have a constant base, we delay the address fetch */
994 Mark1 = GetCodePos ();
995 Mark2 = 0; /* Silence gcc */
996 if (!ConstBaseAddr) {
997 /* Get a pointer to the array into the primary */
998 ExprLoad (CF_NONE, Expr);
1000 /* Get the array pointer on stack. Do not push more than 16
1001 * bit, even if this value is greater, since we cannot handle
1002 * other than 16bit stuff when doing indexing.
1004 Mark2 = GetCodePos ();
1008 /* TOS now contains ptr to array elements. Get the subscript. */
1009 ExprWithCheck (hie0, &SubScript);
1011 /* Check the types of array and subscript. We can either have a
1012 * pointer/array to the left, in which case the subscript must be of an
1013 * integer type, or we have an integer to the left, in which case the
1014 * subscript must be a pointer/array.
1015 * Since we do the necessary checking here, we can rely later on the
1018 if (IsClassPtr (Expr->Type)) {
1019 if (!IsClassInt (SubScript.Type)) {
1020 Error ("Array subscript is not an integer");
1021 /* To avoid any compiler errors, make the expression a valid int */
1022 ED_MakeConstAbsInt (&SubScript, 0);
1024 ElementType = Indirect (Expr->Type);
1025 } else if (IsClassInt (Expr->Type)) {
1026 if (!IsClassPtr (SubScript.Type)) {
1027 Error ("Subscripted value is neither array nor pointer");
1028 /* To avoid compiler errors, make the subscript a char[] at
1031 ED_MakeConstAbs (&SubScript, 0, GetCharArrayType (1));
1033 ElementType = Indirect (SubScript.Type);
1035 Error ("Cannot subscript");
1036 /* To avoid compiler errors, fake both the array and the subscript, so
1037 * we can just proceed.
1039 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
1040 ED_MakeConstAbsInt (&SubScript, 0);
1041 ElementType = Indirect (Expr->Type);
1044 /* Check if the subscript is constant absolute value */
1045 if (ED_IsConstAbs (&SubScript)) {
1047 /* The array subscript is a numeric constant. If we had pushed the
1048 * array base address onto the stack before, we can remove this value,
1049 * since we can generate expression+offset.
1051 if (!ConstBaseAddr) {
1055 /* Get an array pointer into the primary */
1056 ExprLoad (CF_NONE, Expr);
1059 if (IsClassPtr (Expr->Type)) {
1061 /* Lhs is pointer/array. Scale the subscript value according to
1064 SubScript.IVal *= CheckedSizeOf (ElementType);
1066 /* Remove the address load code */
1069 /* In case of an array, we can adjust the offset of the expression
1070 * already in Expr. If the base address was a constant, we can even
1071 * remove the code that loaded the address into the primary.
1073 if (IsTypeArray (Expr->Type)) {
1075 /* Adjust the offset */
1076 Expr->IVal += SubScript.IVal;
1080 /* It's a pointer, so we do have to load it into the primary
1081 * first (if it's not already there).
1083 if (ConstBaseAddr) {
1084 ExprLoad (CF_NONE, Expr);
1085 ED_MakeRValExpr (Expr);
1088 /* Use the offset */
1089 Expr->IVal = SubScript.IVal;
1094 /* Scale the rhs value according to the element type */
1095 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1097 /* Add the subscript. Since arrays are indexed by integers,
1098 * we will ignore the true type of the subscript here and
1099 * use always an int. #### Use offset but beware of ExprLoad!
1101 g_inc (CF_INT | CF_CONST, SubScript.IVal);
1107 /* Array subscript is not constant. Load it into the primary */
1108 Mark2 = GetCodePos ();
1109 ExprLoad (CF_NONE, &SubScript);
1112 if (IsClassPtr (Expr->Type)) {
1114 /* Indexing is based on unsigneds, so we will just use the integer
1115 * portion of the index (which is in (e)ax, so there's no further
1118 g_scale (CF_INT, CheckedSizeOf (ElementType));
1122 /* Get the int value on top. If we come here, we're sure, both
1123 * values are 16 bit (the first one was truncated if necessary
1124 * and the second one is a pointer). Note: If ConstBaseAddr is
1125 * true, we don't have a value on stack, so to "swap" both, just
1126 * push the subscript.
1128 if (ConstBaseAddr) {
1130 ExprLoad (CF_NONE, Expr);
1137 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1141 /* The offset is now in the primary register. It we didn't have a
1142 * constant base address for the lhs, the lhs address is already
1143 * on stack, and we must add the offset. If the base address was
1144 * constant, we call special functions to add the address to the
1147 if (!ConstBaseAddr) {
1149 /* The array base address is on stack and the subscript is in the
1150 * primary. Add both.
1156 /* The subscript is in the primary, and the array base address is
1157 * in Expr. If the subscript has itself a constant address, it is
1158 * often a better idea to reverse again the order of the
1159 * evaluation. This will generate better code if the subscript is
1160 * a byte sized variable. But beware: This is only possible if the
1161 * subscript was not scaled, that is, if this was a byte array
1164 if ((ED_IsLocConst (&SubScript) || ED_IsLocStack (&SubScript)) &&
1165 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1169 /* Reverse the order of evaluation */
1170 if (CheckedSizeOf (SubScript.Type) == SIZEOF_CHAR) {
1177 /* Get a pointer to the array into the primary. */
1178 ExprLoad (CF_NONE, Expr);
1180 /* Add the variable */
1181 if (ED_IsLocStack (&SubScript)) {
1182 g_addlocal (Flags, SubScript.IVal);
1184 Flags |= GlobalModeFlags (SubScript.Flags);
1185 g_addstatic (Flags, SubScript.Name, SubScript.IVal);
1188 if (ED_IsLocAbs (Expr)) {
1189 /* Constant numeric address. Just add it */
1190 g_inc (CF_INT, Expr->IVal);
1191 } else if (ED_IsLocStack (Expr)) {
1192 /* Base address is a local variable address */
1193 if (IsTypeArray (Expr->Type)) {
1194 g_addaddr_local (CF_INT, Expr->IVal);
1196 g_addlocal (CF_PTR, Expr->IVal);
1199 /* Base address is a static variable address */
1200 unsigned Flags = CF_INT | GlobalModeFlags (Expr->Flags);
1201 if (IsTypeArray (Expr->Type)) {
1202 g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1204 g_addstatic (Flags, Expr->Name, Expr->IVal);
1212 /* The result is an expression in the primary */
1213 ED_MakeRValExpr (Expr);
1217 /* Result is of element type */
1218 Expr->Type = ElementType;
1220 /* An array element is actually a variable. So the rules for variables
1221 * with respect to the reference type apply: If it's an array, it is
1222 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1223 * but an array cannot contain functions).
1225 if (IsTypeArray (Expr->Type)) {
1231 /* Consume the closing bracket */
1237 static void StructRef (ExprDesc* Expr)
1238 /* Process struct field after . or ->. */
1243 /* Skip the token and check for an identifier */
1245 if (CurTok.Tok != TOK_IDENT) {
1246 Error ("Identifier expected");
1247 Expr->Type = type_int;
1251 /* Get the symbol table entry and check for a struct field */
1252 strcpy (Ident, CurTok.Ident);
1254 Field = FindStructField (Expr->Type, Ident);
1256 Error ("Struct/union has no field named `%s'", Ident);
1257 Expr->Type = type_int;
1261 /* If we have a struct pointer that is an lvalue and not already in the
1262 * primary, load it now.
1264 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1266 /* Load into the primary */
1267 ExprLoad (CF_NONE, Expr);
1269 /* Make it an lvalue expression */
1270 ED_MakeLValExpr (Expr);
1273 /* Set the struct field offset */
1274 Expr->IVal += Field->V.Offs;
1276 /* The type is now the type of the field */
1277 Expr->Type = Field->Type;
1279 /* An struct member is actually a variable. So the rules for variables
1280 * with respect to the reference type apply: If it's an array, it is
1281 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1282 * but a struct field cannot be a function).
1284 if (IsTypeArray (Expr->Type)) {
1293 static void hie11 (ExprDesc *Expr)
1294 /* Handle compound types (structs and arrays) */
1296 /* Evaluate the lhs */
1299 /* Check for a rhs */
1300 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1301 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1303 switch (CurTok.Tok) {
1306 /* Array reference */
1311 /* Function call. */
1312 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1313 /* Not a function */
1314 Error ("Illegal function call");
1315 /* Force the type to be a implicitly defined function, one
1316 * returning an int and taking any number of arguments.
1317 * Since we don't have a name, place it at absolute address
1320 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1322 /* Call the function */
1323 FunctionCall (Expr);
1327 if (!IsClassStruct (Expr->Type)) {
1328 Error ("Struct expected");
1334 /* If we have an array, convert it to pointer to first element */
1335 if (IsTypeArray (Expr->Type)) {
1336 Expr->Type = ArrayToPtr (Expr->Type);
1338 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1339 Error ("Struct pointer expected");
1345 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1353 void Store (ExprDesc* Expr, const type* StoreType)
1354 /* Store the primary register into the location denoted by Expr. If StoreType
1355 * is given, use this type when storing instead of Expr->Type. If StoreType
1356 * is NULL, use Expr->Type instead.
1361 /* If StoreType was not given, use Expr->Type instead */
1362 if (StoreType == 0) {
1363 StoreType = Expr->Type;
1366 /* Prepare the code generator flags */
1367 Flags = TypeOf (StoreType);
1369 /* Do the store depending on the location */
1370 switch (ED_GetLoc (Expr)) {
1373 /* Absolute: numeric address or const */
1374 g_putstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0);
1378 /* Global variable */
1379 g_putstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal);
1384 /* Static variable or literal in the literal pool */
1385 g_putstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal);
1388 case E_LOC_REGISTER:
1389 /* Register variable */
1390 g_putstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal);
1394 /* Value on the stack */
1395 g_putlocal (Flags, Expr->IVal, 0);
1399 /* The primary register (value is already there) */
1400 /* ### Do we need a test here if the flag is set? */
1404 /* An expression in the primary register */
1405 g_putind (Flags, Expr->IVal);
1409 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1412 /* Assume that each one of the stores will invalidate CC */
1413 ED_MarkAsUntested (Expr);
1418 static void PreInc (ExprDesc* Expr)
1419 /* Handle the preincrement operators */
1424 /* Skip the operator token */
1427 /* Evaluate the expression and check that it is an lvalue */
1429 if (!ED_IsLVal (Expr)) {
1430 Error ("Invalid lvalue");
1434 /* Get the data type */
1435 Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1437 /* Get the increment value in bytes */
1438 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1440 /* Check the location of the data */
1441 switch (ED_GetLoc (Expr)) {
1444 /* Absolute: numeric address or const */
1445 g_addeqstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0, Val);
1449 /* Global variable */
1450 g_addeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal, Val);
1455 /* Static variable or literal in the literal pool */
1456 g_addeqstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal, Val);
1459 case E_LOC_REGISTER:
1460 /* Register variable */
1461 g_addeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal, Val);
1465 /* Value on the stack */
1466 g_addeqlocal (Flags, Expr->IVal, Val);
1470 /* The primary register */
1475 /* An expression in the primary register */
1476 g_addeqind (Flags, Expr->IVal, Val);
1480 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1483 /* Result is an expression, no reference */
1484 ED_MakeRValExpr (Expr);
1489 static void PreDec (ExprDesc* Expr)
1490 /* Handle the predecrement operators */
1495 /* Skip the operator token */
1498 /* Evaluate the expression and check that it is an lvalue */
1500 if (!ED_IsLVal (Expr)) {
1501 Error ("Invalid lvalue");
1505 /* Get the data type */
1506 Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1508 /* Get the increment value in bytes */
1509 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1511 /* Check the location of the data */
1512 switch (ED_GetLoc (Expr)) {
1515 /* Absolute: numeric address or const */
1516 g_subeqstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0, Val);
1520 /* Global variable */
1521 g_subeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal, Val);
1526 /* Static variable or literal in the literal pool */
1527 g_subeqstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal, Val);
1530 case E_LOC_REGISTER:
1531 /* Register variable */
1532 g_subeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal, Val);
1536 /* Value on the stack */
1537 g_subeqlocal (Flags, Expr->IVal, Val);
1541 /* The primary register */
1546 /* An expression in the primary register */
1547 g_subeqind (Flags, Expr->IVal, Val);
1551 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1554 /* Result is an expression, no reference */
1555 ED_MakeRValExpr (Expr);
1560 static void PostIncDec (ExprDesc* Expr, void (*inc) (unsigned, unsigned long))
1561 /* Handle i-- and i++ */
1567 /* The expression to increment must be an lvalue */
1568 if (!ED_IsLVal (Expr)) {
1569 Error ("Invalid lvalue");
1573 /* Get the data type */
1574 Flags = TypeOf (Expr->Type);
1576 /* Push the address if needed */
1579 /* Fetch the value and save it (since it's the result of the expression) */
1580 ExprLoad (CF_NONE, Expr);
1581 g_save (Flags | CF_FORCECHAR);
1583 /* If we have a pointer expression, increment by the size of the type */
1584 if (IsTypePtr (Expr->Type)) {
1585 inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1587 inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1590 /* Store the result back */
1593 /* Restore the original value in the primary register */
1594 g_restore (Flags | CF_FORCECHAR);
1596 /* The result is always an expression, no reference */
1597 ED_MakeRValExpr (Expr);
1602 static void UnaryOp (ExprDesc* Expr)
1603 /* Handle unary -/+ and ~ */
1607 /* Remember the operator token and skip it */
1608 token_t Tok = CurTok.Tok;
1611 /* Get the expression */
1614 /* We can only handle integer types */
1615 if (!IsClassInt (Expr->Type)) {
1616 Error ("Argument must have integer type");
1617 ED_MakeConstAbsInt (Expr, 1);
1620 /* Check for a constant expression */
1621 if (ED_IsConstAbs (Expr)) {
1622 /* Value is constant */
1624 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1625 case TOK_PLUS: break;
1626 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1627 default: Internal ("Unexpected token: %d", Tok);
1630 /* Value is not constant */
1631 ExprLoad (CF_NONE, Expr);
1633 /* Get the type of the expression */
1634 Flags = TypeOf (Expr->Type);
1636 /* Handle the operation */
1638 case TOK_MINUS: g_neg (Flags); break;
1639 case TOK_PLUS: break;
1640 case TOK_COMP: g_com (Flags); break;
1641 default: Internal ("Unexpected token: %d", Tok);
1644 /* The result is a rvalue in the primary */
1645 ED_MakeRValExpr (Expr);
1651 void hie10 (ExprDesc* Expr)
1652 /* Handle ++, --, !, unary - etc. */
1656 switch (CurTok.Tok) {
1674 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1675 /* Constant expression */
1676 Expr->IVal = !Expr->IVal;
1678 g_bneg (TypeOf (Expr->Type));
1679 ED_MakeRValExpr (Expr);
1680 ED_TestDone (Expr); /* bneg will set cc */
1686 ExprWithCheck (hie10, Expr);
1687 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1688 /* Not a const, load it into the primary and make it a
1691 ExprLoad (CF_NONE, Expr);
1692 ED_MakeRValExpr (Expr);
1694 /* If the expression is already a pointer to function, the
1695 * additional dereferencing operator must be ignored.
1697 if (IsTypeFuncPtr (Expr->Type)) {
1698 /* Expression not storable */
1701 if (IsClassPtr (Expr->Type)) {
1702 Expr->Type = Indirect (Expr->Type);
1704 Error ("Illegal indirection");
1712 ExprWithCheck (hie10, Expr);
1713 /* The & operator may be applied to any lvalue, and it may be
1714 * applied to functions, even if they're no lvalues.
1716 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type)) {
1717 /* Allow the & operator with an array */
1718 if (!IsTypeArray (Expr->Type)) {
1719 Error ("Illegal address");
1722 Expr->Type = PointerTo (Expr->Type);
1729 if (TypeSpecAhead ()) {
1730 type Type[MAXTYPELEN];
1732 Size = CheckedSizeOf (ParseType (Type));
1735 /* Remember the output queue pointer */
1736 CodeMark Mark = GetCodePos ();
1738 Size = CheckedSizeOf (Expr->Type);
1739 /* Remove any generated code */
1742 ED_MakeConstAbs (Expr, Size, type_size_t);
1743 ED_MarkAsUntested (Expr);
1747 if (TypeSpecAhead ()) {
1757 /* Handle post increment */
1758 if (CurTok.Tok == TOK_INC) {
1759 PostIncDec (Expr, g_inc);
1760 } else if (CurTok.Tok == TOK_DEC) {
1761 PostIncDec (Expr, g_dec);
1771 static void hie_internal (const GenDesc* Ops, /* List of generators */
1773 void (*hienext) (ExprDesc*),
1775 /* Helper function */
1781 token_t Tok; /* The operator token */
1782 unsigned ltype, type;
1783 int rconst; /* Operand is a constant */
1789 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1791 /* Tell the caller that we handled it's ops */
1794 /* All operators that call this function expect an int on the lhs */
1795 if (!IsClassInt (Expr->Type)) {
1796 Error ("Integer expression expected");
1799 /* Remember the operator token, then skip it */
1803 /* Get the lhs on stack */
1804 Mark1 = GetCodePos ();
1805 ltype = TypeOf (Expr->Type);
1806 if (ED_IsConstAbs (Expr)) {
1807 /* Constant value */
1808 Mark2 = GetCodePos ();
1809 g_push (ltype | CF_CONST, Expr->IVal);
1811 /* Value not constant */
1812 ExprLoad (CF_NONE, Expr);
1813 Mark2 = GetCodePos ();
1817 /* Get the right hand side */
1818 rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1820 /* Check the type of the rhs */
1821 if (!IsClassInt (Expr2.Type)) {
1822 Error ("Integer expression expected");
1825 /* Check for const operands */
1826 if (ED_IsConstAbs (Expr) && rconst) {
1828 /* Both operands are constant, remove the generated code */
1832 /* Evaluate the result */
1833 Expr->IVal = kcalc (Tok, Expr->IVal, Expr2.IVal);
1835 /* Get the type of the result */
1836 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1840 /* If the right hand side is constant, and the generator function
1841 * expects the lhs in the primary, remove the push of the primary
1844 unsigned rtype = TypeOf (Expr2.Type);
1847 /* Second value is constant - check for div */
1850 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1851 Error ("Division by zero");
1852 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1853 Error ("Modulo operation with zero");
1855 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1858 ltype |= CF_REG; /* Value is in register */
1862 /* Determine the type of the operation result. */
1863 type |= g_typeadjust (ltype, rtype);
1864 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1867 Gen->Func (type, Expr2.IVal);
1869 /* We have a rvalue in the primary now */
1870 ED_MakeRValExpr (Expr);
1877 static void hie_compare (const GenDesc* Ops, /* List of generators */
1879 void (*hienext) (ExprDesc*))
1880 /* Helper function for the compare operators */
1886 token_t tok; /* The operator token */
1888 int rconst; /* Operand is a constant */
1893 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1895 /* Remember the operator token, then skip it */
1899 /* Get the lhs on stack */
1900 Mark1 = GetCodePos ();
1901 ltype = TypeOf (Expr->Type);
1902 if (ED_IsConstAbs (Expr)) {
1903 /* Constant value */
1904 Mark2 = GetCodePos ();
1905 g_push (ltype | CF_CONST, Expr->IVal);
1907 /* Value not constant */
1908 ExprLoad (CF_NONE, Expr);
1909 Mark2 = GetCodePos ();
1913 /* Get the right hand side */
1914 rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1916 /* Make sure, the types are compatible */
1917 if (IsClassInt (Expr->Type)) {
1918 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1919 Error ("Incompatible types");
1921 } else if (IsClassPtr (Expr->Type)) {
1922 if (IsClassPtr (Expr2.Type)) {
1923 /* Both pointers are allowed in comparison if they point to
1924 * the same type, or if one of them is a void pointer.
1926 type* left = Indirect (Expr->Type);
1927 type* right = Indirect (Expr2.Type);
1928 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1929 /* Incomatible pointers */
1930 Error ("Incompatible types");
1932 } else if (!ED_IsNullPtr (&Expr2)) {
1933 Error ("Incompatible types");
1937 /* Check for const operands */
1938 if (ED_IsConstAbs (Expr) && rconst) {
1940 /* Both operands are constant, remove the generated code */
1944 /* Evaluate the result */
1945 Expr->IVal = kcalc (tok, Expr->IVal, Expr2.IVal);
1949 /* If the right hand side is constant, and the generator function
1950 * expects the lhs in the primary, remove the push of the primary
1956 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1959 ltype |= CF_REG; /* Value is in register */
1963 /* Determine the type of the operation result. If the left
1964 * operand is of type char and the right is a constant, or
1965 * if both operands are of type char, we will encode the
1966 * operation as char operation. Otherwise the default
1967 * promotions are used.
1969 if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
1971 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
1972 flags |= CF_UNSIGNED;
1975 flags |= CF_FORCECHAR;
1978 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
1979 flags |= g_typeadjust (ltype, rtype);
1983 Gen->Func (flags, Expr2.IVal);
1985 /* The result is an rvalue in the primary */
1986 ED_MakeRValExpr (Expr);
1989 /* Result type is always int */
1990 Expr->Type = type_int;
1992 /* Condition codes are set */
1999 static void hie9 (ExprDesc *Expr)
2000 /* Process * and / operators. */
2002 static const GenDesc hie9_ops[] = {
2003 { TOK_STAR, GEN_NOPUSH, g_mul },
2004 { TOK_DIV, GEN_NOPUSH, g_div },
2005 { TOK_MOD, GEN_NOPUSH, g_mod },
2006 { TOK_INVALID, 0, 0 }
2010 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2015 static void parseadd (ExprDesc* Expr)
2016 /* Parse an expression with the binary plus operator. Expr contains the
2017 * unprocessed left hand side of the expression and will contain the
2018 * result of the expression on return.
2022 unsigned flags; /* Operation flags */
2023 CodeMark Mark; /* Remember code position */
2024 type* lhst; /* Type of left hand side */
2025 type* rhst; /* Type of right hand side */
2028 /* Skip the PLUS token */
2031 /* Get the left hand side type, initialize operation flags */
2035 /* Check for constness on both sides */
2036 if (ED_IsConst (Expr)) {
2038 /* The left hand side is a constant of some sort. Good. Get rhs */
2040 if (ED_IsConstAbs (&Expr2)) {
2042 /* Right hand side is a constant numeric value. Get the rhs type */
2045 /* Both expressions are constants. Check for pointer arithmetic */
2046 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2047 /* Left is pointer, right is int, must scale rhs */
2048 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2049 /* Result type is a pointer */
2050 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2051 /* Left is int, right is pointer, must scale lhs */
2052 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2053 /* Result type is a pointer */
2054 Expr->Type = Expr2.Type;
2055 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2056 /* Integer addition */
2057 Expr->IVal += Expr2.IVal;
2058 typeadjust (Expr, &Expr2, 1);
2061 Error ("Invalid operands for binary operator `+'");
2066 /* lhs is a constant and rhs is not constant. Load rhs into
2069 ExprLoad (CF_NONE, &Expr2);
2071 /* Beware: The check above (for lhs) lets not only pass numeric
2072 * constants, but also constant addresses (labels), maybe even
2073 * with an offset. We have to check for that here.
2076 /* First, get the rhs type. */
2080 if (ED_IsLocAbs (Expr)) {
2081 /* A numerical constant */
2084 /* Constant address label */
2085 flags |= GlobalModeFlags (Expr->Flags) | CF_CONSTADDR;
2088 /* Check for pointer arithmetic */
2089 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2090 /* Left is pointer, right is int, must scale rhs */
2091 g_scale (CF_INT, CheckedPSizeOf (lhst));
2092 /* Operate on pointers, result type is a pointer */
2094 /* Generate the code for the add */
2095 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2096 /* Numeric constant */
2097 g_inc (flags, Expr->IVal);
2099 /* Constant address */
2100 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2102 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2104 /* Left is int, right is pointer, must scale lhs. */
2105 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2107 /* Operate on pointers, result type is a pointer */
2109 Expr->Type = Expr2.Type;
2111 /* Since we do already have rhs in the primary, if lhs is
2112 * not a numeric constant, and the scale factor is not one
2113 * (no scaling), we must take the long way over the stack.
2115 if (ED_IsLocAbs (Expr)) {
2116 /* Numeric constant, scale lhs */
2117 Expr->IVal *= ScaleFactor;
2118 /* Generate the code for the add */
2119 g_inc (flags, Expr->IVal);
2120 } else if (ScaleFactor == 1) {
2121 /* Constant address but no need to scale */
2122 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2124 /* Constant address that must be scaled */
2125 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2126 g_getimmed (flags, Expr->Name, Expr->IVal);
2127 g_scale (CF_PTR, ScaleFactor);
2130 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2131 /* Integer addition */
2132 flags |= typeadjust (Expr, &Expr2, 1);
2133 /* Generate the code for the add */
2134 if (ED_IsLocAbs (Expr)) {
2135 /* Numeric constant */
2136 g_inc (flags, Expr->IVal);
2138 /* Constant address */
2139 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2143 Error ("Invalid operands for binary operator `+'");
2146 /* Result is a rvalue in primary register */
2147 ED_MakeRValExpr (Expr);
2152 /* Left hand side is not constant. Get the value onto the stack. */
2153 ExprLoad (CF_NONE, Expr); /* --> primary register */
2154 Mark = GetCodePos ();
2155 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2157 /* Evaluate the rhs */
2158 if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2160 /* Right hand side is a constant. Get the rhs type */
2163 /* Remove pushed value from stack */
2165 pop (TypeOf (Expr->Type));
2167 /* Check for pointer arithmetic */
2168 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2169 /* Left is pointer, right is int, must scale rhs */
2170 Expr2.IVal *= CheckedPSizeOf (lhst);
2171 /* Operate on pointers, result type is a pointer */
2173 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2174 /* Left is int, right is pointer, must scale lhs (ptr only) */
2175 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2176 /* Operate on pointers, result type is a pointer */
2178 Expr->Type = Expr2.Type;
2179 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2180 /* Integer addition */
2181 flags = typeadjust (Expr, &Expr2, 1);
2184 Error ("Invalid operands for binary operator `+'");
2187 /* Generate code for the add */
2188 g_inc (flags | CF_CONST, Expr2.IVal);
2192 /* lhs and rhs are not constant. Get the rhs type. */
2195 /* Check for pointer arithmetic */
2196 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2197 /* Left is pointer, right is int, must scale rhs */
2198 g_scale (CF_INT, CheckedPSizeOf (lhst));
2199 /* Operate on pointers, result type is a pointer */
2201 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2202 /* Left is int, right is pointer, must scale lhs */
2203 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2204 g_swap (CF_INT); /* Swap TOS and primary */
2205 g_scale (CF_INT, CheckedPSizeOf (rhst));
2206 /* Operate on pointers, result type is a pointer */
2208 Expr->Type = Expr2.Type;
2209 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2210 /* Integer addition. Note: Result is never constant.
2211 * Problem here is that typeadjust does not know if the
2212 * variable is an rvalue or lvalue, so if both operands
2213 * are dereferenced constant numeric addresses, typeadjust
2214 * thinks the operation works on constants. Removing
2215 * CF_CONST here means handling the symptoms, however, the
2216 * whole parser is such a mess that I fear to break anything
2217 * when trying to apply another solution.
2219 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2222 Error ("Invalid operands for binary operator `+'");
2225 /* Generate code for the add */
2230 /* Result is a rvalue in primary register */
2231 ED_MakeRValExpr (Expr);
2234 /* Condition codes not set */
2235 ED_MarkAsUntested (Expr);
2241 static void parsesub (ExprDesc* Expr)
2242 /* Parse an expression with the binary minus operator. Expr contains the
2243 * unprocessed left hand side of the expression and will contain the
2244 * result of the expression on return.
2248 unsigned flags; /* Operation flags */
2249 type* lhst; /* Type of left hand side */
2250 type* rhst; /* Type of right hand side */
2251 CodeMark Mark1; /* Save position of output queue */
2252 CodeMark Mark2; /* Another position in the queue */
2253 int rscale; /* Scale factor for the result */
2256 /* Skip the MINUS token */
2259 /* Get the left hand side type, initialize operation flags */
2262 rscale = 1; /* Scale by 1, that is, don't scale */
2264 /* Remember the output queue position, then bring the value onto the stack */
2265 Mark1 = GetCodePos ();
2266 ExprLoad (CF_NONE, Expr); /* --> primary register */
2267 Mark2 = GetCodePos ();
2268 g_push (TypeOf (lhst), 0); /* --> stack */
2270 /* Parse the right hand side */
2271 if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2273 /* The right hand side is constant. Get the rhs type. */
2276 /* Check left hand side */
2277 if (ED_IsConstAbs (Expr)) {
2279 /* Both sides are constant, remove generated code */
2281 pop (TypeOf (lhst)); /* Clean up the stack */
2283 /* Check for pointer arithmetic */
2284 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2285 /* Left is pointer, right is int, must scale rhs */
2286 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2287 /* Operate on pointers, result type is a pointer */
2288 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2289 /* Left is pointer, right is pointer, must scale result */
2290 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2291 Error ("Incompatible pointer types");
2293 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2294 CheckedPSizeOf (lhst);
2296 /* Operate on pointers, result type is an integer */
2297 Expr->Type = type_int;
2298 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2299 /* Integer subtraction */
2300 typeadjust (Expr, &Expr2, 1);
2301 Expr->IVal -= Expr2.IVal;
2304 Error ("Invalid operands for binary operator `-'");
2307 /* Result is constant, condition codes not set */
2308 ED_MarkAsUntested (Expr);
2312 /* Left hand side is not constant, right hand side is.
2313 * Remove pushed value from stack.
2316 pop (TypeOf (lhst));
2318 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2319 /* Left is pointer, right is int, must scale rhs */
2320 Expr2.IVal *= CheckedPSizeOf (lhst);
2321 /* Operate on pointers, result type is a pointer */
2323 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2324 /* Left is pointer, right is pointer, must scale result */
2325 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2326 Error ("Incompatible pointer types");
2328 rscale = CheckedPSizeOf (lhst);
2330 /* Operate on pointers, result type is an integer */
2332 Expr->Type = type_int;
2333 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2334 /* Integer subtraction */
2335 flags = typeadjust (Expr, &Expr2, 1);
2338 Error ("Invalid operands for binary operator `-'");
2341 /* Do the subtraction */
2342 g_dec (flags | CF_CONST, Expr2.IVal);
2344 /* If this was a pointer subtraction, we must scale the result */
2346 g_scale (flags, -rscale);
2349 /* Result is a rvalue in the primary register */
2350 ED_MakeRValExpr (Expr);
2351 ED_MarkAsUntested (Expr);
2357 /* Right hand side is not constant. Get the rhs type. */
2360 /* Check for pointer arithmetic */
2361 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2362 /* Left is pointer, right is int, must scale rhs */
2363 g_scale (CF_INT, CheckedPSizeOf (lhst));
2364 /* Operate on pointers, result type is a pointer */
2366 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2367 /* Left is pointer, right is pointer, must scale result */
2368 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2369 Error ("Incompatible pointer types");
2371 rscale = CheckedPSizeOf (lhst);
2373 /* Operate on pointers, result type is an integer */
2375 Expr->Type = type_int;
2376 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2377 /* Integer subtraction. If the left hand side descriptor says that
2378 * the lhs is const, we have to remove this mark, since this is no
2379 * longer true, lhs is on stack instead.
2381 if (ED_IsLocAbs (Expr)) {
2382 ED_MakeRValExpr (Expr);
2384 /* Adjust operand types */
2385 flags = typeadjust (Expr, &Expr2, 0);
2388 Error ("Invalid operands for binary operator `-'");
2391 /* Generate code for the sub (the & is a hack here) */
2392 g_sub (flags & ~CF_CONST, 0);
2394 /* If this was a pointer subtraction, we must scale the result */
2396 g_scale (flags, -rscale);
2399 /* Result is a rvalue in the primary register */
2400 ED_MakeRValExpr (Expr);
2401 ED_MarkAsUntested (Expr);
2407 static void hie8 (ExprDesc* Expr)
2408 /* Process + and - binary operators. */
2411 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2412 if (CurTok.Tok == TOK_PLUS) {
2422 static void hie7 (ExprDesc* Expr)
2423 /* Parse << and >>. */
2425 static const GenDesc hie7_ops [] = {
2426 { TOK_SHL, GEN_NOPUSH, g_asl },
2427 { TOK_SHR, GEN_NOPUSH, g_asr },
2428 { TOK_INVALID, 0, 0 }
2432 hie_internal (hie7_ops, Expr, hie8, &UsedGen);
2437 static void hie6 (ExprDesc* Expr)
2438 /* Handle greater-than type comparators */
2440 static const GenDesc hie6_ops [] = {
2441 { TOK_LT, GEN_NOPUSH, g_lt },
2442 { TOK_LE, GEN_NOPUSH, g_le },
2443 { TOK_GE, GEN_NOPUSH, g_ge },
2444 { TOK_GT, GEN_NOPUSH, g_gt },
2445 { TOK_INVALID, 0, 0 }
2447 hie_compare (hie6_ops, Expr, hie7);
2452 static void hie5 (ExprDesc* Expr)
2453 /* Handle == and != */
2455 static const GenDesc hie5_ops[] = {
2456 { TOK_EQ, GEN_NOPUSH, g_eq },
2457 { TOK_NE, GEN_NOPUSH, g_ne },
2458 { TOK_INVALID, 0, 0 }
2460 hie_compare (hie5_ops, Expr, hie6);
2465 static void hie4 (ExprDesc* Expr)
2466 /* Handle & (bitwise and) */
2468 static const GenDesc hie4_ops[] = {
2469 { TOK_AND, GEN_NOPUSH, g_and },
2470 { TOK_INVALID, 0, 0 }
2474 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2479 static void hie3 (ExprDesc* Expr)
2480 /* Handle ^ (bitwise exclusive or) */
2482 static const GenDesc hie3_ops[] = {
2483 { TOK_XOR, GEN_NOPUSH, g_xor },
2484 { TOK_INVALID, 0, 0 }
2488 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2493 static void hie2 (ExprDesc* Expr)
2494 /* Handle | (bitwise or) */
2496 static const GenDesc hie2_ops[] = {
2497 { TOK_OR, GEN_NOPUSH, g_or },
2498 { TOK_INVALID, 0, 0 }
2502 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2507 static void hieAndPP (ExprDesc* Expr)
2508 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2509 * called recursively from the preprocessor.
2514 ConstAbsIntExpr (hie2, Expr);
2515 while (CurTok.Tok == TOK_BOOL_AND) {
2521 ConstAbsIntExpr (hie2, &Expr2);
2523 /* Combine the two */
2524 Expr->IVal = (Expr->IVal && Expr2.IVal);
2530 static void hieOrPP (ExprDesc *Expr)
2531 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2532 * called recursively from the preprocessor.
2537 ConstAbsIntExpr (hieAndPP, Expr);
2538 while (CurTok.Tok == TOK_BOOL_OR) {
2544 ConstAbsIntExpr (hieAndPP, &Expr2);
2546 /* Combine the two */
2547 Expr->IVal = (Expr->IVal || Expr2.IVal);
2553 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2554 /* Process "exp && exp" */
2560 if (CurTok.Tok == TOK_BOOL_AND) {
2562 /* Tell our caller that we're evaluating a boolean */
2565 /* Get a label that we will use for false expressions */
2566 lab = GetLocalLabel ();
2568 /* If the expr hasn't set condition codes, set the force-test flag */
2569 if (!ED_IsTested (Expr)) {
2570 ED_MarkForTest (Expr);
2573 /* Load the value */
2574 ExprLoad (CF_FORCECHAR, Expr);
2576 /* Generate the jump */
2577 g_falsejump (CF_NONE, lab);
2579 /* Parse more boolean and's */
2580 while (CurTok.Tok == TOK_BOOL_AND) {
2587 if (!ED_IsTested (&Expr2)) {
2588 ED_MarkForTest (&Expr2);
2590 ExprLoad (CF_FORCECHAR, &Expr2);
2592 /* Do short circuit evaluation */
2593 if (CurTok.Tok == TOK_BOOL_AND) {
2594 g_falsejump (CF_NONE, lab);
2596 /* Last expression - will evaluate to true */
2597 g_truejump (CF_NONE, TrueLab);
2601 /* Define the false jump label here */
2602 g_defcodelabel (lab);
2604 /* The result is an rvalue in primary */
2605 ED_MakeRValExpr (Expr);
2606 ED_TestDone (Expr); /* Condition codes are set */
2612 static void hieOr (ExprDesc *Expr)
2613 /* Process "exp || exp". */
2616 int BoolOp = 0; /* Did we have a boolean op? */
2617 int AndOp; /* Did we have a && operation? */
2618 unsigned TrueLab; /* Jump to this label if true */
2622 TrueLab = GetLocalLabel ();
2624 /* Call the next level parser */
2625 hieAnd (Expr, TrueLab, &BoolOp);
2627 /* Any boolean or's? */
2628 if (CurTok.Tok == TOK_BOOL_OR) {
2630 /* If the expr hasn't set condition codes, set the force-test flag */
2631 if (!ED_IsTested (Expr)) {
2632 ED_MarkForTest (Expr);
2635 /* Get first expr */
2636 ExprLoad (CF_FORCECHAR, Expr);
2638 /* For each expression jump to TrueLab if true. Beware: If we
2639 * had && operators, the jump is already in place!
2642 g_truejump (CF_NONE, TrueLab);
2645 /* Remember that we had a boolean op */
2648 /* while there's more expr */
2649 while (CurTok.Tok == TOK_BOOL_OR) {
2656 hieAnd (&Expr2, TrueLab, &AndOp);
2657 if (!ED_IsTested (&Expr2)) {
2658 ED_MarkForTest (&Expr2);
2660 ExprLoad (CF_FORCECHAR, &Expr2);
2662 /* If there is more to come, add shortcut boolean eval. */
2663 g_truejump (CF_NONE, TrueLab);
2667 /* The result is an rvalue in primary */
2668 ED_MakeRValExpr (Expr);
2669 ED_TestDone (Expr); /* Condition codes are set */
2672 /* If we really had boolean ops, generate the end sequence */
2674 DoneLab = GetLocalLabel ();
2675 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2676 g_falsejump (CF_NONE, DoneLab);
2677 g_defcodelabel (TrueLab);
2678 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2679 g_defcodelabel (DoneLab);
2685 static void hieQuest (ExprDesc* Expr)
2686 /* Parse the ternary operator */
2690 ExprDesc Expr2; /* Expression 2 */
2691 ExprDesc Expr3; /* Expression 3 */
2692 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
2693 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
2694 type* ResultType; /* Type of result */
2697 /* Call the lower level eval routine */
2698 if (Preprocessing) {
2704 /* Check if it's a ternary expression */
2705 if (CurTok.Tok == TOK_QUEST) {
2707 if (!ED_IsTested (Expr)) {
2708 /* Condition codes not set, request a test */
2709 ED_MarkForTest (Expr);
2711 ExprLoad (CF_NONE, Expr);
2712 labf = GetLocalLabel ();
2713 g_falsejump (CF_NONE, labf);
2715 /* Parse second expression. Remember for later if it is a NULL pointer
2716 * expression, then load it into the primary.
2718 ExprWithCheck (hie1, &Expr2);
2719 Expr2IsNULL = ED_IsNullPtr (&Expr2);
2720 if (!IsTypeVoid (Expr2.Type)) {
2721 /* Load it into the primary */
2722 ExprLoad (CF_NONE, &Expr2);
2723 ED_MakeRValExpr (&Expr2);
2725 labt = GetLocalLabel ();
2729 /* Jump here if the first expression was false */
2730 g_defcodelabel (labf);
2732 /* Parse second expression. Remember for later if it is a NULL pointer
2733 * expression, then load it into the primary.
2735 ExprWithCheck (hie1, &Expr3);
2736 Expr3IsNULL = ED_IsNullPtr (&Expr3);
2737 if (!IsTypeVoid (Expr3.Type)) {
2738 /* Load it into the primary */
2739 ExprLoad (CF_NONE, &Expr3);
2740 ED_MakeRValExpr (&Expr3);
2743 /* Check if any conversions are needed, if so, do them.
2744 * Conversion rules for ?: expression are:
2745 * - if both expressions are int expressions, default promotion
2746 * rules for ints apply.
2747 * - if both expressions are pointers of the same type, the
2748 * result of the expression is of this type.
2749 * - if one of the expressions is a pointer and the other is
2750 * a zero constant, the resulting type is that of the pointer
2752 * - if both expressions are void expressions, the result is of
2754 * - all other cases are flagged by an error.
2756 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2758 /* Get common type */
2759 ResultType = promoteint (Expr2.Type, Expr3.Type);
2761 /* Convert the third expression to this type if needed */
2762 TypeConversion (&Expr3, ResultType);
2764 /* Setup a new label so that the expr3 code will jump around
2765 * the type cast code for expr2.
2767 labf = GetLocalLabel (); /* Get new label */
2768 g_jump (labf); /* Jump around code */
2770 /* The jump for expr2 goes here */
2771 g_defcodelabel (labt);
2773 /* Create the typecast code for expr2 */
2774 TypeConversion (&Expr2, ResultType);
2776 /* Jump here around the typecase code. */
2777 g_defcodelabel (labf);
2778 labt = 0; /* Mark other label as invalid */
2780 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2781 /* Must point to same type */
2782 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2783 Error ("Incompatible pointer types");
2785 /* Result has the common type */
2786 ResultType = Expr2.Type;
2787 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2788 /* Result type is pointer, no cast needed */
2789 ResultType = Expr2.Type;
2790 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2791 /* Result type is pointer, no cast needed */
2792 ResultType = Expr3.Type;
2793 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2794 /* Result type is void */
2795 ResultType = Expr3.Type;
2797 Error ("Incompatible types");
2798 ResultType = Expr2.Type; /* Doesn't matter here */
2801 /* If we don't have the label defined until now, do it */
2803 g_defcodelabel (labt);
2806 /* Setup the target expression */
2807 ED_MakeRValExpr (Expr);
2808 Expr->Type = ResultType;
2814 static void opeq (const GenDesc* Gen, ExprDesc* Expr)
2815 /* Process "op=" operators. */
2822 /* op= can only be used with lvalues */
2823 if (!ED_IsLVal (Expr)) {
2824 Error ("Invalid lvalue in assignment");
2828 /* There must be an integer or pointer on the left side */
2829 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2830 Error ("Invalid left operand type");
2831 /* Continue. Wrong code will be generated, but the compiler won't
2832 * break, so this is the best error recovery.
2836 /* Skip the operator token */
2839 /* Determine the type of the lhs */
2840 flags = TypeOf (Expr->Type);
2841 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2843 /* Get the lhs address on stack (if needed) */
2846 /* Fetch the lhs into the primary register if needed */
2847 ExprLoad (CF_NONE, Expr);
2849 /* Bring the lhs on stack */
2850 Mark = GetCodePos ();
2853 /* Evaluate the rhs */
2854 if (evalexpr (CF_NONE, hie1, &Expr2) == 0) {
2855 /* The resulting value is a constant. If the generator has the NOPUSH
2856 * flag set, don't push the lhs.
2858 if (Gen->Flags & GEN_NOPUSH) {
2863 /* lhs is a pointer, scale rhs */
2864 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2867 /* If the lhs is character sized, the operation may be later done
2870 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2871 flags |= CF_FORCECHAR;
2874 /* Special handling for add and sub - some sort of a hack, but short code */
2875 if (Gen->Func == g_add) {
2876 g_inc (flags | CF_CONST, Expr2.IVal);
2877 } else if (Gen->Func == g_sub) {
2878 g_dec (flags | CF_CONST, Expr2.IVal);
2880 Gen->Func (flags | CF_CONST, Expr2.IVal);
2883 /* rhs is not constant and already in the primary register */
2885 /* lhs is a pointer, scale rhs */
2886 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2889 /* If the lhs is character sized, the operation may be later done
2892 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2893 flags |= CF_FORCECHAR;
2896 /* Adjust the types of the operands if needed */
2897 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2900 ED_MakeRValExpr (Expr);
2905 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr)
2906 /* Process the += and -= operators */
2914 /* We're currently only able to handle some adressing modes */
2915 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2916 /* Use generic routine */
2921 /* We must have an lvalue */
2922 if (ED_IsRVal (Expr)) {
2923 Error ("Invalid lvalue in assignment");
2927 /* There must be an integer or pointer on the left side */
2928 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2929 Error ("Invalid left operand type");
2930 /* Continue. Wrong code will be generated, but the compiler won't
2931 * break, so this is the best error recovery.
2935 /* Skip the operator */
2938 /* Check if we have a pointer expression and must scale rhs */
2939 MustScale = IsTypePtr (Expr->Type);
2941 /* Initialize the code generator flags */
2945 /* Evaluate the rhs */
2947 if (ED_IsConstAbs (&Expr2)) {
2948 /* The resulting value is a constant. Scale it. */
2950 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
2955 /* Not constant, load into the primary */
2956 ExprLoad (CF_NONE, &Expr2);
2958 /* lhs is a pointer, scale rhs */
2959 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
2963 /* Setup the code generator flags */
2964 lflags |= TypeOf (Expr->Type) | CF_FORCECHAR;
2965 rflags |= TypeOf (Expr2.Type);
2967 /* Convert the type of the lhs to that of the rhs */
2968 g_typecast (lflags, rflags);
2970 /* Output apropriate code depending on the location */
2971 switch (ED_GetLoc (Expr)) {
2974 /* Absolute: numeric address or const */
2975 lflags |= CF_ABSOLUTE;
2976 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2977 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2979 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2984 /* Global variable */
2985 lflags |= CF_EXTERNAL;
2986 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2987 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2989 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2995 /* Static variable or literal in the literal pool */
2996 lflags |= CF_STATIC;
2997 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2998 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3000 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3004 case E_LOC_REGISTER:
3005 /* Register variable */
3006 lflags |= CF_REGVAR;
3007 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3008 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3010 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3015 /* Value on the stack */
3016 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3017 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3019 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3024 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3027 /* Expression is a rvalue in the primary now */
3028 ED_MakeRValExpr (Expr);
3033 void hie1 (ExprDesc* Expr)
3034 /* Parse first level of expression hierarchy. */
3037 switch (CurTok.Tok) {
3043 case TOK_PLUS_ASSIGN:
3044 addsubeq (&GenPASGN, Expr);
3047 case TOK_MINUS_ASSIGN:
3048 addsubeq (&GenSASGN, Expr);
3051 case TOK_MUL_ASSIGN:
3052 opeq (&GenMASGN, Expr);
3055 case TOK_DIV_ASSIGN:
3056 opeq (&GenDASGN, Expr);
3059 case TOK_MOD_ASSIGN:
3060 opeq (&GenMOASGN, Expr);
3063 case TOK_SHL_ASSIGN:
3064 opeq (&GenSLASGN, Expr);
3067 case TOK_SHR_ASSIGN:
3068 opeq (&GenSRASGN, Expr);
3071 case TOK_AND_ASSIGN:
3072 opeq (&GenAASGN, Expr);
3075 case TOK_XOR_ASSIGN:
3076 opeq (&GenXOASGN, Expr);
3080 opeq (&GenOASGN, Expr);
3090 void hie0 (ExprDesc *Expr)
3091 /* Parse comma operator. */
3094 while (CurTok.Tok == TOK_COMMA) {
3102 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3103 /* Will evaluate an expression via the given function. If the result is a
3104 * constant, 0 is returned and the value is put in the Expr struct. If the
3105 * result is not constant, ExprLoad is called to bring the value into the
3106 * primary register and 1 is returned.
3110 ExprWithCheck (Func, Expr);
3112 /* Check for a constant expression */
3113 if (ED_IsConstAbs (Expr)) {
3114 /* Constant expression */
3117 /* Not constant, load into the primary */
3118 ExprLoad (Flags, Expr);
3125 void Expression0 (ExprDesc* Expr)
3126 /* Evaluate an expression via hie0 and put the result into the primary register */
3128 ExprWithCheck (hie0, Expr);
3129 ExprLoad (CF_NONE, Expr);
3134 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3135 /* Will evaluate an expression via the given function. If the result is not
3136 * a constant of some sort, a diagnostic will be printed, and the value is
3137 * replaced by a constant one to make sure there are no internal errors that
3138 * result from this input error.
3141 ExprWithCheck (Func, Expr);
3142 if (!ED_IsConst (Expr)) {
3143 Error ("Constant expression expected");
3144 /* To avoid any compiler errors, make the expression a valid const */
3145 ED_MakeConstAbsInt (Expr, 1);
3151 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3152 /* Will evaluate an expression via the given function. If the result is not
3153 * something that may be evaluated in a boolean context, a diagnostic will be
3154 * printed, and the value is replaced by a constant one to make sure there
3155 * are no internal errors that result from this input error.
3158 ExprWithCheck (Func, Expr);
3159 if (!ED_IsBool (Expr)) {
3160 Error ("Boolean expression expected");
3161 /* To avoid any compiler errors, make the expression a valid int */
3162 ED_MakeConstAbsInt (Expr, 1);
3168 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3169 /* Will evaluate an expression via the given function. If the result is not
3170 * a constant numeric integer value, a diagnostic will be printed, and the
3171 * value is replaced by a constant one to make sure there are no internal
3172 * errors that result from this input error.
3175 ExprWithCheck (Func, Expr);
3176 if (!ED_IsConstAbsInt (Expr)) {
3177 Error ("Constant integer expression expected");
3178 /* To avoid any compiler errors, make the expression a valid const */
3179 ED_MakeConstAbsInt (Expr, 1);